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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3618ff515c715ccd0717893e786d5a3330e4b829 | 13256fd739d7fd26e86232d799847d15311ac782 | /munge_data.R | 801d2ce8bc74c92584248da5f99cf6c03be4231a | [
"MIT"
] | permissive | ads40/ancient_shipwrecks | ead40dec21e0dc2e041020e956fb53d5aadd87b4 | 564e8feb62ee332f8b4ee286c5079fcfaed47245 | refs/heads/main | 2023-06-08T12:54:02.628954 | 2021-06-29T11:47:22 | 2021-06-29T11:47:22 | 380,363,420 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,903 | r | munge_data.R | #####################################################################################
#
# Import shipwrecks data into RDS file
#
# Source: Strauss, J. (2013). Shipwrecks Database. Version 1.0.
# Accessed (date): oxrep.classics.ox.ac.uk/databases/shipwrecks_database/
#
#####################################################################################
library(dplyr)
library(readr)
raw_file <- "original_data/StraussShipwrecks/StraussShipwrecks.csv"
col_spec <- cols(
`Wreck ID` = col_double(),
`Strauss ID` = col_double(),
Name = col_character(),
`Parker Number` = col_character(),
`Sea area` = col_character(),
Country = col_character(),
Region = col_character(),
Latitude = col_double(),
Longitude = col_double(),
`Min depth` = col_double(),
`Max depth` = col_double(),
Depth = col_character(),
Period = col_character(),
Dating = col_character(),
`Earliest date` = col_double(),
`Latest date` = col_double(),
`Date range` = col_double(),
`Mid point of date range` = col_double(),
Probability = col_double(),
`Place of origin` = col_character(),
`Place of destination` = col_character(),
Reference = col_character(),
Comments = col_character(),
Amphorae = col_logical(),
Marble = col_logical(),
`Columns etc` = col_logical(),
Sarcophagi = col_logical(),
Blocks = col_logical(),
`Marble type` = col_character(),
`Other cargo` = col_character(),
`Hull remains` = col_character(),
`Shipboard paraphernalia` = col_character(),
`Ship equipment` = col_character(),
`Estimated tonnage` = col_double(),
`Amphora type` = col_character()
)
df <- read_csv(raw_file, col_types = col_spec) %>%
rename_with(~ tolower(gsub(" ", "_", .x, fixed = TRUE)))
# RDS is the better choice: one object per file, and you assign the assign the result of
# `readRDS` to a name of your choosing.
saveRDS(df, "processed_data/shipwrecks.RDS")
|
a4201fe0b8198ecc31e551b1c66ad7ccc4c3606c | 48fb9e67b2e7835cea7d6fc4844284b05a3df6b6 | /man/ResidualFitIndex-class.Rd | 7610084a6f3d0b064775ebcde6969319a4c36359 | [] | no_license | tmatta/glvmfit | c8bbf66f5254a173b4bb5c3b13a73c8e6b6b8876 | f680da080df83dce249aa7739469df14e2837d2c | refs/heads/master | 2023-08-21T03:07:08.002200 | 2021-10-15T13:17:26 | 2021-10-15T13:17:26 | 289,073,745 | 0 | 0 | null | 2021-08-05T00:30:58 | 2020-08-20T17:57:31 | R | UTF-8 | R | false | true | 553 | rd | ResidualFitIndex-class.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/class_ResidualFitIndex.R
\docType{class}
\name{ResidualFitIndex-class}
\alias{ResidualFitIndex-class}
\title{An S4 class to represent a residual fit indices.}
\description{
An S4 class to represent a residual fit indices.
}
\section{Slots}{
\describe{
\item{\code{type}}{A length-one numeric vector}
\item{\code{resid}}{A length-one numeric vector}
\item{\code{ssr}}{A length-one numeric vector}
\item{\code{size}}{A length-one numeric vector}
\item{\code{index}}{}
}}
|
82980a606afa14cf2cd6b8919e8cdc27ee7d7445 | 62ec89b6d425b18ff1ff5be2b9649785282d7865 | /inst/snippets/Example6.15b.R | 5cc1f93d3b07bfb314d413e13b496e8375e7f2b2 | [] | no_license | klaassenj/Lock5withR | 8cf9bab45ba1d87db77713b8c9b6826b663363c3 | f2773d9f828b72882ed1c4d6b3b2e539a3b3b24a | refs/heads/master | 2023-08-02T15:20:09.975771 | 2018-03-14T22:48:09 | 2018-03-14T22:48:09 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 172 | r | Example6.15b.R | Boot.Rent <- do(1000) * mean( ~ Rent, data = resample(ManhattanApartments))
head(Boot.Rent, 3)
favstats( ~ mean, data = Boot.Rent)
cdata( ~ mean, 0.95, data = Boot.Rent)
|
c6f0e38c569996b148c858ac38212202d25010fc | d62d9ea2f6aa749fa48455bddbd3208279ce6449 | /tests/testthat/test-load-fgs.R | dcd078cbe13b89f10bfaeba1d4169c12820d4a05 | [] | no_license | jporobicg/atlantistools | 3bffee764cca1c3d8c7a298fd3a0b8b486b7957e | 75ea349fe21435e9d15e8d12ac8060f7ceef31a2 | refs/heads/master | 2021-01-12T03:06:55.821723 | 2017-05-26T04:03:33 | 2017-05-26T04:03:33 | 78,160,576 | 1 | 0 | null | 2017-05-25T23:35:23 | 2017-01-06T00:51:21 | R | UTF-8 | R | false | false | 626 | r | test-load-fgs.R | context("load_fgs with setas sample files")
d <- system.file("extdata", "setas-model-new-trunk", package = "atlantistools")
file <- file.path(d, "SETasGroupsDem_NoCep.csv")
test_that("test format of species names", {
expect_is(load_fgs(file)$Name, "character")
expect_is(load_fgs(file)$Code, "character")
})
test_that("test file dimensions", {
expect_equal(dim(load_fgs(file))[1], 8)
expect_equal(dim(load_fgs(file))[2], 25)
})
test_that("test acronym extractions", {
expect_equal(get_nonage_acronyms(file), c("CEP", "BML", "PL", "DL", "DR", "DC"))
expect_equal(get_fish_acronyms(file), c("FPS", "FVS"))
})
|
06fc9328c2305d794892330227b367e9bf0b186a | 2784cf4d05bfbc81f9b8530949482b8883c99bb7 | /R_Scripts/PSO/comparing_symmetric_trinomials.R | 1e492b121e1d46bc6172b5da2aeeafdb65ef31cf | [] | no_license | adityas16/FirstRepository | b7c8f917b844de330249d2bda132ff0e1d68e7df | 7195d5e884a4322c7a77d9a603b4ae25a652f03c | refs/heads/master | 2022-12-23T04:53:09.773446 | 2021-11-01T21:44:53 | 2021-11-01T21:44:53 | 27,124,026 | 0 | 0 | null | 2022-12-08T01:10:49 | 2014-11-25T12:10:52 | Jupyter Notebook | UTF-8 | R | false | false | 423 | r | comparing_symmetric_trinomials.R | na=227
na1=57
na_minus1=52
nb=212
nb1=39
nb_minus1=42
mu_1 = (na1+nb1)/(na+nb)
mu_minus1 = (na_minus1+nb_minus1)/(na+nb)
mu=mu_1 - mu_minus1
pa1=na1/na
pa_minus1= na_minus1/na
var_a =((pa1*(1-pa1)) + (pa_minus1*(1- pa_minus1)))/na
pb1=nb1/nb
pb_minus1= nb_minus1/nb
var_b =(pb1*(1-pb1) + pb_minus1*(1- pb_minus1))/nb
xa=(pa1 - pa_minus1)
xb=(pb1 - pb_minus1)
df= na+nb
z=(xa-xb)/sqrt(var_a + var_b)
(1-pnorm(z))
|
4aaf19a4cd7d196d3e59e918ea5d29118be89c18 | 4a227a164b1073b1b1ed4d91a94b5db721f2ff75 | /rr_gop_simulation/codes/2b_generalized_op_simulation.R | 9b99f136fa5d49e9b1f16a7dfc9ef15ef8590aba | [] | no_license | placeboo/Extending-Odds-Product-Model-to-Categorical-Treatment | 61a1cc36a4e91cc066331474a1859c0a9e1b546a | ce6a100cb19938104b1eb45d07aa418c79fecb55 | refs/heads/master | 2020-04-23T18:40:20.726974 | 2019-06-11T07:35:20 | 2019-06-11T07:35:20 | 171,375,570 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 2,231 | r | 2b_generalized_op_simulation.R | # in 2_generalized_op_simulation, for small sample size (n=100),
# there is report for the sd when uisng optimHess.
# this file for n=100, have sd use close function for Hessian matrix
rm(list = ls())
args = commandArgs(TRUE)
seed = as.numeric(args[[1]])
library(brm)
source("functions/generalized_op.R")
source("functions/var.R")
alpha_true = cbind(c(-0.5,1),c(0.5, 1.5))
beta_true = c(1, -0.5)
sample_size = 100
st=format(Sys.Date(), "%Y-%m-%d")
#beta_true = c(1, -1)
do.one.mle.sim = function(alpha.true, beta.true, sample.size, alpha.start, beta.start, max.step=10^5, thres=10^-5){
# generate data
#print(max.step)
v1 = rep(1, sample.size)
v2 = runif(sample.size, -2, 2)
va = cbind(v1, v2)
vb = va
nz = ncol(alpha.start) + 1
z = sample(x = c(0:(nz-1)), size = sample.size, replace = T)
z = as.factor(z)
ny = sample.size
logRR.mat = va %*% alpha.true
logOP.mat = vb %*% beta.true
prob.mat = matrix(NA, nrow = ny, nz)
for(i in 1:ny){
prob.mat[i,] = getProbScalarRR_v2(logRR.mat[i,], logOP.mat[i])
}
y = rep(0, sample.size)
for(i in 1:nz){
y[z == i-1] = rbinom(length(which(z==i-1)), 1, prob.mat[z==i-1,i])
}
# find the MLE
mle = max.likelihood.v3(y, z, va, vb, alpha.start, beta.start, max.step, thres)
# sd using close function
sd2 = sqrt(rr.gop.var(y, z, va, vb, alpha=mle[[1]], beta = mle[[2]]))
mle.mat = cbind(mle[[1]], mle[[2]], c(mle[[3]], mle[[4]]), mle[[5]], sd2[,-3])
colnames(mle.mat) = c(paste("alpha", c(1: (nz-1)), sep = ""), "beta", "cnverg_logl",
paste("alpha", c(1: (nz-1)), "_sd", sep = ""),
paste("alpha", c(1: (nz-1)), "_sd2", sep = ""))
return(mle.mat)
}
N_sim = 100
set.seed(seed)
mle.mat = replicate(N_sim, do.one.mle.sim(alpha.true = alpha_true, beta.true = beta_true, sample.size = sample_size, alpha.start = matrix(0,2,2), beta.start = c(0, 0), max.step =500, thres=10^-4))
# save simulation results
filename = paste("rr_gop_simulation/data4/","SampleSize", sample_size,"_", "Seed", seed, "_", st, ".Rdata", sep = "")
save(file = filename, mle.mat)
|
9744c5cc8f7bd2eac6298751fb4ac5cd14345c86 | 1dc2e1570e89f438ffa2dbc853d236588ea39139 | /pvalue.R | d1bef3e52e814e79f37173141216801b4a3fcbf5 | [] | no_license | lish2/esrd_microbiome | e1c012d485576687d5288d960e47cc4019215e4f | 412124ba934f323614178553b66e51c35199fb03 | refs/heads/main | 2023-08-16T10:07:00.005026 | 2021-10-12T03:55:46 | 2021-10-12T03:55:46 | 415,810,548 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,762 | r | pvalue.R |
#-------------------------
# 分组的菌株含量差异
#-------------------------
library(ggplot2)
library(vegan)
rm(list=ls())
result = rbind()
sample_map = read.table("../../00.data/mapping.file",sep="\t", header=T, check.names=F)
dt = read.table("../00.data/mag.clust.profile", sep="\t", header=T, check.names = F,row.names=1)
region = c("BJ", "SH")[2] # 在这边改变地域
sample_map = sample_map[which(sample_map$protopathy !="na" & sample_map$group2 == region & sample_map$group3 != "CKD"),]
dt = dt[,sample_map$sample]
grps = unique(sample_map$protopathy)
com = t(combn(grps,2))
nspecies = nrow(dt)
names = rownames(dt)
for (n in 1:nspecies){
temp_dt = dt[n,]
for(c in 1:nrow(com)){
g1 = com[c,1]
g2 = com[c,2]
g1s = sample_map[which(sample_map$protopathy == g1),1]
g2s = sample_map[which(sample_map$protopathy == g2),1]
dt1 = as.matrix(temp_dt[,g1s])
dt2 = as.matrix(temp_dt[,g2s])
m1 = mean(dt1)
m2 = mean(dt2)
p = wilcox.test(dt1,dt2)$p.value
temp_result = data.frame(name = names[n],g1=g1, g2=g2,mean1 = m1, mean2=m2,pvalue=p)
result = rbind(result, temp_result)
}
}
write.table(result, paste(region, "pvalue.csv", sep=""), sep=",", row.names=F)
#write.table(fdrtool(as.matrix(read.table("clipboard", sep="\t"))[,1], stat='pvalue')$qval, "clipboard-128",sep="\t", row.names=F,col.names = F)
#-------------------------
# 上海 分组的菌株含量差异
#-------------------------
library(ggplot2)
library(vegan)
rm(list=ls())
sample_map = read.table("../../00.data/mapping.file",sep="\t", header=T, check.names=F)
dt = read.table("../../00.data/new_mag.clust.profile.rename", sep="\t", header=T, check.names = F,row.names=1)
dt = dt/colSums(dt)*100
sample_map = sample_map[which(sample_map$group2 %in% c("SH")),]
# 哪个分组进行比较
group = 'group4'
dt = dt[,sample_map$new_sample]
grps = unique(sample_map[,group])
com = t(combn(grps,2))
nspecies = nrow(dt)
names = rownames(dt)
result = rbind()
for (n in 1:nspecies){
temp_dt = dt[n,]
for(c in 1:nrow(com)){
g1 = com[c,1]
g2 = com[c,2]
g1s = sample_map[which(sample_map[,group] == g1),'new_sample']
g2s = sample_map[which(sample_map[,group] == g2),'new_sample']
dt1 = as.matrix(temp_dt[,g1s])
dt2 = as.matrix(temp_dt[,g2s])
c1 = sum(dt1 != 0 )
c2 = sum(dt2 != 0)
m1 = mean(dt1)
m2 = mean(dt2)
p = wilcox.test(dt1,dt2)$p.value
temp_result = data.frame(name = names[n],g1=g1, g2=g2,mean1 = m1, mean2=m2,pvalue=p, count1=c1, count2= c2)
result = rbind(result, temp_result)
}
}
write.table(result, paste("SH", ".new_sample_group4.pvalue.csv", sep=""), sep=",", row.names=F)
|
c4da28cb1a787cbdb4e6447b18287404e974024a | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/pracma/examples/clenshaw_curtis.Rd.R | 91ab3ad0093e04a4ea71b621aefdc1156e0eeeec | [] | 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 | 368 | r | clenshaw_curtis.Rd.R | library(pracma)
### Name: clenshaw_curtis
### Title: Clenshaw-Curtis Quadrature Formula
### Aliases: clenshaw_curtis
### Keywords: math
### ** Examples
## Quadrature with Chebyshev nodes and weights
f <- function(x) sin(x+cos(10*exp(x))/3)
## Not run: ezplot(f, -1, 1, fill = TRUE)
cc <- clenshaw_curtis(f, n = 64) #=> 0.0325036517151 , true error > 1.3e-10
|
e531d28354b89206511d55de2fe4d4bf4439aa72 | d2707f7a51274321ca0d87831e356bfaabdd90b6 | /app/src/lightbox.R | 35caf8c3b9ecad4ff4d7f4220d06f721e471e0c8 | [
"Apache-2.0"
] | permissive | t3ta/quovidi_demo | e77f58c492429f949e1f7d342b3f9065e812616a | ddcb9972c8ee83f70e8e2b499030ae5654c20dd6 | refs/heads/master | 2023-02-20T12:25:57.289225 | 2021-01-20T13:43:53 | 2021-01-20T13:43:53 | 330,365,029 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,062 | r | lightbox.R |
lightbox_gallery <- function(df, gallery, display = "block", path = "img", width = "50%") {
tags$div(
style = sprintf("display: %s;", display),
tagList(
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "lightbox-2.10.0/lightbox.min.css"),
tags$link(rel = "stylesheet", type = "text/css", href = "styles.css")
),
tags$div(
class = "card-deck",
lapply(seq_len(nrow(df)), function(i) {
tags$div(
`data-type` = "template", class = "card",
tags$a(
id = df$key[i],
href = paste0(path, "/", df$src[i]),
`data-lightbox` = gallery, # this identifies gallery group
`data-title` = df$key[i],
tags$img(
class = "card-img-top",
src = paste0(path, "/", df$src[i]),
width = width,
height = "auto"
)
)
)
})
),
includeScript("www/lightbox-2.10.0/lightbox.min.js")
)
)
}
|
cf09edfcaebd056d96bbbe274104eb1a5c1b5c94 | 3431d8517624ef035f7bd063d215b3c640cbcd40 | /R/bbase.os.R | f9c14dc45117055f9fdd6f1a695b34e29b693e31 | [] | no_license | cran/AROC | f97a8479f3f3218ce919170cb632dee45e532b43 | 8488b3ab91877bc9dc520ec2f82a4c62af93d6ea | refs/heads/master | 2022-03-21T18:38:04.882962 | 2022-02-21T12:30:22 | 2022-02-21T12:30:22 | 136,818,648 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 204 | r | bbase.os.R | bbase.os <-
function(x, K, bdeg = 3, eps = 1e-5, intercept = TRUE) {
# Using the function bs
B <- bs(x, degree = bdeg, df = K + bdeg, intercept = intercept)
#class(B) <- c("bbase.os", "matrix")
B
}
|
a54a256331c73f760ebaf7055288db75f479eee1 | e75b125413f890a51d178e7729f59b3e4caf77d6 | /man/xnormalize_scData.Rd | 1ae0832903503a15db308be86049b61f7603bd16 | [] | no_license | cran/scSorter | 54b675640cc4428d007b248377dbb83383fb6ea0 | 873c1c3308e5d42cf047384ff45af676b42ec38a | refs/heads/master | 2023-03-25T22:41:17.705873 | 2021-03-17T05:40:02 | 2021-03-17T05:40:02 | 292,345,928 | 0 | 1 | null | null | null | null | UTF-8 | R | false | true | 560 | rd | xnormalize_scData.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utilities_temp.R
\name{xnormalize_scData}
\alias{xnormalize_scData}
\title{Normalize scRNA-seq Data}
\usage{
xnormalize_scData(expr)
}
\arguments{
\item{expr}{A matrix of input scRNA-seq data. Rows correspond to genes and columns correpond to cells.}
}
\value{
A matrix of normalized expression data.
}
\description{
Normalize scRNA-seq data. Please only use this function when you do not have access to Seurat package. More details are available in the vignette of this package.
}
|
68155f036d970a8b781df8274308952d581247b8 | 112104780212d9c7f8da1355704493b35b076bc8 | /source/nn.R | ac7c65811e5fca7963399db66ce6db525f652735 | [] | no_license | arildsd/ML-FIFA19-Models | 8bdc180b5d7744842155784aaae1ee41f788ec8d | 285f44dee1161355ef17c9c8eaec04bd24fdc8e0 | refs/heads/master | 2020-05-30T08:24:15.698187 | 2019-06-23T21:38:36 | 2019-06-23T21:38:36 | 189,620,818 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 548 | r | nn.R | # File path to the data
DATA_FILE_PATH = "../data/processed.csv"
# Load the pre-processed data
df = read.csv(DATA_FILE_PATH)
# Normalize the data
normalize <- function(x) {
return ((x - min(x)) / (max(x) - min(x)))
}
maxmindf <- as.data.frame(lapply(df, normalize))
x = model.matrix(value~., maxmindf)[,-1]
y = df$value
set.seed(489)
train = sample(1:nrow(x), nrow(x)/2)
test = (-train)
ytest = y[test]
library(neuralnet)
nn <- neuralnet(y ~ x,data=train, hidden=c(2,1), linear.output=TRUE, threshold=0.01)
plot(nn)
nn$result.matrix
|
0745c0401d3378031109afbc35b8788c697cca08 | b8841bf56594f65fe13115b7f8318b97c9dddb1f | /ch_distributions_oi_biostat/figures/normApproxToBinomFail/normApproxToBinomFail.R | de2252fb90c2c6ee05790ee8cbec5ecaa14df1b5 | [] | no_license | OI-Biostat/oi_biostat_text | 5cdab8191714beef6a67d61d1f69982e4d8c13aa | a333893cffe830b8ce1e31d9226a9a50906605e4 | refs/heads/master | 2023-05-28T12:33:51.243348 | 2022-11-30T20:59:44 | 2022-11-30T20:59:44 | 281,164,408 | 7 | 7 | null | 2022-11-30T21:02:43 | 2020-07-20T16:06:49 | TeX | UTF-8 | R | false | false | 680 | r | normApproxToBinomFail.R | library(openintro)
data(COL)
k <- 0:400
p <- 0.2
n <- 400
myPDF('normApproxToBinomFail.pdf', 7.5, 2.25,
mar = c(1.7, 1, 0.1, 1),
mgp = c(2.2, 0.6, 0),
tcl = -0.35)
X <- seq(40, 120, 0.01)
Y <- dnorm(X, 80, 8)
plot(X, Y,
type = "l",
xlim = c(55, 105),
axes = FALSE,
xlab = "",
ylab = "")
polygon(c(69, 69, 71, 71),
dnorm(c(-1000, 69, 71, -1000), 80, 8),
col = COL[1])
polygon(rep(c(67.9, 69, 70, 71.1), rep(2, 4)) + 0.5,
dbinom(c(-1000, 69, 69, 70, 70, 71, 71, -1000), 400, .2),
border = COL[4],
lwd = 2)
axis(1)
axis(1,
1:200,
rep("", 200),
tcl = -0.12)
abline(h = 0)
dev.off()
|
ad67037c314ec58c064a766b598ec2836765bbc3 | c8af18505a9c09ad7226d7ca16bb9cd3dc921896 | /lmIdxTest.R | 5518d364021c5dfdce3680499e2e4d6772bc436a | [] | no_license | investparty/initPortfolio | 434235e42628cb47e5ffa56d68b0d202b8380429 | b36253e9c9c6fe171dbdedbbb48b5397eceedb3c | refs/heads/master | 2021-01-22T18:14:44.851469 | 2015-08-24T04:21:21 | 2015-08-24T04:21:21 | 40,949,154 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,403 | r | lmIdxTest.R | #load quotes
load("C:/Users/Danil/Documents/investparty/data/quotes.RData")
#prepare weeks data
weekRets <- lapply(quotes, function(x){
df <- subset(x, select = c("Date", "ret"))
df <- df[complete.cases(df),]
df$gf <- strftime(df$Date, format = "%W/%Y")
wy <- aggregate(df$ret, by = list(Category = df$gf), FUN = sum)
wy$mean <- aggregate(df$ret, by = list(Category = df$gf), FUN = mean)$x
wy$sd <- aggregate(df$ret, by = list(Category = df$gf), FUN = sd)$x
wy$mean <- c(NA, wy$mean[1:(nrow(wy)-1)])
wy$sd <- c(NA, wy$sd[1:(nrow(wy)-1)])
wy$lag <- c(NA, wy$x[1:(nrow(wy)-1)])
wy <- wy[complete.cases(wy),]
wy$dir <- sign(wy$x)
wy$dir[wy$dir == (-1)] <- 0
wy$week <- as.numeric(substr(wy$Category, 1, 2))
wy$year <- as.numeric(substr(wy$Category, 4, 7))
wy$Category <- NULL
colnames(wy) <- c(attributes(x)$name, "mean", "sd", "lag", "direction", "week", "year")
attributes(wy)$name <- attributes(x)$name
wy <- wy[order(wy$year, wy$week),]
return(wy)
})
names(weekRets) <- sapply(weekRets, function(x){attributes(x)$name})
#load idx
idxname <- "csi"
indx <- read.csv(paste("C:/Users/Danil/Documents/investparty/data/", idxname, ".csv", collapse = "", sep = ""), sep = ";", dec = ",", skip = 1, header = T)
indx$Date <- as.Date(indx$Date, format = "%d.%m.%Y")
indx <- indx[complete.cases(indx),]
indx <- indx[order(indx$Date),]
colnames(indx) <- c("Date", "value")
attributes(indx)$name <- idxname
#select years by idx
years <- unique(format(indx$Date, "%Y"))
#idx modification function
idxfunc <- function(x){mean(x) / sd(x) / length(x)}
#prepare model data
modelData <- lapply(head(years, n = (length(years)-2)), function(year)
{
print(year)
byYears <- t(sapply(weekRets, function(share, idx, y){
learnData <- share[share$year == y,]
if(nrow(learnData) > 0)
{
idxData <- idx[format(idx$Date, "%Y") == as.character(y),]
idxData$week <- as.numeric(strftime(idxData$Date, format = "%W"))
widx <- aggregate(idxData$value, by = list(Category = idxData$week), FUN = idxfunc)
colnames(widx) <- c("week", "value")
widx <- widx[order(widx$week),]
widx$week <- widx$week + 1
weeks <- widx$week
weeks <- learnData$week[learnData$week %in% weeks]
widx <- widx[widx$week %in% weeks,]
learnData <- learnData[learnData$week %in% widx$week,]
learnData$idx <- widx$value
model <- lm(formula(paste(attributes(share)$name, "~idx", collapse = "", sep = "")), subset(learnData, select = c(attributes(share)$name, "idx")))
armodel <- lm(formula(paste(attributes(share)$name, "~idx+lag", collapse = "", sep = "")), subset(learnData, select = c(attributes(share)$name, "idx", "lag")))
#test
y <- y + 1
testData <- share[share$year == y,]
idxData <- idx[format(idx$Date, "%Y") == as.character(y),]
idxData$week <- as.numeric(strftime(idxData$Date, format = "%W"))
widx <- aggregate(idxData$value, by = list(Category = idxData$week), FUN = idxfunc)
colnames(widx) <- c("week", "value")
widx <- widx[order(widx$week),]
widx$week <- widx$week + 1
weeks <- widx$week
weeks <- testData$week[testData$week %in% weeks]
widx <- widx[widx$week %in% weeks,]
testData <- testData[testData$week %in% widx$week,]
testData$idx <- widx$value
testData$prediction <- predict(model, subset(testData, select = c("idx")))
modelprob <- sum(sign(testData[,1]) == sign(testData$prediction)) / nrow(testData)
testData$arprediction <- predict(armodel, subset(testData, select = c("idx", "lag")))
armodelprob <- sum(sign(testData[,1]) == sign(testData$arprediction)) / nrow(testData)
return(c(modelprob, armodelprob))
} else
{
return(c(0, 0))
}
}, idx = indx, y = as.numeric(year)))
row.names(byYears) <- names(weekRets)
return(byYears)
})
names(modelData) <- as.numeric(head(years, n = (length(years)-2)))
#aggregate results
idxModel <- t(sapply(c(1:length(quotes)), function(x){
m <- mean(sapply(modelData, function(r){return(r[x,1])}), na.rm = T)
arm <- mean(sapply(modelData, function(r){return(r[x,2])}), na.rm = T)
return(c(m, arm))
}))
colnames(idxModel) <- c("idxModel", "arModel")
rownames(idxModel) <- names(weekRets)
#save results
write.table(idxModel, paste("C:/Users/Danil/Documents/investparty/tests/", idxname, ".csv", collapse = "", sep = ""), sep = ";", dec = ",")
|
2ef69df99469118ca0d191f01f02c53c4122fdf9 | 6a28ba69be875841ddc9e71ca6af5956110efcb2 | /Operations_Research:_An_Introduction_by_Hamdy_A_Taha/CH5/EX5.3.1/5.3.1.R | b223424d0769f6511f26a1775d8c86e31fcc9324 | [] | permissive | FOSSEE/R_TBC_Uploads | 1ea929010b46babb1842b3efe0ed34be0deea3c0 | 8ab94daf80307aee399c246682cb79ccf6e9c282 | refs/heads/master | 2023-04-15T04:36:13.331525 | 2023-03-15T18:39:42 | 2023-03-15T18:39:42 | 212,745,783 | 0 | 3 | MIT | 2019-10-04T06:57:33 | 2019-10-04T05:57:19 | null | UTF-8 | R | false | false | 567 | r | 5.3.1.R | ##Chapter 5 : Transportation Model and its Variant
##Example 3-1 : Page 207
costs <- matrix (c(10,2,20,11,12,7,9,20,4,14,16,18), 3, 4,byrow = T)
#Constraints 1,2 & 3 are row constraints as they corresponds to rows of transportation tableau
row.signs <-rep("=",3)
row.rhs <-c(15,25,10)
#Constraints 4 & 5 are coloumn constraints as they corresponds to coloumns of transportation tableau
col.signs <-rep("=",4)
col.rhs <-c(5,15,15,15)
library(lpSolve)
solution <- lp.transport (costs, "min", row.signs, row.rhs, col.signs, col.rhs)
solution$objval
solution$solution
|
d1d64d30b85dc39664bcfe8c93eb96f38addccc0 | dd1a32589e25774ae0b791faaeb48e9341dc7b23 | /plot4.R | 96eaa3cc9b179c76ff8025ad31673072c9c1bcee | [] | no_license | avindeni/ExData_Plotting1 | d379eca8b7e2aba98da5040a09f6ef4519e7c6da | 8fc27148117ee581776fd65786f16f7c8690c628 | refs/heads/master | 2021-01-24T06:57:45.512231 | 2017-06-04T22:20:47 | 2017-06-04T22:20:47 | 93,330,012 | 0 | 0 | null | 2017-06-04T17:28:42 | 2017-06-04T17:28:42 | null | UTF-8 | R | false | false | 2,101 | r | plot4.R | plot4 <- function() {
#power<-read.table("household_power_consumption.csv",sep=";",head=TRUE)
jpeg('plot4.jpg')
par(mfrow = c(2,2))
date_power<-power[which(power$Date=="1/2/2007" | power$Date=="2/2/2007"),]
# plot 1
global_power<-date_power$Global_active_power
global_power<-as.vector(global_power)
remove <- c("?")
clean_power<-global_power [! global_power %in% remove]
Clean_power<-as.numeric(clean_power)
plot(Clean_power,type="l",xaxt="n",xlab="",ylab="Global Active Power")
ticks<-c("Thu","Fri","Sat")
axis(1,at=day_ticks,labels=ticks)
# plot 2
voltage <- date_power$Voltage
voltage <- as.vector(voltage)
clean_voltage<-as.numeric(voltage [! voltage %in% remove])
time_power<-date_power$Time
time_power<-as.vector(time_power)
day_ticks<-which(time_power=="00:00:00")
day_ticks<-c(day_ticks,length(time_power))
plot(clean_voltage,xaxt="n",type="l",xlab="datetime",ylab="Voltage")
ticks<-c("Thu","Fri","Sat")
axis(1,at=day_ticks,labels=ticks)
# plot 3
meter1<-as.vector(date_power$Sub_metering_1)
meter2<-as.vector(date_power$Sub_metering_2)
meter3<-as.vector(date_power$Sub_metering_3)
clean_meter1<-as.numeric(meter1 [! meter1 %in% remove])
clean_meter2<-as.numeric(meter2 [! meter2 %in% remove])
clean_meter3<-as.numeric(meter3 [! meter3 %in% remove])
plot(clean_meter1,xaxt="n",type="n",xlab="",ylab="Energy sub metering")
ticks<-c("Thu","Fri","Sat")
axis(1,at=day_ticks,labels=ticks)
points(clean_meter1,col = "black",type="s")
points(clean_meter2,col = "red",type="s")
points(clean_meter3,col = "blue",type="s")
legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red","blue"),lty=c(1,1))
# plot 4
global_repower<-date_power$Global_reactive_power
global_repower<-as.vector(global_repower)
remove <- c("?")
clean_repower<-global_repower [! global_repower %in% remove]
Clean_repower<-as.numeric(clean_repower)
plot(Clean_repower,type="s",xaxt="n",xlab="datetime",ylab="Global_rective_power")
ticks<-c("Thu","Fri","Sat")
axis(1,at=day_ticks,labels=ticks)
dev.off()
} |
32927f28ae28cbdf1fd2302622baad1e900fd7fc | edf45e446d8d40398bdef3d93af700b40b240be2 | /scripts/sketches.R | 84103be211ee714ed4c71ca7e40e568176d5bf2f | [
"MIT"
] | permissive | uschiLaa/burning-sage | 6eb9c5f45c05c0565c7c77c112b85341e222139d | 9bfa115a8aeca3ed73dbdd1007a09898b8ce3e42 | refs/heads/master | 2023-06-25T11:16:20.284430 | 2021-07-27T07:44:29 | 2021-07-27T07:44:29 | 238,853,553 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 1,396 | r | sketches.R | # sketches data
library(dplyr)
library(tourr)
library(here)
library(burningsage)
data("sketches_train")
sk_small <- filter(sketches, word %in% c("banana", "cactus", "crab")) %>%
mutate(word = factor(word, levels = c("banana", "cactus", "crab")))
pal <- RColorBrewer::brewer.pal(3, "Dark2")
col <- pal[as.numeric(as.factor(sk_small$word))]
sk_pca <- prcomp(select(sk_small, -word, -id))
scale2 <- function(x, na.rm = FALSE) (x - mean(x, na.rm = na.rm)) / sd(x, na.rm)
sk_5 <- sk_pca$x[,1:5] %>%
as_tibble() %>%
mutate_all(scale2)
set.seed(1000)
render_gif(
sk_5,
tour_path = grand_tour(),
gif_file = here::here("gifs", "sketches_grand.gif"),
display = display_xy(col=col, axes = "bottomleft"),
rescale = FALSE,
frames = 100
)
set.seed(1000)
render(
sk_5,
tour_path = grand_tour(),
dev = "png",
display = display_xy(col=col, axes = "bottomleft"),
rescale = FALSE,
frames = 100,
here::here("pngs", "sketches_grand-%03d.png")
)
set.seed(1000)
render_gif(
sk_5,
tour_path = grand_tour(),
gif_file = here("gifs", "sketches_sage.gif"),
display = display_sage(col=col, gam=2, axes = "bottomleft"),
rescale = FALSE,
frames = 100
)
set.seed(1000)
render(
sk_5,
tour_path = grand_tour(),
dev = "png",
display = display_sage(col=col, gam=2, axes = "bottomleft"),
rescale = FALSE,
frames = 100,
here::here("pngs", "sketches_sage-%03d.png")
)
|
168ce66492f96c60ba18e2d2ecf9315633b3243c | 2e932fd7d489ce462cb3d333ad4aa66779570745 | /archive/output_BUGS_plots.R | 1a4fbeb16a7e2a659a841cb618a461fa0ee1617c | [] | no_license | Dr-Dong/malaria_evidence_synthesis | 0ed126d2715d8eecc5b148e7e2e3c34619b6b04c | 6481eebdea5d1549aa64b6e59ee34cb484c6fac8 | refs/heads/master | 2020-08-28T02:52:06.718783 | 2019-07-24T17:29:56 | 2019-07-24T17:29:56 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,667 | r | output_BUGS_plots.R |
## posterior predicted: multinomial all categories
plot(colMeans(BUGSoutput$sims.list$prob_pred[,,1]), type = "l", ylim = c(0,1))
lines(colMeans(BUGSoutput$sims.list$prob_pred[,,2]), type = "l", col = "red")
lines(colMeans(BUGSoutput$sims.list$prob_pred[,,3]), type = "l", col = "blue")
lines(colMeans(BUGSoutput$sims.list$prob_pred[,,4]), type = "l", col = "green")
polygon(x = c(1:365, 365:1),
y = c(colMeans(BUGSoutput$sims.list$prob_pred[,,1]) - 1.96*apply(BUGSoutput$sims.list$prob_pred[,,1], 2, sd),
rev(colMeans(BUGSoutput$sims.list$prob_pred[,,1]) + 1.96*apply(BUGSoutput$sims.list$prob_pred[,,1], 2, sd))),
col = transp("aquamarine3",0.2), border = FALSE)
polygon(x = c(1:365, 365:1),
y = c(colMeans(BUGSoutput$sims.list$prob_pred[,,2]) - 1.96*apply(BUGSoutput$sims.list$prob_pred[,,2], 2, sd),
rev(colMeans(BUGSoutput$sims.list$prob_pred[,,2]) + 1.96*apply(BUGSoutput$sims.list$prob_pred[,,2], 2, sd))),
col = transp("green",0.2), border = FALSE)
polygon(x = c(1:365, 365:1),
y = c(colMeans(BUGSoutput$sims.list$prob_pred[,,3]) - 1.96*apply(BUGSoutput$sims.list$prob_pred[,,3], 2, sd),
rev(colMeans(BUGSoutput$sims.list$prob_pred[,,3]) + 1.96*apply(BUGSoutput$sims.list$prob_pred[,,3], 2, sd))),
col = transp("orange",0.2), border = FALSE)
polygon(x = c(1:365, 365:1),
y = c(colMeans(BUGSoutput$sims.list$prob_pred[,,4]) - 1.96*apply(BUGSoutput$sims.list$prob_pred[,,4], 2, sd),
rev(colMeans(BUGSoutput$sims.list$prob_pred[,,4]) + 1.96*apply(BUGSoutput$sims.list$prob_pred[,,4], 2, sd))),
col = transp("yellow",0.2), border = FALSE)
##TEST
## all == 1
colMeans(BUGSoutput$sims.list$prob_pred[,,1]) + colMeans(BUGSoutput$sims.list$prob_pred[,,2]) + colMeans(BUGSoutput$sims.list$prob_pred[,,3]) + colMeans(BUGSoutput$sims.list$prob_pred[,,4])
library(adegenet)
## posterior predicted: summed multinomial as death and fed
plot(colMeans(BUGSoutput$sims.list$predd_pred), type = "l", ylim = c(0,1))
lines(colMeans(BUGSoutput$sims.list$predf_pred), type = "l", col = "red")
polygon(x = c(1:365, 365:1),
y = c(colMeans(BUGSoutput$sims.list$predd_pred) - 1.96*apply(BUGSoutput$sims.list$predd_pred, 2, sd),
rev(colMeans(BUGSoutput$sims.list$predd_pred) + 1.96*apply(BUGSoutput$sims.list$predd_pred, 2, sd))),
# y = c(quantile(BUGSoutput$sims.list$predd_pred, probs = 0.25),
# rev(quantile(BUGSoutput$sims.list$predd_pred, probs = 0.75))),
col = transp("orange",0.2), border = FALSE)
polygon(x = c(1:365, 365:1),
y = c(colMeans(BUGSoutput$sims.list$predf_pred) - 1.96*apply(BUGSoutput$sims.list$predf_pred, 2, sd),
rev(colMeans(BUGSoutput$sims.list$predf_pred) + 1.96*apply(BUGSoutput$sims.list$predf_pred, 2, sd))),
col = transp("aquamarine3",0.2), border = FALSE)
## posterior predicted: binomial death and fed
plot(colMeans(BUGSoutput$sims.list$Yd_pred), type = "l", ylim = c(0,1))
lines(colMeans(BUGSoutput$sims.list$Yf_pred), type = "l", col = "red")
polygon(x = c(1:365, 365:1),
y = c(colMeans(BUGSoutput$sims.list$Yd_pred) - 1.96*apply(BUGSoutput$sims.list$Yd_pred, 2, sd),
rev(colMeans(BUGSoutput$sims.list$Yd_pred) + 1.96*apply(BUGSoutput$sims.list$Yd_pred, 2, sd))),
col = transp("orange",0.2), border = FALSE)
polygon(x = c(1:365, 365:1),
y = c(colMeans(BUGSoutput$sims.list$Yf_pred) - 1.96*apply(BUGSoutput$sims.list$Yf_pred, 2, sd),
rev(colMeans(BUGSoutput$sims.list$Yf_pred) + 1.96*apply(BUGSoutput$sims.list$Yf_pred, 2, sd))),
col = transp("aquamarine3",0.2), border = FALSE)
|
fd4a43d16e9cda2e8605bb0595da1f007c456d96 | 744f59804d8d2b683525cfdaf7e3771988262830 | /get_mzs.R | 326e00d66ecdcbf0e4e5e0728a91ece360b0bedb | [] | no_license | HegemanLab/extra_tools | c197f4b497afc813e03db882b870b44ba6fc4678 | b7c5bf532cd5f7cc3e2bc41c3f8aa0a1a74e98a3 | refs/heads/master | 2021-01-10T17:46:43.905617 | 2018-06-08T21:45:09 | 2018-06-08T21:45:09 | 52,366,758 | 0 | 0 | null | 2018-05-15T03:06:59 | 2016-02-23T14:57:06 | R | UTF-8 | R | false | false | 1,236 | r | get_mzs.R | # Helper script to extract a list of mz values from a list of files
library(xcms)
setwd("C:/Users/Lab/Desktop/Coding_Bits/VanKrevelen")
get_mzs <- function(in_file) {
xraw <- xcmsRaw(in_file)
peak_data <- findPeaks(xraw)
peak_data <- peak_data@.Data
peak_data[, 1]
}
files <- c(
"ACM_Feb6_244-pos.mzXML",
"ACM_Feb6_268-pos.mzXML",
"ACM_Feb6_277-pos.mzXML",
"ACM_Feb6_B2_255-pos.mzXML",
"ACM_Feb6_B2_274-pos.mzXML",
"ACM_Feb6_B3_270-pos.mzXML"
)
mzs <- lapply(files, get_mzs)
lapply(1:length(mzs), function(x){
write.table(mzs[x], file = paste(files[x], '.csv'), col.names = "mzs", row.names = F)
})
output <- unlist(mzs)
setwd("C:/Users/Lab/Desktop/Tissue_Spray_Final/Tri/Input/")
write.table(output, file = "Tri-pos-mzs.txt", row.names = F, col.names = F)
get_both_mzs <- function(in_file) {
xraw <- xcmsRaw(in_file)
peak_data <- findPeaks(xraw)
peak_data <- peak_data@.Data
peak_data[, 1]
}
#Single File
output <- get_mzs("ACM_sept16_T1R3_GL20_method1.mzXML")
setwd("C:/Users/Lab/Desktop")
write.table(output, file = "ACM_sept16_T1R3_GL20_method1.mzXML-mzs.txt", row.names = F, col.names = F)
setwd("C:/Users/Lab/Desktop/Coding_Bits/VanKrevelen")
|
faabc3cf52cdd698f5a82766cc1ddfc44ed89a55 | d4065309f6031e6af1fe91147ca1dc18a559205f | /EasyQC/R/clsPZPLOT7.r | 2a3e3a00580688dc411336c0a10fe2023ba47f53 | [] | no_license | barbarathorslund/warfarin | 3741b85bd580599cde2ba283e23774a7a018c19e | 0ec7779313ad126605a047e44c7485b3a348568e | refs/heads/main | 2023-06-25T22:35:36.441326 | 2021-07-14T18:50:44 | 2021-07-14T18:50:44 | 345,354,658 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,830 | r | clsPZPLOT7.r | setClass("PZPLOT",
representation = representation(
strEqcCommand = "character",
colBeta = "character",
colSe = "character",
colPval = "character",
numPvalOffset = "numeric"
),
prototype = prototype(
strEqcCommand = "",
colBeta = "",
colSe = "",
colPval = "",
numPvalOffset = 0.05
),
contains = c("SPLOT")
)
setGeneric("setPZPLOT", function(object) standardGeneric("setPZPLOT"))
setMethod("setPZPLOT", signature = (object = "PZPLOT"), function(object) {
object@arcdAdd2Plot <- "abline(a=0,b=1,col='grey',lty=1)"
object@numDefaultCex <- 0.3
object@blnGrid <- TRUE
object@strMode <- "subplot"
object@strDefaultColour <- "black"
object@strPlotName <- "PZ"
object@strAxes <- "zeroequal"
object@strPlotName <- "PZ-PLOTS"
aEqcSlotNamesIn = c("colBeta",
"colSe",
"colPval",
"numPvalOffset",
# Inherited SPLOT:
"strDefaultColour",
"numDefaultSymbol",
"numDefaultCex",
"arcdColourCrit",
"astrColour",
"astrColourLegend",
"arcdSymbolCrit",
"anumSymbol",
"astrSymbolLegend",
"arcdCexCrit",
"anumCex",
"strAxes",
"strXlab",
"strYlab",
"strTitle",
#"blnLegend",
"arcdAdd2Plot",
"strMode",
"strFormat",
"rcdExclude",
"numCexAxis",
"numCexLab",
"numWidth",
"numHeight",
"anumParMar",
"anumParMgp",
"strParBty",
"blnGrid",
"strPlotName"
)
#aEcfSlotNamesIn = c("arcdAddCol", "astrAddColNames")
objEqcReader <- EqcReader(object@strEqcCommand,aEqcSlotNamesIn)
for(i in 1:length(objEqcReader@lsEqcSlotsOut)) {
tmpSlot <- names(objEqcReader@lsEqcSlotsOut)[i]
tmpSlotVal <- objEqcReader@lsEqcSlotsOut[[i]]
if(all(!is.na(tmpSlotVal))) slot(object, tmpSlot) <- tmpSlotVal
}
if(object@rcdExclude == "") object@rcdExclude <- paste(object@colPval,">=",object@numPvalOffset, sep="")
else object@rcdExclude <- paste(object@rcdExclude, "|", paste(object@colPval,">=",object@numPvalOffset, sep=""),sep="")
object@rcdSPlotX <- paste("-log10(",object@colPval,")", sep="")
object@rcdSPlotY <- paste("-log10(2*pnorm(abs(",object@colBeta,"/",object@colSe,"),lower.tail=FALSE))", sep="")
if(object@strXlab == "") object@strXlab <- object@rcdSPlotX
if(object@strYlab == "") object@strYlab <- "-log10(P.Zstat)"
return(object)
})
#############################################################################################################################
validPZPLOT <- function(objPZPLOT) {
## Paste validity checks specific for SPLOT
## Pval <-> se
## fileGcSnps exists
## colMarkerGcSnps exists
return(TRUE)
}
PZPLOT.GWADATA.valid <- function(objPZPLOT, objGWA){
if(!(objPZPLOT@colBeta %in% objGWA@aHeader))
stop(paste("EASY ERROR:PZPLOT\n Column colBeta\n",objPZPLOT@colBeta," does not exist in file\n",objGWA@fileInShortName,"\n !!!", sep=""))
if(!(objPZPLOT@colSe %in% objGWA@aHeader))
stop(paste("EASY ERROR:PZPLOT\n Column colSe\n",objPZPLOT@colSe," does not exist in file\n",objGWA@fileInShortName,"\n !!!", sep=""))
if(!(objPZPLOT@colPval %in% objGWA@aHeader))
stop(paste("EASY ERROR:PZPLOT\n Column colPval\n",objPZPLOT@colPval," does not exist in file\n",objGWA@fileInShortName,"\n !!!", sep=""))
}
PZPLOT <- function(strEqcCommand){
## Wrapper for class definition
PZPLOTout <- setPZPLOT(new("PZPLOT", strEqcCommand = strEqcCommand))
validPZPLOT(PZPLOTout)
#ADDCOLout.valid <- validADDCOL(ADDCOLout)
return(PZPLOTout)
#validECF(ECFout)
#return(ECFout)
## Identical:
# ECFin <- new("ECF5", fileECF = fileECFIn)
# ECFout <- setECF5(ECFin)
# return(ECFout)
}
|
82349593fb4ffd05cfdc395ea3ad3b6110a7a239 | 72e8bd721b82c0e8239bf00129dbc1f00f19e2f2 | /testData/r_skeletons/rpart.R | 419f299300aa2777df9041171eead4328a7275e6 | [
"BSD-2-Clause",
"MIT"
] | permissive | yoongkang0122/r4intellij | 59dc560db7a1ea7aead2be8a98bbbba4e4051259 | e1dc26b462f94e3884d07ba5321eefa7263d1ad9 | refs/heads/master | 2021-01-25T09:20:56.708602 | 2017-05-13T05:52:49 | 2017-05-13T05:52:49 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 26,378 | r | rpart.R | ##
## Exported symobls in package `rpart`
##
## Exported package methods
xpred.rpart <- function (fit, xval = 10L, cp, return.all = FALSE)
{
if (!inherits(fit, "rpart"))
stop("Invalid fit object")
method <- fit$method
method.int <- pmatch(method, c("anova", "poisson", "class",
"user", "exp"))
if (method.int == 5L)
method.int <- 2L
Terms <- fit$terms
Y <- fit$y
X <- fit$x
wt <- fit$wt
numresp <- fit$numresp
if (is.null(Y) || is.null(X)) {
m <- fit$model
if (is.null(m)) {
m <- fit$call[match(c("", "formula", "data", "weights",
"subset", "na.action"), names(fit$call), 0L)]
if (is.null(m$na.action))
m$na.action <- na.rpart
m[[1]] <- quote(stats::model.frame)
m <- eval.parent(m)
}
if (is.null(X))
X <- rpart.matrix(m)
if (is.null(wt))
wt <- model.extract(m, "weights")
if (is.null(Y)) {
yflag <- TRUE
Y <- model.extract(m, "response")
offset <- attr(Terms, "offset")
if (method != "user") {
init <- get(paste("rpart", method, sep = "."))(Y,
offset, NULL)
Y <- init$y
numy <- if (is.matrix(Y))
ncol(Y)
else 1L
}
}
else {
yflag <- FALSE
numy <- if (is.matrix(Y))
ncol(Y)
else 1L
}
}
else {
yflag <- FALSE
numy <- if (is.matrix(Y))
ncol(Y)
else 1L
offset <- 0L
}
nobs <- nrow(X)
nvar <- ncol(X)
if (length(wt) == 0)
wt <- rep(1, nobs)
cats <- rep(0, nvar)
xlevels <- attr(fit, "xlevels")
if (!is.null(xlevels))
cats[match(names(xlevels), colnames(X))] <- unlist(lapply(xlevels,
length))
controls <- fit$control
if (missing(cp)) {
cp <- fit$cptable[, 1L]
cp <- sqrt(cp * c(10, cp[-length(cp)]))
cp[1L] <- (1 + fit$cptable[1L, 1L])/2
}
if (length(xval) == 1L) {
xgroups <- sample(rep(1L:xval, length = nobs), nobs,
replace = FALSE)
}
else if (length(xval) == nrow(X)) {
xgroups <- xval
xval <- length(unique(xgroups))
}
else {
if (!is.null(fit$na.action)) {
temp <- as.integer(fit$na.action)
xval <- xval[-temp]
if (length(xval) == nobs) {
xgroups <- xval
xval <- length(unique(xgroups))
}
else stop("Wrong length for 'xval'")
}
else stop("Wrong length for 'xval'")
}
costs <- fit$call$costs
if (is.null(costs))
costs <- rep(1, nvar)
parms <- fit$parms
if (method == "user") {
mlist <- fit$functions
if (yflag) {
init <- if (length(parms) == 0L)
mlist$init(Y, offset, , wt)
else mlist$init(Y, offset, parms, wt)
Y <- init$Y
numy <- init$numy
parms <- init$parms
}
else {
numy <- if (is.matrix(Y))
ncol(Y)
else 1L
init <- list(numresp = numresp, numy = numy, parms = parms)
}
keep <- rpartcallback(mlist, nobs, init)
method.int <- 4L
}
if (is.matrix(Y))
Y <- as.double(t(Y))
else storage.mode(Y) <- "double"
storage.mode(X) <- "double"
storage.mode(wt) <- "double"
temp <- as.double(unlist(parms))
if (length(temp) == 0L)
temp <- 0
pred <- .Call(C_xpred, ncat = as.integer(cats * (!fit$ordered)),
method = as.integer(method.int), as.double(unlist(controls)),
temp, as.integer(xval), as.integer(xgroups), Y, X, wt,
as.integer(numy), as.double(costs), as.integer(return.all),
as.double(cp), as.double(fit$frame[1L, "dev"]), as.integer(numresp))
if (return.all && numresp > 1L) {
temp <- array(pred, dim = c(numresp, length(cp), nrow(X)),
dimnames = list(NULL, format(cp), rownames(X)))
aperm(temp)
}
else matrix(pred, nrow = nrow(X), byrow = TRUE, dimnames = list(rownames(X),
format(cp)))
}
prune <- function (tree, ...)
UseMethod("prune")
meanvar <- function (tree, ...)
UseMethod("meanvar")
plotcp <- function (x, minline = TRUE, lty = 3, col = 1, upper = c("size",
"splits", "none"), ...)
{
dots <- list(...)
if (!inherits(x, "rpart"))
stop("Not a legitimate \"rpart\" object")
upper <- match.arg(upper)
p.rpart <- x$cptable
if (ncol(p.rpart) < 5L)
stop("'cptable' does not contain cross-validation results")
xstd <- p.rpart[, 5L]
xerror <- p.rpart[, 4L]
nsplit <- p.rpart[, 2L]
ns <- seq_along(nsplit)
cp0 <- p.rpart[, 1L]
cp <- sqrt(cp0 * c(Inf, cp0[-length(cp0)]))
if (!"ylim" %in% names(dots))
dots$ylim <- c(min(xerror - xstd) - 0.1, max(xerror +
xstd) + 0.1)
do.call(plot, c(list(ns, xerror, axes = FALSE, xlab = "cp",
ylab = "X-val Relative Error", type = "o"), dots))
box()
axis(2, ...)
segments(ns, xerror - xstd, ns, xerror + xstd)
axis(1L, at = ns, labels = as.character(signif(cp, 2L)),
...)
switch(upper, size = {
axis(3L, at = ns, labels = as.character(nsplit + 1),
...)
mtext("size of tree", side = 3, line = 3)
}, splits = {
axis(3L, at = ns, labels = as.character(nsplit), ...)
mtext("number of splits", side = 3, line = 3)
})
minpos <- min(seq_along(xerror)[xerror == min(xerror)])
if (minline)
abline(h = (xerror + xstd)[minpos], lty = lty, col = col)
invisible()
}
rsq.rpart <- function (x)
{
if (!inherits(x, "rpart"))
stop("Not a legitimate \"rpart\" object")
p.rpart <- printcp(x)
xstd <- p.rpart[, 5L]
xerror <- p.rpart[, 4L]
rel.error <- p.rpart[, 3L]
nsplit <- p.rpart[, 2L]
method <- x$method
if (!method == "anova")
warning("may not be applicable for this method")
plot(nsplit, 1 - rel.error, xlab = "Number of Splits", ylab = "R-square",
ylim = c(0, 1), type = "o")
par(new = TRUE)
plot(nsplit, 1 - xerror, type = "o", ylim = c(0, 1), lty = 2,
xlab = " ", ylab = " ")
legend(0, 1, c("Apparent", "X Relative"), lty = 1:2)
ylim <- c(min(xerror - xstd) - 0.1, max(xerror + xstd) +
0.1)
plot(nsplit, xerror, xlab = "Number of Splits", ylab = "X Relative Error",
ylim = ylim, type = "o")
segments(nsplit, xerror - xstd, nsplit, xerror + xstd)
invisible()
}
post <- function (tree, ...)
UseMethod("post")
prune.rpart <- function (tree, cp, ...)
{
ff <- tree$frame
id <- as.integer(row.names(ff))
toss <- id[ff$complexity <= cp & ff$var != "<leaf>"]
if (length(toss) == 0L)
return(tree)
newx <- snip.rpart(tree, toss)
temp <- pmax(tree$cptable[, 1L], cp)
keep <- match(unique(temp), temp)
newx$cptable <- tree$cptable[keep, , drop = FALSE]
newx$cptable[max(keep), 1L] <- cp
newx$variable.importance <- importance(newx)
newx
}
path.rpart <- function (tree, nodes, pretty = 0, print.it = TRUE)
{
if (!inherits(tree, "rpart"))
stop("Not a legitimate \"rpart\" object")
splits <- labels.rpart(tree, pretty = pretty)
frame <- tree$frame
n <- row.names(frame)
node <- as.numeric(n)
which <- descendants(node)
path <- list()
if (missing(nodes)) {
xy <- rpartco(tree)
while (length(i <- identify(xy, n = 1L, plot = FALSE)) >
0L) {
path[[n[i]]] <- path.i <- splits[which[, i]]
if (print.it) {
cat("\n", "node number:", n[i], "\n")
cat(paste(" ", path.i), sep = "\n")
}
}
}
else {
if (length(nodes <- node.match(nodes, node)) == 0L)
return(invisible())
for (i in nodes) {
path[[n[i]]] <- path.i <- splits[which[, i]]
if (print.it) {
cat("\n", "node number:", n[i], "\n")
cat(paste(" ", path.i), sep = "\n")
}
}
}
invisible(path)
}
rpart <- function (formula, data, weights, subset, na.action = na.rpart,
method, model = FALSE, x = FALSE, y = TRUE, parms, control,
cost, ...)
{
Call <- match.call()
if (is.data.frame(model)) {
m <- model
model <- FALSE
}
else {
indx <- match(c("formula", "data", "weights", "subset"),
names(Call), nomatch = 0L)
if (indx[1] == 0L)
stop("a 'formula' argument is required")
temp <- Call[c(1L, indx)]
temp$na.action <- na.action
temp[[1L]] <- quote(stats::model.frame)
m <- eval.parent(temp)
}
Terms <- attr(m, "terms")
if (any(attr(Terms, "order") > 1L))
stop("Trees cannot handle interaction terms")
Y <- model.response(m)
wt <- model.weights(m)
if (any(wt < 0))
stop("negative weights not allowed")
if (!length(wt))
wt <- rep(1, nrow(m))
offset <- model.offset(m)
X <- rpart.matrix(m)
nobs <- nrow(X)
nvar <- ncol(X)
if (missing(method)) {
method <- if (is.factor(Y) || is.character(Y))
"class"
else if (inherits(Y, "Surv"))
"exp"
else if (is.matrix(Y))
"poisson"
else "anova"
}
if (is.list(method)) {
mlist <- method
method <- "user"
init <- if (missing(parms))
mlist$init(Y, offset, wt = wt)
else mlist$init(Y, offset, parms, wt)
keep <- rpartcallback(mlist, nobs, init)
method.int <- 4L
parms <- init$parms
}
else {
method.int <- pmatch(method, c("anova", "poisson", "class",
"exp"))
if (is.na(method.int))
stop("Invalid method")
method <- c("anova", "poisson", "class", "exp")[method.int]
if (method.int == 4L)
method.int <- 2L
init <- if (missing(parms))
get(paste("rpart", method, sep = "."), envir = environment())(Y,
offset, , wt)
else get(paste("rpart", method, sep = "."), envir = environment())(Y,
offset, parms, wt)
ns <- asNamespace("rpart")
if (!is.null(init$print))
environment(init$print) <- ns
if (!is.null(init$summary))
environment(init$summary) <- ns
if (!is.null(init$text))
environment(init$text) <- ns
}
Y <- init$y
xlevels <- .getXlevels(Terms, m)
cats <- rep(0L, ncol(X))
if (!is.null(xlevels))
cats[match(names(xlevels), colnames(X))] <- unlist(lapply(xlevels,
length))
extraArgs <- list(...)
if (length(extraArgs)) {
controlargs <- names(formals(rpart.control))
indx <- match(names(extraArgs), controlargs, nomatch = 0L)
if (any(indx == 0L))
stop(gettextf("Argument %s not matched", names(extraArgs)[indx ==
0L]), domain = NA)
}
controls <- rpart.control(...)
if (!missing(control))
controls[names(control)] <- control
xval <- controls$xval
if (is.null(xval) || (length(xval) == 1L && xval == 0L) ||
method == "user") {
xgroups <- 0L
xval <- 0L
}
else if (length(xval) == 1L) {
xgroups <- sample(rep(1L:xval, length = nobs), nobs,
replace = FALSE)
}
else if (length(xval) == nobs) {
xgroups <- xval
xval <- length(unique(xgroups))
}
else {
if (!is.null(attr(m, "na.action"))) {
temp <- as.integer(attr(m, "na.action"))
xval <- xval[-temp]
if (length(xval) == nobs) {
xgroups <- xval
xval <- length(unique(xgroups))
}
else stop("Wrong length for 'xval'")
}
else stop("Wrong length for 'xval'")
}
if (missing(cost))
cost <- rep(1, nvar)
else {
if (length(cost) != nvar)
stop("Cost vector is the wrong length")
if (any(cost <= 0))
stop("Cost vector must be positive")
}
tfun <- function(x) if (is.matrix(x))
rep(is.ordered(x), ncol(x))
else is.ordered(x)
labs <- sub("^`(.*)`$", "\\1", attr(Terms, "term.labels"))
isord <- unlist(lapply(m[labs], tfun))
storage.mode(X) <- "double"
storage.mode(wt) <- "double"
temp <- as.double(unlist(init$parms))
if (!length(temp))
temp <- 0
rpfit <- .Call(C_rpart, ncat = as.integer(cats * (!isord)),
method = as.integer(method.int), as.double(unlist(controls)),
temp, as.integer(xval), as.integer(xgroups), as.double(t(init$y)),
X, wt, as.integer(init$numy), as.double(cost))
nsplit <- nrow(rpfit$isplit)
ncat <- if (!is.null(rpfit$csplit))
nrow(rpfit$csplit)
else 0L
if (nsplit == 0L)
xval <- 0L
numcp <- ncol(rpfit$cptable)
temp <- if (nrow(rpfit$cptable) == 3L)
c("CP", "nsplit", "rel error")
else c("CP", "nsplit", "rel error", "xerror", "xstd")
dimnames(rpfit$cptable) <- list(temp, 1L:numcp)
tname <- c("<leaf>", colnames(X))
splits <- matrix(c(rpfit$isplit[, 2:3], rpfit$dsplit), ncol = 5L,
dimnames = list(tname[rpfit$isplit[, 1L] + 1L], c("count",
"ncat", "improve", "index", "adj")))
index <- rpfit$inode[, 2L]
nadd <- sum(isord[rpfit$isplit[, 1L]])
if (nadd > 0L) {
newc <- matrix(0L, nadd, max(cats))
cvar <- rpfit$isplit[, 1L]
indx <- isord[cvar]
cdir <- splits[indx, 2L]
ccut <- floor(splits[indx, 4L])
splits[indx, 2L] <- cats[cvar[indx]]
splits[indx, 4L] <- ncat + 1L:nadd
for (i in 1L:nadd) {
newc[i, 1L:(cats[(cvar[indx])[i]])] <- -as.integer(cdir[i])
newc[i, 1L:ccut[i]] <- as.integer(cdir[i])
}
catmat <- if (ncat == 0L)
newc
else {
cs <- rpfit$csplit
ncs <- ncol(cs)
ncc <- ncol(newc)
if (ncs < ncc)
cs <- cbind(cs, matrix(0L, nrow(cs), ncc - ncs))
rbind(cs, newc)
}
ncat <- ncat + nadd
}
else catmat <- rpfit$csplit
if (nsplit == 0L) {
frame <- data.frame(row.names = 1L, var = "<leaf>", n = rpfit$inode[,
5L], wt = rpfit$dnode[, 3L], dev = rpfit$dnode[,
1L], yval = rpfit$dnode[, 4L], complexity = rpfit$dnode[,
2L], ncompete = 0L, nsurrogate = 0L)
}
else {
temp <- ifelse(index == 0L, 1L, index)
svar <- ifelse(index == 0L, 0L, rpfit$isplit[temp, 1L])
frame <- data.frame(row.names = rpfit$inode[, 1L], var = tname[svar +
1L], n = rpfit$inode[, 5L], wt = rpfit$dnode[, 3L],
dev = rpfit$dnode[, 1L], yval = rpfit$dnode[, 4L],
complexity = rpfit$dnode[, 2L], ncompete = pmax(0L,
rpfit$inode[, 3L] - 1L), nsurrogate = rpfit$inode[,
4L])
}
if (method.int == 3L) {
numclass <- init$numresp - 2L
nodeprob <- rpfit$dnode[, numclass + 5L]/sum(wt)
temp <- pmax(1L, init$counts)
temp <- rpfit$dnode[, 4L + (1L:numclass)] %*% diag(init$parms$prior/temp)
yprob <- temp/rowSums(temp)
yval2 <- matrix(rpfit$dnode[, 4L + (0L:numclass)], ncol = numclass +
1L)
frame$yval2 <- cbind(yval2, yprob, nodeprob)
}
else if (init$numresp > 1L)
frame$yval2 <- rpfit$dnode[, -(1L:3L), drop = FALSE]
if (is.null(init$summary))
stop("Initialization routine is missing the 'summary' function")
functions <- if (is.null(init$print))
list(summary = init$summary)
else list(summary = init$summary, print = init$print)
if (!is.null(init$text))
functions <- c(functions, list(text = init$text))
if (method == "user")
functions <- c(functions, mlist)
where <- rpfit$which
names(where) <- row.names(m)
ans <- list(frame = frame, where = where, call = Call, terms = Terms,
cptable = t(rpfit$cptable), method = method, parms = init$parms,
control = controls, functions = functions, numresp = init$numresp)
if (nsplit)
ans$splits = splits
if (ncat > 0L)
ans$csplit <- catmat + 2L
if (nsplit)
ans$variable.importance <- importance(ans)
if (model) {
ans$model <- m
if (missing(y))
y <- FALSE
}
if (y)
ans$y <- Y
if (x) {
ans$x <- X
ans$wt <- wt
}
ans$ordered <- isord
if (!is.null(attr(m, "na.action")))
ans$na.action <- attr(m, "na.action")
if (!is.null(xlevels))
attr(ans, "xlevels") <- xlevels
if (method == "class")
attr(ans, "ylevels") <- init$ylevels
class(ans) <- "rpart"
ans
}
rpart.exp <- function (y, offset, parms, wt)
{
if (!inherits(y, "Surv"))
stop("Response must be a 'survival' object - use the 'Surv()' function")
ny <- ncol(y)
n <- nrow(y)
status <- y[, ny]
if (any(y[, 1L] <= 0))
stop("Observation time must be > 0")
if (all(status == 0))
stop("No deaths in data set")
time <- y[, ny - 1L]
dtimes <- sort(unique(time[status == 1]))
temp <- .Call(C_rpartexp2, as.double(dtimes), as.double(.Machine$double.eps))
dtimes <- dtimes[temp == 1]
if (length(dtimes) > 1000)
dtimes <- quantile(dtimes, 0:1000/1000)
itable <- c(0, dtimes[-length(dtimes)], max(time))
drate2 <- function(n, ny, y, wt, itable) {
time <- y[, ny - 1L]
status <- y[, ny]
ilength <- diff(itable)
ngrp <- length(ilength)
index <- unclass(cut(time, itable, include.lowest = TRUE))
itime <- time - itable[index]
if (ny == 3L) {
stime <- y[, 1L]
index2 <- unclass(cut(stime, itable, include.lowest = TRUE))
itime2 <- stime - itable[index2]
}
tab1 <- table(index)
temp <- rev(cumsum(rev(tab1)))
pyears <- ilength * c(temp[-1L], 0) + tapply(itime, index,
sum)
if (ny == 3L) {
tab2 <- table(index2, levels = 1:ngrp)
temp <- rev(cumsum(rev(tab2)))
py2 <- ilength * c(0, temp[-ngrp]) + tapply(itime2,
index2, sum)
pyears <- pyears - py2
}
deaths <- tapply(status, index, sum)
rate <- deaths/pyears
rate
}
rate <- drate2(n, ny, y, wt, itable)
cumhaz <- cumsum(c(0, rate * diff(itable)))
newy <- approx(itable, cumhaz, time)$y
if (ny == 3L)
newy <- newy - approx(itable, cumhaz, y[, 1L])$y
if (length(offset) == n)
newy <- newy * exp(offset)
if (missing(parms))
parms <- c(shrink = 1L, method = 1L)
else {
parms <- as.list(parms)
if (is.null(names(parms)))
stop("You must input a named list for parms")
parmsNames <- c("method", "shrink")
indx <- pmatch(names(parms), parmsNames, 0L)
if (any(indx == 0L))
stop(gettextf("'parms' component not matched: %s",
names(parms)[indx == 0L]), domain = NA)
else names(parms) <- parmsNames[indx]
if (is.null(parms$method))
method <- 1L
else method <- pmatch(parms$method, c("deviance", "sqrt"))
if (is.na(method))
stop("Invalid error method for Poisson")
if (is.null(parms$shrink))
shrink <- 2L - method
else shrink <- parms$shrink
if (!is.numeric(shrink) || shrink < 0L)
stop("Invalid shrinkage value")
parms <- c(shrink = shrink, method = method)
}
list(y = cbind(newy, y[, 2L]), parms = parms, numresp = 2L,
numy = 2L, summary = function(yval, dev, wt, ylevel,
digits) {
paste0(" events=", formatg(yval[, 2L]), ", estimated rate=",
formatg(yval[, 1L], digits), " , mean deviance=",
formatg(dev/wt, digits))
}, text = function(yval, dev, wt, ylevel, digits, n,
use.n) {
if (use.n) paste0(formatg(yval[, 1L], digits), "\n",
formatg(yval[, 2L]), "/", n) else paste(formatg(yval[,
1L], digits))
})
}
rpart.control <- function (minsplit = 20L, minbucket = round(minsplit/3), cp = 0.01,
maxcompete = 4L, maxsurrogate = 5L, usesurrogate = 2L, xval = 10L,
surrogatestyle = 0L, maxdepth = 30L, ...)
{
if (maxcompete < 0L) {
warning("The value of 'maxcompete' supplied is < 0; the value 0 was used instead")
maxcompete <- 0L
}
if (any(xval < 0L)) {
warning("The value of 'xval' supplied is < 0; the value 0 was used instead")
xval <- 0L
}
if (maxdepth > 30L)
stop("Maximum depth is 30")
if (maxdepth < 1L)
stop("Maximum depth must be at least 1")
if (missing(minsplit) && !missing(minbucket))
minsplit <- minbucket * 3L
if ((usesurrogate < 0L) || (usesurrogate > 2L)) {
warning("The value of 'usesurrogate' supplied was out of range, the default value of 2 is used instead.")
usesurrogate <- 2L
}
if ((surrogatestyle < 0L) || (surrogatestyle > 1L)) {
warning("The value of 'surrogatestyle' supplied was out of range, the default value of 0 is used instead.")
surrogatestyle <- 0L
}
list(minsplit = minsplit, minbucket = minbucket, cp = cp,
maxcompete = maxcompete, maxsurrogate = maxsurrogate,
usesurrogate = usesurrogate, surrogatestyle = surrogatestyle,
maxdepth = maxdepth, xval = xval)
}
printcp <- function (x, digits = getOption("digits") - 2L)
{
if (!inherits(x, "rpart"))
stop("'x' must be an \"rpart\" object")
cat(switch(x$method, anova = "\nRegression tree:\n", class = "\nClassification tree:\n",
poisson = "\nRates regression tree:\n", exp = "\nSurvival regression tree:\n"))
if (!is.null(cl <- x$call)) {
dput(cl, control = NULL)
cat("\n")
}
frame <- x$frame
leaves <- frame$var == "<leaf>"
used <- unique(frame$var[!leaves])
if (!is.null(used)) {
cat("Variables actually used in tree construction:\n")
print(sort(as.character(used)), quote = FALSE)
cat("\n")
}
cat("Root node error: ", format(frame$dev[1L], digits = digits),
"/", frame$n[1L], " = ", format(frame$dev[1L]/frame$n[1L],
digits = digits), "\n\n", sep = "")
n <- x$frame$n
omit <- x$na.action
if (length(omit))
cat("n=", n[1L], " (", naprint(omit), ")\n\n", sep = "")
else cat("n=", n[1L], "\n\n")
print(x$cptable, digits = digits)
invisible(x$cptable)
}
na.rpart <- function (x)
{
Terms <- attr(x, "terms")
if (!is.null(Terms))
yvar <- attr(Terms, "response")
else yvar <- 0L
if (yvar == 0L) {
xmiss <- is.na(x)
keep <- (xmiss %*% rep(1, ncol(xmiss))) < ncol(xmiss)
}
else {
xmiss <- is.na(x[-yvar])
ymiss <- is.na(x[[yvar]])
keep <- if (is.matrix(ymiss))
((xmiss %*% rep(1, ncol(xmiss))) < ncol(xmiss)) &
((ymiss %*% rep(1, ncol(ymiss))) == 0)
else ((xmiss %*% rep(1, ncol(xmiss))) < ncol(xmiss)) &
!ymiss
}
if (all(keep))
x
else {
temp <- seq(keep)[!keep]
names(temp) <- row.names(x)[!keep]
class(temp) <- c("na.rpart", "omit")
structure(x[keep, , drop = FALSE], na.action = temp)
}
}
snip.rpart <- function (x, toss)
{
if (!inherits(x, "rpart"))
stop("Not an \"rpart\" object")
if (missing(toss) || length(toss) == 0L) {
toss <- snip.rpart.mouse(x)
if (length(toss) == 0L)
return(x)
}
ff <- x$frame
id <- as.integer(row.names(ff))
ff.n <- length(id)
toss <- unique(toss)
toss.idx <- match(toss, id, 0L)
if (any(toss.idx == 0L)) {
warning(gettext("Nodes %s are not in this tree", toss[toss.idx ==
0L]), domain = NA)
toss <- toss[toss.idx > 0L]
toss.idx <- toss.idx[toss.idx > 0L]
}
id2 <- id
while (any(id2 > 1L)) {
id2 <- id2%/%2L
xx <- (match(id2, toss, 0L) > 0L)
toss <- c(toss, id[xx])
id2[xx] <- 0L
}
temp <- match(toss%/%2L, toss, 0L)
newleaf <- match(toss[temp == 0L], id)
keepit <- (1:ff.n)[is.na(match(id, toss))]
n.split <- rep(1L:ff.n, ff$ncompete + ff$nsurrogate + (ff$var !=
"<leaf>"))
split <- x$splits[match(n.split, keepit, 0L) > 0L, , drop = FALSE]
temp <- split[, 2L] > 1L
if (any(temp)) {
x$csplit <- x$csplit[split[temp, 4L], , drop = FALSE]
split[temp, 4L] <- 1L
if (is.matrix(x$csplit))
split[temp, 4L] <- 1L:nrow(x$csplit)
}
else x$csplit <- NULL
x$splits <- split
ff$ncompete[newleaf] <- ff$nsurrogate[newleaf] <- 0L
ff$var[newleaf] <- "<leaf>"
x$frame <- ff[sort(c(keepit, newleaf)), ]
id2 <- id[x$where]
id3 <- id[sort(c(keepit, newleaf))]
temp <- match(id2, id3, 0L)
while (any(temp == 0L)) {
id2[temp == 0L] <- id2[temp == 0L]%/%2L
temp <- match(id2, id3, 0L)
}
x$where <- match(id2, id3)
x
}
## Package Data
car.test.frame <- rpart::car.test.frame ## Automobile Data from 'Consumer Reports' 1990
car90 <- rpart::car90 ## Automobile Data from 'Consumer Reports' 1990
cu.summary <- rpart::cu.summary ## Automobile Data from 'Consumer Reports' 1990
kyphosis <- rpart::kyphosis ## Data on Children who have had Corrective Spinal Surgery
solder <- rpart::solder ## Soldering of Components on Printed-Circuit Boards
stagec <- rpart::stagec ## Stage C Prostate Cancer
## Package Info
.skeleton_package_title = "Recursive Partitioning and Regression Trees"
.skeleton_package_version = "4.1-10"
.skeleton_package_depends = "graphics,stats,grDevices"
.skeleton_package_imports = ""
## Internal
.skeleton_version = 5
## EOF |
d2444f275389e2fc13073549437a453090780e32 | 14a75f70b9bd9f7ed27d01277f30f2b93f334194 | /man/toFactorLoading.Rd | 5309a844bab8ee9e7175682ca3b8b8c50d5a23c1 | [] | no_license | mhunter1/rpf | 7a2190e8811ac56f1162daefe3aff461b45be44c | fc9118ff6e4ba2c25ddf2b1b71557c071f355ce6 | refs/heads/master | 2021-01-21T23:53:19.892870 | 2015-04-14T20:20:35 | 2015-04-14T20:20:35 | 33,954,788 | 0 | 0 | null | 2015-04-14T20:17:19 | 2015-04-14T20:17:18 | null | UTF-8 | R | false | false | 505 | rd | toFactorLoading.Rd | % Generated by roxygen2 (4.0.2): do not edit by hand
\name{toFactorLoading}
\alias{toFactorLoading}
\title{Convert response function slopes to factor loadings}
\usage{
toFactorLoading(slope, ogive = rpf.ogive)
}
\arguments{
\item{slope}{a matrix with items in the columns and slopes in the rows}
\item{ogive}{the ogive constant (default rpf.ogive)}
}
\value{
a factor loading matrix with items in the rows and factors in the columns
}
\description{
Convert response function slopes to factor loadings
}
|
b3069032f27b30268aab9dd8887713cc956021b7 | e651e4b15ca7fabe8b12cabff46997fe918a576f | /shinyapp/server.R | 47ea1e309158dd5f0f3c5c8cccf61074cfc8cbad | [] | no_license | gwerbin/browsers-by-country | cfcb6311f612a0b6089fe05312d3c43d33b13d68 | 81f2ff41baafffd45972234818af6aad48144d69 | refs/heads/master | 2020-04-06T18:36:37.353436 | 2015-08-18T19:25:35 | 2015-08-18T19:25:35 | 40,991,756 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 352 | r | server.R | library(shiny)
source("browsers.R")
shinyServer(function(input, output) {
date_range <- reactive({
levels(most_popular$DateRange)[input$dates]
})
output$date_display <- reactive({
d <- unlist(strsplit(date_range(), "-"))
paste("July", d, collapse = " - ")
})
output$map <- renderPlot({
plot_map(date_range(), cols)
})
})
|
1d68f6e6835a6d3efbba5a8972b3fd05017a3985 | d650fe3ce27ada1dd397e1c8dd1f247c2bffb8a0 | /Data Explorer App/Scripts/Frontend/Data Definition Tab/Select Tab.R | bb520fb4e50856077f138987bd59af795e37ce08 | [] | no_license | shuyelin06/Data-Explorer | 4abeca42918b17d3a4187e845ae9c6933c1f79ca | 5c3ec6fefea4b7cd98a6ce04a0054c7637d8a189 | refs/heads/main | 2023-07-13T09:27:08.233933 | 2021-08-26T16:09:52 | 2021-08-26T16:09:52 | 388,231,545 | 0 | 0 | null | 2021-08-06T21:57:49 | 2021-07-21T19:58:17 | R | UTF-8 | R | false | false | 271 | r | Select Tab.R | dataSelectNav <- tabPanel(
# Title of Tab
title = "Retrieve Data",
# UI Elements
titlePanel("Select Data to be Displayed"),
uiOutput(
outputId = "selectAddData"
),
actionButton(
inputId = "selectDataRetrieve",
label = "Load Data"
)
) |
3f8bab926bdd6938646957d7f3181225546b4aa4 | 81fbffa9af93f4c2dafcc26441f83070c7d3e19c | /Vulnerability_by_Occupation.R | 6238243653014c2c60d29cb25cef402214fed955 | [] | no_license | olin-shipstead/covid-occupational-vulernability | 3734bf111a2a0d24e3fc8b728645d9e966ac38e0 | 327dc354a7a44731cc2a4ab60aea6ff358febf83 | refs/heads/main | 2022-12-31T23:15:14.066974 | 2020-10-24T18:42:40 | 2020-10-24T18:42:40 | 306,946,578 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,684 | r | Vulnerability_by_Occupation.R | # Olin Shipstead
# 15 March 2020
# Exercise recreating NYTimes plot:
# https://www.nytimes.com/interactive/2020/03/15/business/economy/coronavirus-worker-risk.html
library(ggplot2)
library(plotly)
exposure <- read.csv("Exposed_to_Disease_or_Infections.csv")[,c(1,3)]
proximity <- read.csv("Physical_Proximity.csv")[,c(1,3)]
employment <- read.csv("national_M2018_dl.csv", header=T)
employment<- employment[,c(2,4,7)]
colnames(employment) <- c("Occupation","Employment","Mean Salary")
rawdata <- merge(proximity, exposure, by="Occupation")
colnames(rawdata) <- c("Occupation", "Proximity","Exposure")
rawdata1 <- merge(rawdata,employment, by="Occupation")
rawdata3 <- rawdata1[!duplicated(rawdata1),] # duplicated used to remove repeat observations
colnames(rawdata3) <- c("Occupation","Proximity","Exposure","Employment","Mean Salary")
rawdata3$Exposure <- as.numeric(as.character(rawdata3$Exposure)) # used to convert factor column to numeric
rawdata3$Employment <- as.numeric(as.character(gsub(",","",rawdata3$Employment))) # gsub used to remove commas
rawdata3$`Mean Salary` <- as.numeric(as.character(gsub(",","",rawdata3$`Mean Salary`)))
p <- ggplot(rawdata3, aes(Proximity, Exposure))
p + geom_point(alpha=0.5, na.rm=T, aes(size=Employment, color=`Mean Salary`))+
scale_size(range=c(1,12))+
scale_color_gradient(low="blue",high="red")+
geom_label(aes(label=ifelse(Employment>1500000 & (Exposure > 60 | Proximity > 70),as.character(Occupation),NA)), nudge_y = 7)+
labs(title = "Vulnerability to Infection by Occupation", subtitle = "Using data from O*NET, Department of Labor")+
theme_classic()
|
934ebb8b09863c9908c4e8db567300cbf9467b7d | 5101152b7ec06d87e8265ecf3b279c956176a2d7 | /R/readMzXmlDir-functions.R | f27bc79b4b92a328f7a57d79e12beab5c49bb16d | [] | no_license | sgibb/readMzXmlData | d5b100d3214f2a2d9717651c8c360b48bacd6ec9 | e00579ac9771950236ae118640e52fefa1e7ba06 | refs/heads/master | 2022-11-27T05:40:39.150679 | 2022-11-08T09:10:33 | 2022-11-08T09:10:58 | 5,784,522 | 5 | 4 | null | null | null | null | UTF-8 | R | false | false | 4,521 | r | readMzXmlDir-functions.R | ## Copyright 2011-2012 Sebastian Gibb
## <mail@sebastiangibb.de>
##
## This file is part of readMzXmlData for R and related languages.
##
## readMzXmlData is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## readMzXmlData is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with readMzXmlData. If not, see <https://www.gnu.org/licenses/>
#' Reads recursively mass spectrometry data in mzXML format.
#'
#' Reads recursively all mass spectrometry data in mzXML format in a specified
#' directory.
#'
#' @details See \code{\link{readMzXmlFile}}.
#'
#' @param mzXmlDir \code{character}, path to \emph{directory} which should
#' be read recursively.
#' @param removeCalibrationScans \code{logical}, if \code{TRUE} all scans in
#' directories called \dQuote{[Cc]alibration} will be ignored.
#' @param removeMetaData \code{logical}, to save memory metadata could be
#' deleted.
#' @param rewriteNames \code{logical}, if \code{TRUE} all list elements get
#' an unique name from metadata otherwise file path is used.
#' @param fileExtension \code{character}, file extension of mzXML formatted
#' files. The directory is only searched for \emph{fileExtension} files.
#' In most cases it would be \dQuote{"mzXML"} but sometimes you have to use
#' \dQuote{xml}.
#' @param verbose \code{logical}, verbose output?
#'
#' @return A list of spectra.
#' \itemize{
#' \item{\code{[[1]]spectrum$mass}: }{A vector of calculated mass.}
#' \item{\code{[[1]]spectrum$intensity}: }{A vector of intensity values.}
#' \item{\code{[[1]]metaData}: }{A list of metaData depending on read spectrum.}
#' }
#'
#' @author Sebastian Gibb \email{mail@@sebastiangibb.de}
#' @seealso \code{\link{readMzXmlFile}},
#' \code{\link[MALDIquantForeign]{importMzXml}}
#' @keywords IO
#' @rdname readMzXmlDir
#' @export
#' @examples
#'
#' ## load library
#' library("readMzXmlData")
#'
#' ## get examples directory
#' exampleDirectory <- system.file("Examples", package="readMzXmlData")
#'
#' ## read example spectra
#' spec <- readMzXmlDir(exampleDirectory)
#'
#' ## plot spectra
#' plot(spec[[1]]$spectrum$mass, spec[[1]]$spectrum$intensity, type="n")
#'
#' l <- length(spec)
#' legendStr <- character(l)
#' for (i in seq(along=spec)) {
#' lines(spec[[i]]$spectrum$mass, spec[[i]]$spectrum$intensity, type="l",
#' col=rainbow(l)[i])
#' legendStr[i] <- basename(spec[[i]]$metaData$file)
#' }
#'
#' ## draw legend
#' legend(x="topright", legend=legendStr, col=rainbow(l), lwd=1)
#'
readMzXmlDir <- function(mzXmlDir, removeCalibrationScans=TRUE,
removeMetaData=FALSE, rewriteNames=TRUE, fileExtension="mzXML",
verbose=FALSE) {
if (verbose) {
message("Look for spectra in ", sQuote(mzXmlDir), " ...")
}
if ((!file.exists(mzXmlDir)) || (!file.info(mzXmlDir)$isdir)) {
stop("Directory ", sQuote(mzXmlDir), " doesn't exists or is no ",
"directory!")
}
## look for mzXML files (alphabetical sort)
files <- list.files(path=mzXmlDir,
pattern=paste0("^.*\\.", fileExtension, "$"),
recursive=TRUE)
## remove calibrations scans?
if (removeCalibrationScans) {
calibrationScans <- grep(pattern="[Cc]alibration", x=files, value=TRUE)
if (length(calibrationScans) > 0) {
files <- setdiff(files, calibrationScans)
}
}
if (length(files) <= 0) {
stop("Directory doesn't contain any ", fileExtension, " file.")
}
## generate "path/files"
files <- sapply(files, function(x) {
x <- file.path(mzXmlDir, x)
return(x)
})
## read mzXML files
mzXmlData <- list()
for (i in seq(along=files)) {
mzXmlFile <- .readMzXmlFile(mzXmlFile=files[i],
removeMetaData=removeMetaData, verbose=verbose)
for (j in seq(along=mzXmlFile)) {
spectra <- list()
spectra$spectra <- mzXmlFile[[j]]
mzXmlData <- c(mzXmlData, spectra)
}
}
if (!removeMetaData & rewriteNames) {
## rewrite names
if (verbose) {
message("rewrite names ...")
}
names(mzXmlData) <- paste0("s", 1:length(mzXmlData))
}
return(mzXmlData)
}
|
72f707e169ce561548aca6690a445bde4c628eb5 | dfbb9c6071a23981639d1e5d8b6356197ce4775a | /man/j_list_by.Rd | 936be5c1f18914300cc922a6bd5a93092822ae89 | [
"MIT"
] | permissive | matcasti/dtPipe | e569a8948117ee7a9b345077a1d7c759a978fcfe | 74b34c4a8f48ff552798d4d3afd9c140e9e0c646 | refs/heads/master | 2023-08-17T05:58:14.242295 | 2021-09-30T00:21:28 | 2021-09-30T00:21:28 | 410,735,559 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 389 | rd | j_list_by.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/pipes.R
\name{j_list_by}
\alias{j_list_by}
\title{Pipeable functions to improve data.table's readability}
\usage{
j_list_by(x, ..., by)
}
\arguments{
\item{x}{a data.table}
\item{...}{further arguments}
\item{by}{for grouping purposes}
}
\description{
Pipeable functions to improve data.table's readability
}
|
c0fcf9894a3a7d7acb04aefc2a23ce676020ec6b | fd365694237edb699e53eef04f1c3c0ff649f3c8 | /R/opal.symbol.R | ada2e6ec8650cd39fb737f6acedec308b9978e77 | [] | no_license | obiba/opalr | f73a0eb0280bc768b47711d6a1a08ce0eded7ce1 | 5ca4936deae7e3410db5ee6a02df7994ff5fa336 | refs/heads/master | 2023-08-03T06:18:07.954481 | 2023-07-21T06:58:07 | 2023-07-21T06:58:07 | 166,788,279 | 3 | 3 | null | 2021-05-13T15:50:49 | 2019-01-21T09:45:41 | R | UTF-8 | R | false | false | 7,114 | r | opal.symbol.R | #-------------------------------------------------------------------------------
# Copyright (c) 2021 OBiBa. All rights reserved.
#
# This program and the accompanying materials
# are made available under the terms of the GNU Public License v3.0.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------
#' List R symbols
#'
#' Get the R symbols available in the remote R session.
#'
#' @family symbol functions
#' @param opal Opal object.
#' @examples
#' \dontrun{
#' o <- opal.login('administrator','password', url='https://opal-demo.obiba.org')
#' opal.symbols(o)
#' opal.logout(o)
#' }
#' @export
opal.symbols <- function(opal) {
ignore <- .getRSessionId(opal)
opal.get(opal, "r", "session", opal$rid, "symbols", acceptType = "application/octet-stream")
}
#' Remove a R symbol
#'
#' Remove a symbol from the remote R session.
#'
#' @family symbol functions
#' @param opal Opal object.
#' @param symbol Name of the R symbol.
#' @examples
#' \dontrun{
#' o <- opal.login('administrator','password', url='https://opal-demo.obiba.org')
#' opal.symbol_rm(o, 'D')
#' opal.logout(o)
#' }
#' @export
opal.symbol_rm <- function(opal, symbol) {
ignore <- .getRSessionId(opal)
tryCatch(opal.delete(opal, "r", "session", opal$rid, "symbol", symbol), error=function(e){})
}
#' Remove a R symbol (deprecated)
#'
#' Remove a symbol from the current R session. Deprecated: see opal.symbol_rm function instead.
#'
#' @family symbol functions
#' @param opal Opal object.
#' @param symbol Name of the R symbol.
#' @examples
#' \dontrun{
#' o <- opal.login('administrator','password', url='https://opal-demo.obiba.org')
#' opal.rm(o, 'D')
#' opal.logout(o)
#' }
#' @export
opal.rm <- function(opal, symbol) {
opal.symbol_rm(opal, symbol)
}
#' Save a tibble
#'
#' Save a tibble identified by symbol as a file of format SAS, SPSS, Stata, CSV or TSV in the remote R session working directory.
#'
#' @family symbol functions
#' @param opal Opal object.
#' @param symbol Name of the R symbol representing a tibble.
#' @param destination The path of the file in the R session workspace. Supported file extensions are:
#' .sav (SPSS), .zsav (compressed SPSS), .sas7bdat (SAS), .xpt (SAS Transport), .dta (Stata),
#' .csv (comma separated values), .tsv (tab separated values).
#' @examples
#' \dontrun{
#' o <- opal.login('administrator','password', url='https://opal-demo.obiba.org')
#' opal.symbol_save(o, 'D', 'test.sav')
#' opal.logout(o)
#' }
#' @export
opal.symbol_save <- function(opal, symbol, destination) {
ignore <- .getRSessionId(opal)
if (!is.na(opal$version) && opal.version_compare(opal,"2.8")<0) {
stop("Saving tibble in a file is not available for opal ", opal$version, " (2.8.0 or higher is required)")
} else {
if (is.null(destination)) {
stop("Destination file path is missing or empty.")
}
if (endsWith(destination, ".zsav") || endsWith(destination, ".xpt")) {
if (!is.na(opal$version) && opal.version_compare(opal,"2.14")<0) {
stop("Saving tibble in a compressed SPSS or SAS Transport file is not available for opal ", opal$version, " (2.14.0 or higher is required)")
}
}
query <- list(destination=destination)
res <- opal.put(opal, "r", "session", opal$rid, "symbol", symbol, "_save", query=query)
}
}
#' Import a tibble
#'
#' Import a tibble identified by the symbol as a table in Opal. This operation creates an importation task
#' in Opal that can be followed (see tasks related functions).
#'
#' @family symbol functions
#' @param opal Opal object.
#' @param symbol Name of the R symbol representing a tibble.
#' @param project Name of the project into which the data are to be imported.
#' @param identifiers Name of the identifiers mapping to use when assigning entities to Opal.
#' @param policy Identifiers policy: 'required' (each identifiers must be mapped prior importation (default)), 'ignore' (ignore unknown identifiers) and 'generate' (generate a system identifier for each unknown identifier).
#' @param id.name The name of the column representing the entity identifiers. Default is 'id'.
#' @param type Entity type (what the data are about). Default is 'Participant'.
#' @param wait Wait for import task completion. Default is TRUE.
#' @examples
#' \dontrun{
#' o <- opal.login('administrator','password', url='https://opal-demo.obiba.org')
#' opal.symbol_import(o, 'D', 'test')
#' opal.logout(o)
#' }
#' @export
opal.symbol_import <- function(opal, symbol, project, identifiers=NULL, policy='required', id.name='id', type='Participant', wait=TRUE) {
rid <- .getRSessionId(opal)
if (!is.na(opal$version) && opal.version_compare(opal,"2.8")<0) {
warning("Importing tibble in a table not available for opal ", opal$version, " (2.8.0 or higher is required)")
} else {
# create a transient datasource
dsFactory <- list(session=rid, symbol=symbol, entityType=type, idColumn=id.name)
if (is.null(identifiers)) {
dsFactory <- paste0('{"Magma.RSessionDatasourceFactoryDto.params": ', .listToJson(dsFactory), '}')
} else {
idConfig <- list(name=identifiers)
if (policy == 'required') {
idConfig["allowIdentifierGeneration"] <- TRUE
idConfig["ignoreUnknownIdentifier"] <- TRUE
} else if (policy == 'ignore') {
idConfig["allowIdentifierGeneration"] <- FALSE
idConfig["ignoreUnknownIdentifier"] <- TRUE
} else {
idConfig["allowIdentifierGeneration"] <- FALSE
idConfig["ignoreUnknownIdentifier"] <- FALSE
}
dsFactory <- paste0('{"Magma.RSessionDatasourceFactoryDto.params": ', .listToJson(dsFactory), ', "idConfig":', .listToJson(idConfig),'}')
}
created <- opal.post(opal, "project", project, "transient-datasources", body=dsFactory, contentType="application/json")
# launch a import task
importCmd <- list(destination=project, tables=list(paste0(created$name, '.', symbol)))
location <- opal.post(opal, "project", project, "commands", "_import", body=.listToJson(importCmd), contentType="application/json", callback=.handleResponseLocation)
if (!is.null(location)) {
# /shell/command/<id>
task <- substring(location, 16)
if (wait) {
status <- 'NA'
waited <- 0
while(!is.element(status, c('SUCCEEDED','FAILED','CANCELED'))) {
# delay is proportional to the time waited, but no more than 10s
delay <- min(10, max(1, round(waited/10)))
Sys.sleep(delay)
waited <- waited + delay
command <- opal.get(opal, "shell", "command", task)
status <- command$status
}
if (is.element(status, c('FAILED','CANCELED'))) {
stop(paste0('Import of "', symbol, '" ended with status: ', status), call.=FALSE)
}
} else {
# returns the task ID so that task completion can be followed
task
}
} else {
# not supposed to be here
location
}
}
} |
3a6eae8c63ed738eca7236a58d78d8f5bb4b924b | 81496aac24e4fcd7b820951aa32f868a96a7dd13 | /pollutantmean.R | b7ece359d9cc53608e92c04f94f3b575fc653e2d | [] | no_license | sarahhamid0/ProgrammingAssignment1 | 1676dc85bbf9d5ab96500a8555a44cd9c578be5d | 227cdb280586055fa41fbfd039d6541777ded1dd | refs/heads/main | 2022-12-25T16:18:09.382691 | 2020-10-06T08:07:12 | 2020-10-06T08:07:12 | 300,354,865 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 288 | r | pollutantmean.R | pollutantmean <- function (directory, pollutant, id = 1:332) {
myfiles <- list.files(path = directory, pattern = ".csv", full.names = TRUE)
x <- numeric()
for(i in id) {
mydata <- read.csv(myfiles[i])
x <- c(x, mydata[[pollutant]])
}
mean(x, na.rm = TRUE)
}
|
9bde130f93eafffc4776302be70ddba106af79e5 | 1c5e993681ab00b3eb698d05f84e1daf2b4723e9 | /R/buildXY.R | 175519b11d391430594b6867e12ea6b6fa547880 | [] | no_license | cran/EDISON | d4e9ecb9187ec33efa2276d00ca5b37a487159e1 | 9d3d3660629fe0ee9fa81697452c47369485fa3a | refs/heads/master | 2021-01-21T21:55:02.171225 | 2016-03-30T21:04:12 | 2016-03-30T21:04:12 | 17,678,892 | 2 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,131 | r | buildXY.R | #' Builds response Y and predictor X.
#'
#' This function builds the response variables Y and predictor variables X from
#' the input data.
#'
#'
#' @param targetData Target input data.
#' @param predData Predictor input data.
#' @param GLOBvar Global variables of the MCMC simulation.
#' @return A list with elements: \item{X}{Predictor variables.}
#' \item{Y}{Response variables.}
#' @author Sophie Lebre
#' @export buildXY
buildXY <-
function(targetData, predData, GLOBvar){
### Build response Y and predictor X
### Assignement of global variables used here ###
n = GLOBvar$n
m = GLOBvar$m
q = GLOBvar$q
dyn = GLOBvar$dyn
target = GLOBvar$target
bestPosMat = GLOBvar$bestPosMat
### end assignement ###
# Read target data
Y = as.array(readDataTS(data=targetData, posI=target, t0=dyn, tf=n, m=m, n=n))
# Read predictor data
posTF = as.matrix(bestPosMat)[target,1:q]
dataTF = t(readDataTS(data=predData, posI=posTF, t0=0, tf=n-dyn, m=m, n=n))
## Add a constant vector to the predictor data
X = cbind(dataTF,array(1,length(dataTF[,1])))
# Return formatted data
return(list(X=X,Y=Y))
}
|
1be142df79c4537f67d7151b9a48de9013205c9c | 246154d146ecfd6b6dd579200a8b65c4eba6b7ba | /R/fitMods.R | 3f0c670c235060b8c43831cebdfe091c410eb39a | [] | no_license | cran/subtee | 310c2d481959e69237401ef303ecf0720e7d0247 | 92c86b0a4334580fb5010a78701d566b5c735080 | refs/heads/master | 2022-05-07T11:55:45.240047 | 2022-03-22T13:10:05 | 2022-03-22T13:10:05 | 162,720,131 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,195 | r | fitMods.R | BIC_survreg = function(fit) AIC(fit, k = log(sum(fit$y[,2])))
## helper function to extract trt eff and interaction estimate and
## covariance matrix from all models and also the p-value of the test
## statistic
getEsts <- function(fit, trtNam, subgrNam){
cf <- coef(fit)
vc <- vcov(fit)
cls <- class(fit)[1]
sfit <- summary(fit)
if(is.na(subgrNam)){
ind1 <- match(trtNam, names(cf))
bic <- switch(cls,
survreg = BIC_survreg(fit),
BIC(fit))
return(list(ests = cf[ind1], ests_vc = vc[ind1,ind1],
AIC=AIC(fit), BIC=bic))
} else {
p <- switch(cls,
survreg = sfit$table[, 4],
rlm = {
rat <- sfit$coefficients[,1]/sfit$coefficients[,2]
2*(1-pnorm(abs(rat)))
},
coxph = {
sfit$coefficients[, 5]
}, {
sfit$coefficients[, 4]
})
bic <- switch(cls,
survreg = BIC_survreg(fit),
BIC(fit))
ind1 <- match(trtNam, names(cf))
ind2 <- match(sprintf("%s:%s", trtNam, subgrNam),
names(cf))
ind <- c(ind1, ind2)
return(list(ests = cf[ind], ests_vc = vc[ind,ind],
pval = p[ind],
AIC=AIC(fit), BIC=bic))
}
}
## function to fit all subgroup models
## Inputs:
## trt - binary trt variable
## resp - response
## subgr - dataframe of candidate subgroups
## covars - additional covariates included in the models
## fitfunc - model fitting function;
## one of "lm", "glm", "survreg", "coxph" or "glm.nb"
## event - event variable; need to be specified for fit functions survreg
## and coxph
## exposure - needs to be specified for fit function "glm.nb"
fitMods <- function(resp, trt, subgr, covars, data,
fitfunc = "lm", event, exposure, ...){
## create formula for model fitting
## look at special cases: survival data and overdispersed count data
if(!is.element(fitfunc, c("survreg", "coxph", "glm.nb"))){
form <- sprintf("%s ~ %s", resp, trt)
}
if(is.element(fitfunc, c("survreg", "coxph"))){
if(missing(event))
stop("need to specify event variable for survreg or coxph")
if(!is.character(event))
stop("event needs to be a character variable")
form <- sprintf("Surv(%s, %s) ~ %s",
resp, event, trt)
}
if(fitfunc == "glm.nb"){
if(missing(exposure))
stop("need to specify exposure variable for glm.nb")
if(!is.character(exposure))
stop("exposure needs to be a character variable")
form <- sprintf("%s ~ %s + offset(log(%s))",
resp, trt, exposure)
}
## translate character to function object
fitf <- get(fitfunc)
## fit all models
nSub <- length(subgr)
fitmods <- vector("list", nSub)
if(is.null(covars)){
progs <- NULL
} else {
progs <- attr(terms(covars), "term.labels")
}
for(i in 1:nSub){
bsub <- sprintf(".subgroup__%s", i)
assign(bsub, data[, subgr[i]])
progDiff <- setdiff(setdiff(progs, subgr[i]), sprintf("`%s`", subgr[i]))
progCovSub <- paste(c(progDiff, bsub), collapse = " + ")
formSub <- sprintf("%s + %s + %s*%s", form, progCovSub,
trt, bsub)
fit <- fitf(as.formula(formSub), data=data, ...)
ests <- getEsts(fit, trt, bsub)
if(any(is.na(ests$ests))){
warning(sprintf("NA in treatment effect estimate in subgroup
model for variable \"%s\".", subgr[i]))
}
lst <- list(model=fit,
ests=ests,
subgrNam=subgr[i])
fitmods[[i]] <- lst
}
names(fitmods) <- subgr
## fit overall model
formOv <- form
if (!is.null(progs)) {
progCov <- paste(unique(progs), collapse = " + ")
formOv <- sprintf("%s + %s", form, progCov)
}
fit <- fitf(as.formula(formOv), data=data, ...)
ests <- getEsts(fit, trt, NA)
fitOverall <- list(model=fit, ests=ests)
## create output list
out <- list()
out$subgroups <- subgr
out$fitmods <- fitmods
out$fitOverall <- fitOverall
out$trtNam <- trt
out
}
|
95f9911a9dfafd093f0928aec5205db9b01da990 | 21b2109b4e4ec9269f1df53b4736da6df11d8be3 | /man/estimate_mdiff_contrast_bs.Rd | 994eb2d05de8dbe89716f265713c120007589c91 | [] | no_license | rcalinjageman/esci2 | 9ec246d962c1deb54b44a942c132b97d1a7272bb | a6356eda12a4788934c42cecf4b7cdb516c6f87b | refs/heads/main | 2023-07-27T20:01:47.970675 | 2021-09-11T03:41:39 | 2021-09-11T03:41:39 | 344,518,167 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 3,465 | rd | estimate_mdiff_contrast_bs.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mdiff_contrast_bs.R
\name{estimate_mdiff_contrast_bs}
\alias{estimate_mdiff_contrast_bs}
\title{Estimate the mean difference for an independent groups contrast.}
\usage{
estimate_mdiff_contrast_bs(
data = NULL,
grouping_variable = NULL,
outcome_variable = NULL,
means = NULL,
sds = NULL,
ns = NULL,
group_labels = NULL,
grouping_variable_name = "My grouping variable",
outcome_variable_name = "My outcome variable",
contrast = NULL,
conf_level = 0.95,
assume_equal_variance = FALSE,
save_raw_data = TRUE
)
}
\arguments{
\item{data}{For raw data - a dataframe or tibble}
\item{grouping_variable}{For raw data - The column name of the grouping
variable, or a vector of group names}
\item{outcome_variable}{For raw data - The column name of the outcome
variable, or a vector of numeric data}
\item{means}{For summary data - A vector of 2 or more means}
\item{sds}{For summary data - A vector of standard deviations, same length as
means}
\item{ns}{For summary data - A vector of sample sizes, same length as means}
\item{group_labels}{For summary data - An optional vector of group labels,
same length as means}
\item{grouping_variable_name}{Optional friendly name for the grouping
variable. Defaults to 'My grouping variable' or the grouping variable
column name if a data.frame is passed.}
\item{outcome_variable_name}{Optional friendly name for the outcome variable.
Defaults to 'My outcome variable' or the outcome variable column name if a
data frame is passed.}
\item{contrast}{A vector of group weights.}
\item{conf_level}{The confidence level for the confidence interval. Given in
decimal form. Defaults to 0.95.}
\item{assume_equal_variance}{Defaults to FALSE}
\item{save_raw_data}{For raw data; defaults to TRUE; set to FALSE to save
memory by not returning raw data in estimate object}
}
\value{
Returnsobject of class esci_estimate
}
\description{
\loadmathjax
\code{estimate_mdiff_contrast_bs} returns the point estimate and
confidence interval for the mean difference in a linear contrast:
\mjdeqn{ \psi = \sum_{i=1}^{a}c_iM_i }{psi = sum(contrasts*means)}
Where there are \emph{a} groups, and \emph{M} is each group mean and \emph{c} is each group
weight; see Kline, equation 7.1
}
\section{Details}{
This is a friendly version of \code{CI_mdiff_contrast_bs}
\itemize{
\item This friendly version can handle raw data and summary data input.
\item This friendly version returns an esci_estimate object which
provides additional supporting information beyond the effect size and CI.
\item All the computational details for this analayis are documented in
\code{\link{CI_mdiff_contrast_bs}}
}
}
\examples{
# From Raw Data ------------------------------------
# Just pass in the data source, grouping column, and outcome column.
# You can pass these in by position, skipping the labels:
# Note... not sure if PlantGrowth dataset meets assumptions for this analysis
estimate_mdiff_contrast_bs(
PlantGrowth,
group,
weight,
contrast = c('ctrl' = -1, 'trt1' = 1)
)
}
\references{
\itemize{
\item Cumming, G., & Calin-Jageman, R. J. (2017).
Introduction to the new statistics: Estimation, open science, and beyond.
Routledge.
}
}
\seealso{
\itemize{
\item \code{\link{plot_mdiff_contrast_bs}} to visualize the results
\item \code{\link{CI_mdiff_contrast_bs}} for a version of this function focused
just on the effect size and CI
}
}
|
09518770da1cb5295e5b9d4f452f2aa5b3f08668 | 919fd296ac269d455a7d995aeb5b9d918cbfc058 | /lessons/r/shiny/3/server.r | b5acb047110d7a42e5b03a95d1152df503c33b4c | [
"Apache-2.0"
] | permissive | aays/studyGroup | 9681427897d30bcddf2162ccdd3b410c4f2cb9e0 | e7d7bb03e70e32c7ca2525ce826e366810d3e9a0 | refs/heads/gh-pages | 2023-04-07T18:18:10.952550 | 2023-02-27T15:45:13 | 2023-02-27T15:45:13 | 171,192,931 | 0 | 0 | Apache-2.0 | 2019-02-18T01:15:35 | 2019-02-18T01:15:34 | null | UTF-8 | R | false | false | 6,574 | r | server.r | #We've now added interactivity to the plot. The user can (a) specify the Variable (Var) scenario they wish to plot the PCA of, and (b) adjust the text's cex values. The server.r script now includes code to add colors that correspond to each selected variable's parameter values (param), as well as a legend.
library(shiny) #First load shiny library
load("../pcas.RDATA") #Load data
#Define a server for the Shiny app
shinyServer(function(input, output) {
#Create a reactive Shiny plot to send to the ui.r called "pcaplot"
output$pcaplot <- renderPlot({
#Match user's variable input selection by subsetting for when foo$Var==input$var
fbar<-droplevels(foo[which(foo$Var==input$var),])
#Generate colors to correspond to the different Variables' parameters. E.g., for the variable "colless", different colors for "loIc","midIc", and "hiIc"
cols<-c("#1f77b4","#ff7f0e","#2ca02c")[1:length(levels(fbar$param))]
#Render the scatterplot of PCA
plot(PC2 ~ PC1, data=fbar, type="n", xlab="PC1", ylab="PC2")
#For each of the different parameter values (different colors), plot the text names of the metrics
for(i in levels(fbar$param)){
foo2<-subset(fbar,param==i)
text(PC2 ~ PC1, data=foo2, labels=foo2$metric, col=cols[which(levels(fbar$param)==i)], cex=input$cexSlider)
}
#Add a legend for the different parameter values (with corresponding colors) of the selected Variable
legend("topright", fill=cols, legend=levels(fbar$param))
})
})
#TASKS:
#1. Depending on the variable that people choose (input$var), we now want to display the chosen variable's parameter (param) values as a check box group. Even though logically we would begin with the checkboxGroupInput function on the ui.R script to display check box options, first remember what the capabilities of the user side (ui.R) are. ui.R cannot evaluate/process information, but only displays output values calculated on the server side (server.R). In other words, the ui.R only takes in the values a user specifies and then sends this information to be evaluated/processed on the server side.
# So to create a checkboxgroup of param values that will change based on what the user selects for a variable (input$var), our first step is to evaluate what the user selects as a variable. This evaluation can only take place on the server side. We therefore need to create an object on the server side (output$paramchkbxgrp) that will evaluate the user's Variable selection (input$var), which will then decide which check box options to display. This decision of what to display is then fed back to the ui.R with the object uiOutput.
# 1.a. Depending on what Variable is selected by the user (input$var), generate a different set of check box options to display (with the function checkboxGroupInput). For instance, if "colless" is selected as the variable, display the parameters values that correspond to "colless", e.g., loIc, midIc and hiIc. This switch function takes the given value (input$var) and then evaluates it. When input$var=="colless", then it evaluates the checkboxGroupInput function with the choices of c("Low" = "loIc", "Mid" = "midIc", "High" = "hiIc").
#Use the following script as a framework for the paramchkbxgrp object:
# output$paramchkbxgrp <- renderUI({
# if (is.null(input$var))
# return()
## Depending on input$var, we'll generate a different
## UI component and send it to the client.
# switch(input$var,
# "colless" = checkboxGroupInput(inputId = "PARAMS", label = "",
# choices = c(
# "Low" = "loIc",
# "Mid" = "midIc",
# "High" = "hiIc"
# ),
# selected = c("loIc","midIc","hiIc")),
##Fill in the ellipses with the corresponding parameter values
# "numsp" = checkboxGroupInput(...),
# "spatial" = checkboxGroupInput(...),
# )
# })
# })
#2. When certain checkboxes are unselected, display the text as grey with some transparency. To do this, within the renderPlot function, adjust the cols object such that the unselected are black with high transparency (display as grey). To do this for the cols object, subset for when input$PARAMS is not in levels(fbar$PARAMS):
# cols[which(!(levels(fbar$param) %in% input$PARAMS))]
#Then assign all of these instances as black rgb(0,0,0, maxColorValue=255) with very high transparency rgb(0,0,0, alpha =25, maxColorValue=255):
# cols[which(!(levels(fbar$param) %in% input$PARAMS))]<- rgb(0,0,0, alpha=25,maxColorValue=255)
# #HINTS
# 1.a Drop-down menu to select Factor
# output$paramchkbxgrp <- renderUI({
# if (is.null(input$var))
# return()
# # Depending on input$var, we'll generate a different
# # UI component and send it to the client.
# switch(input$var,
# "colless" = checkboxGroupInput("PARAMS", "",
# choices = c("Low" = "loIc",
# "Mid" = "midIc",
# "High" = "hiIc"
# ),
# selected = c("loIc","midIc","hiIc")),
# "numsp" = checkboxGroupInput("PARAMS", "",
# choices = c("16 Species" = 16,
# "64 Species" = 64,
# "256 Species" = 256),
# selected = c(16,64,256)),
# "spatial" = checkboxGroupInput("PARAMS", "",
# choices = c("True" = "TRUE",
# "False" = "FALSE"),
# selected = c("TRUE","FALSE")),
# )
# })
# 2.
# output$pcaplot <- renderPlot({
# #Match user's variable input selection by subsetting for when foo$Var==input$var
# fbar<-droplevels(foo[which(foo$Var==input$var),])
# #Generate colors to correspond to the different Variables' parameters. E.g., for the variable "colless", different colors for "loIc","midIc", and "hiIc"
# cols<-c("#1f77b4","#ff7f0e","#2ca02c")[1:length(levels(fbar$param))]
# #***********************ADD THIS TO EXISTING SCRIPT *************************
# #If the param is not selected, set the color value to grey with transparency
# cols[which(!(levels(fbar$param) %in% input$PARAMS))]<- rgb(0,0,0, alpha=25,maxColorValue=255)
# #****************************************************************************
# #Render the scatterplot of PCA
# plot(PC2 ~ PC1, data=fbar, type="n", xlab="PC1", ylab="PC2")
# #For each of the different parameter values (different colors), plot the text names of the metrics
# for(i in levels(fbar$param)){
# foo2<-subset(fbar,param==i)
# text(PC2 ~ PC1, data=foo2, labels=foo2$metric, col=cols[which(levels(fbar$param)==i)], cex=input$cexSlider)
# }
# #Add a legend for the different parameter values (with corresponding colors) of the selected Variable
# legend("topright", fill=cols, legend=levels(fbar$param))
# })
|
d5453d1356e4f42ff3e865352a29b0c738ff605a | 99f350773f2db550c3547b9e73424c2511cf654d | /scripts R/comp_marche.R | 434148d6ae9c2e0c6172a88f11e2c36ebc42e501 | [] | no_license | Clara-Reichert/R4meropy | e42f60cb596d3e9bebea746a24d44a114f71387d | c6cbe551a52a3d1c236a921ba49b78c70dd655c5 | refs/heads/master | 2022-11-24T02:31:35.393708 | 2020-08-04T13:05:44 | 2020-08-04T13:05:44 | 273,433,253 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,051 | r | comp_marche.R | #comparaison omega et multi pour le 03/06
#lire les jeux de données
multi<- read.csv("C:/Users/clare/R4meropy/csv/multi_direct.csv", sep=";")
omega<- read.csv("C:/Users/clare/R4meropy/csv/omega_direct.csv", sep=";")
# convertir le nom de l'image en date-heure
multi$d_h=as.POSIXlt(multi$nom_images, format="chassis_%Y-%m-%d_%H.%M.%S.jpg")
omega$d_h=as.POSIXlt(omega$nom_images, format="chassis_%Y-%m-%d_%H.%M.%S.jpg")
c=1
L=character(length=0)
for (i in 1:length(multi$Latitude)){
if (is.na(multi[i,1]==T)){
print("yes")
L[c]=i
c=c+1
}
}
multi=multi[-as.numeric(L),]
### enlever les lignes sans coordonées pour omega ###
L=character(length=0)
c=1
for (i in 1:length(omega$Latitude)){
if (is.na(omega[i,1]==T)){
print("yes")
L[c]=i
c=c+1
}
}
omega=omega[-as.numeric(L),]
MatchO=match(multi$d_h,omega$d_h)
MatchM=match(omega$d_h,multi$d_h)
omega=omega[MatchO,]
multi=multi[MatchM,]
write.csv2(multi, file = "multi_exact.csv", row.names = FALSE)
write.csv2(omega, file = "omega_exact.csv", row.names = FALSE) |
e6ecbefcf48c1c4b68ce4279a55e2e8223da1d81 | a83761e0ab08bace8620e57e30c3e6cb69a3ca0d | /code/r_scripts/DNA_RPKM.r | f366b24737130befcc02b53fe45b10ea67249ddf | [] | no_license | Karl-Svard/Genome_Analysis | a5e51d124ac0a8c14b02aee8e1c224337b8a4d4d | f3966c13ef87aaa4a142e01a31b60628abfed729 | refs/heads/master | 2022-09-01T20:31:20.771876 | 2020-05-26T21:56:24 | 2020-05-26T21:56:24 | 250,238,585 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,550 | r | DNA_RPKM.r | #!/usr/bin/Rscript
# Script that performs RPKM calculations on DNA mapped bins.
# Takes input from stdin about which site should be looked at ("D1" or "D3")
input<-file('stdin')
site <- readLines(input, n=1)
# List of bin IDs with completeness over 70% and contamination below 5%.
ID <- c(1, 2, 4, 11, 12, 15, 19, 24, 26)
# Pre-allocate vectors for the data frame
Bin_name <- character(length(ID))
Length <- integer(length(ID))
Mapped_reads <- integer(length(ID))
Total_reads <- integer(length(ID))
RPKM <- double(length(ID))
x <- 1
# Iteratively parse through each mapped bin from the site
for (i in ID){
# Path of the file
path <- paste("/home/karsva/Genome_Analysis/data/analysis_results",
"/11_DNA_mapping/site_", site, "/bin_", i, "_", site,
"_DNA_stats.tsv",sep = "")
# Read in file
stats <- read.table(file = path, sep = '\t', header = FALSE)
# Perform calculations
bin_length <- sum(stats$V2)
n_mapped_reads <- sum(stats$V3)
n_unmapped_reads <- sum(stats$V4)
n_total_reads <- n_mapped_reads + n_unmapped_reads
rpkm_value <- n_mapped_reads/((bin_length/1000)*(n_total_reads/1000000))
# Add to vectors
Bin_name[x] <- paste("Bin_",i, sep="")
Length[x] <- bin_length
Mapped_reads[x] <- n_mapped_reads
Total_reads[x] <- n_total_reads
RPKM[x] <- rpkm_value
x = x + 1
}
# Create a resulting data frame
df <- data.frame(Bin_name, ID, Length, Mapped_reads,
Total_reads, RPKM, stringsAsFactors=FALSE)
# Print to stdout
write.table(df, row.names=FALSE, sep="\t")
|
3d7ee76e5100bfb37f6e96fc0e43c901a9997119 | cab829be4f0442f52e38bd311587b22a0d3b1c47 | /plot4.R | 74a275b4f2c99d2321a55f52df476e45614360ab | [] | no_license | DataSciDan/ExData_Plotting1 | dbc2527ef7c855a831a98d2c58ff4c2a54cbcfe9 | 2a80925b34291d65f35f00bfff90f3cc48da19d0 | refs/heads/master | 2021-01-18T10:44:21.327941 | 2015-08-09T16:34:18 | 2015-08-09T16:34:18 | 40,400,816 | 0 | 0 | null | 2015-08-08T11:28:21 | 2015-08-08T11:28:21 | null | UTF-8 | R | false | false | 1,491 | r | plot4.R | data <- read.table("../../household_power_consumption.txt", header = TRUE, sep = ";")
feb1_2 <- data[data$Date == "1/2/2007" | data$Date == "2/2/2007", ]
par(mfcol = c(2,2))
# First Graphic
feb1_2$Global_active_power <- as.numeric(as.character(feb1_2$Global_active_power))
plot(feb1_2$Global_active_power, xaxt="n", type = "l", xlab = "",
ylab = "Global Active Power (kilowatts)")
axis(1, at = c(1, nrow(feb1_2)/2, nrow(feb1_2)), labels = c("Thu", "Fri", "Sat"))
# Second Graphic
feb1_2[,7] <- as.numeric(as.character(feb1_2[,7]))
feb1_2[,8] <- as.numeric(as.character(feb1_2[,8]))
plot(feb1_2[,7], xlab = "", ylab = "Energy sub metering", xaxt = "n", col = "black",
type = "l")
axis(1, at = c(1, nrow(feb1_2)/2, nrow(feb1_2)) , labels = c("Thu", "Fri", "Sat"))
lines(feb1_2[,8], col = "orange")
lines(feb1_2[,9], col = "blue")
legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
col = c("black", "orange", "blue"), lty = 1, bty = "n")
#Third Graphic
feb1_2[,5] <- as.numeric(as.character(feb1_2[,5]))
with(feb1_2, plot(Voltage, xlab = "datetime", xaxt = "n", type = "l"))
axis(1, at = c(1, nrow(feb1_2)/2, nrow(feb1_2)), labels = c("Thu", "Fri", "Sat"))
#Fourth Graphic
feb1_2[,4] <- as.numeric(as.character(feb1_2[,4]))
with(feb1_2, plot(Global_reactive_power, xlab = "datetime", xaxt = "n", type = "l"))
axis(1, at = c(1, nrow(feb1_2)/2, nrow(feb1_2)), labels = c("Thu", "Fri", "Sat"))
dev.copy(png, file = "plot4.png")
dev.off() |
4f5b0abfbb4782d5d2795a346021fbc4e6808904 | 8e4442b99df2526ba1d639067e9a122ab0ea4907 | /R/studentAllocation/R/neat_output.R | 65745dc05f835be8347eaccf6ff583d70e689e43 | [
"MIT"
] | permissive | Joepriesto/studentProjectAllocation | d29b5d22b2a69245bbf8e3d972f1b56ecdcc0151 | 80e8cbabd20186e4b40b2f57d37697b90629422c | refs/heads/master | 2022-03-28T16:33:58.252905 | 2020-01-26T12:26:07 | 2020-01-26T12:26:07 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,789 | r | neat_output.R |
#' Create a neat (tibble) version of the lecturer allocation
#'
#' @param allocation_output Output object from the allocation algorithm
#'
#' @return
#' @export
#' @importFrom dplyr mutate tibble `%>%`
#'
#' @examples
neat_lecturer_output <- function( allocation_output ){
lapply(
names(allocation_output$lecturer_assignments),
function(lect){
students = allocation_output$lecturer_assignments[[lect]]
dplyr::tibble(
lecturer = lect,
cap = allocation_output$lecturer_list[[lect]]$cap,
n_students = length(students),
student_list = paste(students, collapse = ","),
at_capacity = lect %in% allocation_output$full_lecturers
)
}) %>% do.call(args = ., what = rbind) %>%
dplyr::mutate( student_list = as.character(student_list) ) -> lecturer_assignments
return(lecturer_assignments)
}
#' Create a neat (tibble) version of the project allocation
#'
#' @param allocation_output Output object from the allocation algorithm
#'
#' @return
#' @export
#' @importFrom dplyr mutate tibble `%>%` as_tibble
#'
#' @examples
neat_project_output <- function( allocation_output ){
lapply(
names(allocation_output$project_assignments),
function(proj){
students = allocation_output$project_assignments[[proj]]
tibble(
project = proj,
lecturer = allocation_output$project_list[[proj]]$lecturer,
cap = allocation_output$project_list[[proj]]$cap,
n_students = length(students),
student_list = paste(students, collapse = ","),
at_capacity = proj %in% allocation_output$full_projects
)
}) %>% do.call(args = ., what = rbind) %>%
as_tibble() %>%
mutate( student_list = as.character(student_list) ) -> project_assignments
return(project_assignments)
}
#' Create a neat (tibble) version of the student allocation
#'
#' @param allocation_output Output object from the allocation algorithm
#'
#' @return
#' @export
#' @importFrom dplyr mutate tibble `%>%` arrange
#'
#' @examples
neat_student_output <- function( allocation_output ){
stud_list = allocation_output$student_list
rankings <- sapply(names(allocation_output$student_assignments), function( student ){
p <- allocation_output$student_assignments[[ student ]]
match( p, stud_list[[ student ]], nomatch = NA )
})
## Which lecturer offers which project?
proj_lects <- sapply( allocation_output$project_list, function(p){
p[["lecturer"]]
})
tibble(student = names(allocation_output$student_assignments),
project = unlist(allocation_output$student_assignments),
lecturer = proj_lects [ project ],
student_ranking = rankings) %>%
arrange(project) -> student_assignments
return(student_assignments)
} |
7c53289f461ce9896d5b0a1a26db0686261b157b | e35cd7da14f73bf3a0ecc5451d87696dfdcb967f | /Lab8/lab8 rcode.R | 83bae67b137729c15005ea69aea7494ab6b00133 | [] | no_license | KaitlinGlover/Stat201 | 49bac297137fa058336fe63b8fe7f8330f4db41c | 36994a2148c3b1267970ebcabb272f27be5c9553 | refs/heads/master | 2020-12-18T10:24:08.308140 | 2020-01-19T08:08:50 | 2020-01-19T08:08:50 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 109 | r | lab8 rcode.R | p_hat = 0.7273
n = 33
x = 24
p = seq(0,1,by = 0.001)
plot(p,dbinom(x=24,size = n,prob =p),type="l")
|
925ca723cd3a9db77d5a126f9920dd21e40a8da9 | e086f623c66acf66992b7123bb64375e5a64fd9d | /R/StatComp20083R_HW7.R | 730a78b4e8e0fec8165a7fa22bab4d05e3dce346 | [] | no_license | Pengyi-Wang/StatComp20083 | 482aeac70e7d8a232a94e022d8f333e5ce5266b0 | 78f810bb17d0967f48c611f5f6192d270e5d4aa8 | refs/heads/master | 2023-02-03T03:48:28.768819 | 2020-12-19T08:22:47 | 2020-12-19T08:22:47 | 321,667,880 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,621 | r | StatComp20083R_HW7.R | #' @title Benchmark7 R and Rcpp functions.
#' @name benchmarks7
#' @description The functions used in homework 7
#' @importFrom graphics par abline lines abline
#' @examples
#' \dontrun{
#' HW7_1()
#' HW7_2()
#' HW7_3_1()
#' HW7_3_2()
#' }
NULL
#' @title the question 1 of homework
#' @examples
#' \dontrun{
#' HW7_1()
#' }
#' @export
HW7_1=function(){
set.seed(980904)
rw.Metropolis=function(sigma, x0, N) {
x=numeric(N)
x[1]=x0
u=runif(N)
k=0
for(i in 2:N){
y=rnorm(1,x[i-1],sigma)
if(u[i]<=((1/2*exp(-abs(y)))/(1/2*exp(-abs(x[i-1])))))
x[i]=y
else{
x[i]=x[i-1]
k=k+1
}
}
return(list(x=x,k=k))
}
N=2000
sigma=c(.05,.5,2,16)
x0=25
rw1=rw.Metropolis(sigma[1],x0,N)
rw2=rw.Metropolis(sigma[2],x0,N)
rw3=rw.Metropolis(sigma[3],x0,N)
rw4=rw.Metropolis(sigma[4],x0,N)
#number of candidate points rejected
no.reject=data.frame(sigma=sigma,no.reject=c(rw1$k,rw2$k,rw3$k,rw4$k))
knitr::kable(no.reject)
par(mfrow=c(2,2)) #display 4 graphs together
refline=c(log(1/20),-log(1/20))
rw=cbind(rw1$x, rw2$x, rw3$x, rw4$x)
for (j in 1:4) {
plot(rw[,j], type="l",
xlab=bquote(sigma == .(round(sigma[j],3))),
ylab="X", ylim=range(rw[,j]))
abline(h=refline)
}
par(mfrow=c(1,1)) #reset to default
a=c(.05, seq(.1, .9, .1), .95)
Q=c(log(2*a[1:6]),-log(2*(1-a[7:11])))
rw=cbind(rw1$x, rw2$x, rw3$x, rw4$x)
mc=rw[501:N, ]
Qrw=apply(mc, 2, function(x) quantile(x, a))
qq=data.frame(round(cbind(Q, Qrw), 3))
names(qq)=c('True','sigma=0.05','sigma=0.5','sigma=2','sigma=16')
knitr::kable(qq)
}
#' @title the question 2 of homework
#' @examples
#' \dontrun{
#' HW7_2()
#' }
#' @export
HW7_2=function(){
Gelman.Rubin=function(psi) {
# psi[i,j] is the statistic psi(X[i,1:j])
# for chain in i-th row of X
psi=as.matrix(psi)
n=ncol(psi)
k=nrow(psi)
psi.means=rowMeans(psi) #row means
B=n*var(psi.means) #between variance est.
psi.w=apply(psi,1,"var") #within variances
W=mean(psi.w) #within est.
v.hat=W*(n-1)/n + (B/n) #upper variance est.
r.hat=v.hat/W #G-R statistic
return(r.hat)
}
rw.Metropolis=function(sigma, x0, N) {
x=numeric(N)
x[1]=x0
u=runif(N)
k=0
for(i in 2:N){
y=rnorm(1,x[i-1],sigma)
if(u[i]<=((1/2*exp(-abs(y)))/(1/2*exp(-abs(x[i-1])))))
x[i]=y
else{
x[i]=x[i-1]
k=k+1
}
}
return(x)
}
sigma=2 #parameter of proposal distribution
k= 4 #number of chains to generate
n=15000 #length of chains
b=1000 #burn-in length
#choose overdispersed initial values
x0=c(-10, -5, 5, 10)
#generate the chains
set.seed(980904)
X=matrix(0,nrow=k,ncol=n)
for (i in 1:k)
X[i, ]=rw.Metropolis(sigma,x0[i],n)
#compute diagnostic statistics
psi=t(apply(X, 1, cumsum))
for(i in 1:nrow(psi))
psi[i,]=psi[i,]/(1:ncol(psi))
for (i in 1:k)
if(i==1){
plot((b+1):n,psi[i,(b+1):n],ylim=c(-0.2,0.2),type="l",
xlab='Index',ylab=bquote(phi))
}else{
lines(psi[i,(b+1):n],col=i)
}
par(mfrow=c(1,1)) #restore default
#plot the sequence of R-hat statistics
pen=0
rhat <- rep(0, n)
for (j in (b+1):n){
rhat[j] <- Gelman.Rubin(psi[,1:j])
if(pen==0&rhat[j]<=1.1) {pen=j;}
}
plot(rhat[(b+1):n], type="l", xlab="", ylab="R")
abline(h=1.1, lty=2)
print(pen)
}
#' @title the question 3.1 of homework
#' @examples
#' \dontrun{
#' HW7_3_1()
#' }
#' @export
HW7_3_1=function(){
compute=function(n){
k=n
f=function(x){
(1-pt(sqrt(x^2*(k-1)/(k-x^2)),k-1))-(1-pt(sqrt(x^2*k/(k+1-x^2)),k))
}
res1=uniroot(f,c(0.1,sqrt(k)-0.1))
return(res1$root)
}
n=c(4:25,100,500,1000)
root=numeric(length(n))
for(i in 1:length(n)){
root[i]=compute(n[i])
}
rw=round(cbind(n,-root,numeric(length(root)),root),3)
qq=data.frame(rw)
names(qq)=c('k','The first solution','The second solution','The third solution')
knitr::kable(qq)
}
#' @title the question 3.2 of homework
#' @examples
#' \dontrun{
#' HW7_3_2()
#' }
#' @export
HW7_3_2=function(){
compute=function(n){
k=n
f=function(x){
(1-pt(sqrt(x^2*(k-1)/(k-x^2)),k-1))-(1-pt(sqrt(x^2*k/(k+1-x^2)),k))
}
res1=uniroot(f,c(0.1,sqrt(k)-0.1))
return(res1$root)
}
n=c(4:25,100,500,1000)
root=numeric(length(n))
for(i in 1:length(n)){
root[i]=compute(n[i])
}
rw=round(cbind(n,root),3)
qq=data.frame(rw)
names(qq)=c('k','solution')
knitr::kable(qq)
} |
808167ad81053eff5db6262a932a16a51e18ae73 | 8e95e90c8be44ce4b0df63933e7be585fd227ffc | /Rscripts/step4_import_abundances.R | bb505bfbad346a5802a4c332f9997c5a84020ea1 | [
"MIT"
] | permissive | trichelab/single_cell_analyses | 98d938ba0260c6ecba83b12f62eb7de694c8bc13 | dc4b08265cb7282c07e418e0d88e22d9b17257da | refs/heads/master | 2022-12-02T08:40:22.132479 | 2020-08-14T14:11:09 | 2020-08-14T14:11:09 | 263,999,582 | 0 | 1 | MIT | 2020-05-15T14:12:21 | 2020-05-14T18:54:48 | CSS | UTF-8 | R | false | false | 6,911 | r | step4_import_abundances.R | #Rscript of RNA velocity workflow (last edited 5.18.2020)
#Step 4. Import abundances into R with tximeta
suppressPackageStartupMessages({
library(Biostrings)
library(BSgenome)
library(eisaR)
library(GenomicFeatures)
library(SummarizedExperiment)
library(tximeta)
library(rjson)
library(SingleCellExperiment)
library(scater)
library(scran)
library(Rtsne)
})
#first, we load the linked transcriptome we created in step 2
tximeta::loadLinkedTxome("gencode.v34.annotation.expanded.json")
#read alevin output
txi <- tximeta::tximeta(coldata = data.frame(
names = "BMMC_D1T1",
files = "//nasgw.hpc.vai.org/projects_secondary/triche/Pamela/RNA_velocity_doc/alevin_out/alevin/quants_mat.gz",
stringsAsFactors = FALSE
), type = "alevin")
#split counts (with splitSE) into two matrices, one with spliced and one with unspliced abundances, with corresponding rows
cg <- read.delim("gencode.v34.annotation.expanded.features.tsv",
header = TRUE, as.is = TRUE)
# Rename the 'intron' column 'unspliced' to make assay names compatible with scVelo
colnames(cg)[colnames(cg) == "intron"] <- "unspliced"
txis <- tximeta::splitSE(txi, cg, assayName = "counts")
#convert txis to a SingleCellExperiment object
txis <- as(txis, "SingleCellExperiment")
assays(txis) <- list(
counts = assay(txis, "spliced"),
spliced = assay(txis, "spliced"),
unspliced = assay(txis, "unspliced")
)
#removing cells with low gene counts and removing genes that are low across cells
qcstats <- perCellQCMetrics(txis)
qcfilter <- quickPerCellQC(qcstats)
txis <- txis[,!qcfilter$discard]
summary(qcfilter$discard)
#normalize
clusters <- quickCluster(txis)
txis <- computeSumFactors(txis, clusters = clusters)
txis <- scater::logNormCounts(txis)
txis <- scater::runPCA(txis)
txis <- scater::runTSNE(txis, dimred = "PCA")
#save sce object as RDS
saveRDS(txis, "BMMC_D1T1_txi_alevin_abundance.rds")
#class: SingleCellExperiment
#dim: 60289 3137
#metadata(6): tximetaInfo quantInfo ... txomeInfo txdbInfo
#assays(4): counts spliced unspliced logcounts
#rownames(60289): ENSG00000223972.5 ENSG00000243485.5 ... ENSG00000210194.1 ENSG00000210196.2
#rowData names(0):
#colnames(3137): GTCAAACTCATGACAC ATAGAGAGTTTGCAGT ... CAGCAATAGTCACTGT CGACAGCTCTGCGGAC
#colData names(1): sizeFactor
#reducedDimNames(2): PCA TSNE
#altExpNames(0):
print(sum(assay(txis, "spliced"))) #32361675
print(sum(assay(txis, "unspliced"))) #13566617
sessionInfo()
#R version 4.0.0 (2020-04-24)
#Platform: x86_64-w64-mingw32/x64 (64-bit)
#Running under: Windows >= 8 x64 (build 9200)
#Matrix products: default
#Random number generation:
#RNG: Mersenne-Twister
#Normal: Inversion
#Sample: Rounding
#locale:
#[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
#[4] LC_NUMERIC=C LC_TIME=English_United States.1252
#attached base packages:
#[1] stats4 parallel stats graphics grDevices utils datasets methods base
#other attached packages:
#[1] Rtsne_0.15 scran_1.17.0 scater_1.17.0 ggplot2_3.3.0
#[5] SingleCellExperiment_1.11.1 rjson_0.2.20 tximeta_1.7.3 SummarizedExperiment_1.19.0
#[9] DelayedArray_0.15.0 matrixStats_0.56.0 GenomicFeatures_1.41.0 AnnotationDbi_1.51.0
#[13] Biobase_2.49.0 eisaR_1.1.0 BSgenome_1.57.0 rtracklayer_1.49.0
#[17] GenomicRanges_1.41.0 GenomeInfoDb_1.25.0 Biostrings_2.57.0 XVector_0.29.0
#[21] IRanges_2.23.0 S4Vectors_0.27.0 BiocGenerics_0.35.0
#loaded via a namespace (and not attached):
#[1] ggbeeswarm_0.6.0 colorspace_1.4-1 ellipsis_0.3.0 depmixS4_1.4-2
#[5] BiocNeighbors_1.7.0 rstudioapi_0.11 bit64_0.9-7 interactiveDisplayBase_1.27.0
#[9] fansi_0.4.1 tximport_1.17.0 jsonlite_1.6.1 Rsamtools_2.5.0
#[13] dbplyr_1.4.3 shiny_1.4.0.2 BiocManager_1.30.10 compiler_4.0.0
#[17] httr_1.4.1 dqrng_0.2.1 assertthat_0.2.1 Matrix_1.2-18
#[21] fastmap_1.0.1 lazyeval_0.2.2 limma_3.45.0 cli_2.0.2
#[25] later_1.0.0 BiocSingular_1.5.0 htmltools_0.4.0 prettyunits_1.1.1
#[29] tools_4.0.0 igraph_1.2.5 rsvd_1.0.3 gtable_0.3.0
#[33] glue_1.4.0 GenomeInfoDbData_1.2.3 dplyr_0.8.5 rappdirs_0.3.1
#[37] Rcpp_1.0.4.6 vctrs_0.2.4 nlme_3.1-147 DelayedMatrixStats_1.11.0
#[41] stringr_1.4.0 beachmat_2.5.0 mime_0.9 lifecycle_0.2.0
#[45] irlba_2.3.3 ensembldb_2.13.1 statmod_1.4.34 XML_3.99-0.3
#[49] AnnotationHub_2.21.0 edgeR_3.31.0 zlibbioc_1.35.0 MASS_7.3-51.5
#[53] scales_1.1.1 hms_0.5.3 promises_1.1.0 ProtGenerics_1.21.0
#[57] AnnotationFilter_1.13.0 yaml_2.2.1 curl_4.3 gridExtra_2.3
#[61] memoise_1.1.0 biomaRt_2.45.0 stringi_1.4.6 RSQLite_2.2.0
#[65] BiocVersion_3.12.0 BiocParallel_1.23.0 truncnorm_1.0-8 rlang_0.4.6
#[69] pkgconfig_2.0.3 bitops_1.0-6 Rsolnp_1.16 lattice_0.20-41
#[73] purrr_0.3.4 GenomicAlignments_1.25.0 bit_1.1-15.2 tidyselect_1.1.0
#[77] magrittr_1.5 R6_2.4.1 DBI_1.1.0 pillar_1.4.4
#[81] withr_2.2.0 RCurl_1.98-1.2 nnet_7.3-13 tibble_3.0.0
#[85] crayon_1.3.4 BiocFileCache_1.13.0 viridis_0.5.1 progress_1.2.2
#[89] locfit_1.5-9.4 grid_4.0.0 blob_1.2.1 digest_0.6.25
#[93] xtable_1.8-4 httpuv_1.5.2 openssl_1.4.1 munsell_0.5.0
#[97] viridisLite_0.3.0 beeswarm_0.2.3 vipor_0.4.5 askpass_1.1 |
2740fd1d7ea05babb4b709d6db8f0fff991f9f5f | 6d37822046207d43d1f908e5af156c3a1379280a | /ExtractData.R | b995760243581e0244d3eb8735baa39f93dbf871 | [] | no_license | oharar/IM_warbler | 89bdbb0a4dd767dcffe3f38fb6272c4588199d06 | 04dca7c1e118baa718460c68850045aedce0b2ee | refs/heads/master | 2020-05-31T15:06:17.607680 | 2019-08-08T15:20:17 | 2019-08-08T15:20:17 | 190,348,676 | 8 | 3 | null | 2019-08-08T13:45:12 | 2019-06-05T07:39:52 | R | UTF-8 | R | false | false | 6,454 | r | ExtractData.R | # required packages
library(raster)
library(sf)
library(USAboundaries)
library(elevatr)
library(FedData)
library(dplyr)
library(censusapi)
library(spocc)
# You can get this with devtools::install_github("oharar/rBBS")
# library(rBBS)
if(!exists("censuskey")) {
warning("No US census bureau censuskey. If you don't have it, ask for one from https://api.census.gov/data/key_signup.html")
}
# required function
source("Functions/Add2010Census.R")
# the following packages need to be installed to download and format from
# scratch the data that is already included in this repository:
# devtools::install_github("oharar/rBBS")
# install.packages("plyr")
# install.packages("spocc")
# coordinate reference system to use throughout
proj <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
# Get outline of PA
PA <- USAboundaries::us_states(states = "Pennsylvania")
PA <- PA$geometry[1]
PA <- as(PA, "Spatial")
# BBA from Miller et al. appendix
if (!file.exists("Data/BBA.csv")) {
# Local Location of file with data from Miller et al. (2019)
# Data downloaded from here:
Miller.url <- "https://besjournals.onlinelibrary.wiley.com/action/downloadSupplement?doi=10.1111%2F2041-210X.13110&file=mee313110-sup-0001-supplementA.zip"
Miller.file <- "Data/mee313110-sup-0001-supplementa.zip"
# download the Miller file if needed
if (!file.exists(Miller.file)) {
download.file(Muller.url, Miller.file)
}
load(unzip(Miller.file, files = "DI_Data.Rdata"))
# sum counts (counts undertaken in 5 time intervals at a single spatial point)
BBA_Wren <- bba %>%
mutate(total = dplyr::select(., v1:v5) %>% rowSums(na.rm = TRUE)) %>%
dplyr::select(-c(v1:v5)) %>%
mutate(present = if_else(total == 0, FALSE, TRUE)) %>%
dplyr::rename(X = Longitude, Y = Latitude)
write.csv(BBA_Wren, file = "Data/BBA.csv")
} else {
BBA_Wren <- read.csv(file = "Data/BBA.csv")
}
# change to spatial dataframe
BBA_sp <- SpatialPointsDataFrame(
coords = BBA_Wren[, c("X", "Y")],
data = BBA_Wren[, c("present", "point")],
proj4string = crs(proj)
)
# Get BBS data (using rBBS package)
if (!file.exists("Data/BBS.csv")) {
library(rBBS)
source("Functions/GetBBSData.R")
ldply <- plyr::ldply
RegionMetaData <- GetRegions()
WeatherMetaData <- GetWeather()
RoutesMetaData <- GetRoutes()
idx <- RegionMetaData[["State/Prov/TerrName"]] == "PENNSYLVANIA"
PACode <- RegionMetaData$RegionCode[idx]
PAYears <- 2005:2009
# fixed getRouteData
RegionsForZipFiles <- GetRegions(ZipFiles = TRUE)
BBS_Wren <- GetRouteData(
AOU = 6540,
countrynum = 840,
states = PACode,
year = PAYears,
weather = WeatherMetaData,
routes = RoutesMetaData,
TenStops = FALSE,
Zeroes = TRUE
)
# counts are made along a route
# need to be made into number of presences and number of trials (routes)
BBS_Wren <- BBS_Wren %>%
mutate(NPres = rowSums(dplyr::select(., starts_with("stop")) > 0)) %>%
mutate(Ntrials = rowSums(!is.na(dplyr::select(., starts_with("stop"))))) %>%
group_by(route) %>%
summarise(
Ntrials = sum(Ntrials),
NPres = sum(NPres),
Latitude = first(Latitude),
Longitude = first(Longitude)
) %>%
dplyr::rename(X = Longitude, Y = Latitude)
# change to spatial points
BBS_Wren <- as.data.frame(BBS_Wren)
write.csv(BBS_Wren, file = "Data/BBS.csv")
} else {
BBS_Wren <- read.csv(file = "Data/BBS.csv")
}
BBS_sp <- SpatialPointsDataFrame(
coords = BBS_Wren[, c("X", "Y")],
data = BBS_Wren[, c("NPres", "Ntrials")],
proj4string = crs(proj)
)
# eBird, downloaded from GBIF
if (!file.exists("Data/eBird.csv")) {
eBird.raw <- spocc::occ(
query = "Setophaga caerulescens",
from = "gbif",
date = c("2005-01-01", "2005-12-31"),
geometry = PA@bbox
)$gbif
rows <- grep("EBIRD", eBird.raw$data$Setophaga_caerulescens$collectionCode)
cols <- c("longitude", "latitude", "year")
eBird <- eBird.raw$data$Setophaga_caerulescens[rows, cols]
# make into spatial points
eBird_coords <- cbind(eBird$longitude, eBird$latitude)
colnames(eBird_coords) <- c("X", "Y")
write.csv(eBird_coords, file = "Data/eBird.csv", row.names = FALSE)
} else {
eBird_coords <- read.csv(file = "Data/eBird.csv")
}
eBird_pts <- SpatialPoints(coords = eBird_coords, proj4string = proj)
# trim to keep only those occuring in PA (with probably unnecessary
# back-and-forth of data formats)
eBird_pts <- over(eBird_pts, PA)
eBird_pts <- data.frame(eBird_coords[!is.na(eBird_pts), ])
eBird_sp <- SpatialPoints(coords = eBird_pts, proj4string = proj)
# Covariates
# elevation data using elevatr (could theoretically also use FedData but get
# holes in elev raster)
elev <- elevatr::get_elev_raster(PA, z = 6, clip = "locations")
# z = 1 for lowest res, z = 14 for highest (DL time very long)
elevation <- as.data.frame(elev, xy = TRUE, na.rm = TRUE)
elevation$layer[elevation$layer < 0] <- 0
# canopy from the NLCD
NLCD_canopy <- get_nlcd(
template = PA,
year = 2011,
dataset = "canopy",
label = "PA_lc"
)
NLCD_canopy <- projectRaster(from = NLCD_canopy, to = elev)
NLCD_canopy <- mask(NLCD_canopy, elev)
canopy <- as.data.frame(NLCD_canopy, xy = TRUE, na.rm = TRUE)
covariates <- full_join(elevation, canopy, by = c("x", "y"))
# there seems to be a naming clash between different computers, so rather than sorting it out properly...
if(exists("PA_lc_NLCD_2011_canopy", covariates)) {
covariates <- covariates %>%
dplyr::rename(
elevation = layer, ## ????
canopy = PA_lc_NLCD_2011_canopy,
X = x, Y = y
)
} else {
covariates <- covariates %>%
dplyr::rename(
elevation = layer.x,
canopy = layer.y,
X = x, Y = y
)
}
covariate_coords <- covariates[, c("X", "Y")]
covariate_data <- covariates[, c("elevation", "canopy")]
covariates <- SpatialPointsDataFrame(
coords = covariate_coords,
data = covariate_data,
proj4string = crs(proj)
)
# scale the covariates
covariates@data <- data.frame(apply(covariates@data, 2, scale))
# Add population density
censuskey <- "ba4f7dd49b22e58b5e6a5cc99b349b555bbf95a8"
covariates_eBird <- Add2010Census(covariates, proj, censuskey)
covariates_eBird@data$FIPS <- as.numeric(covariates_eBird@data$FIPS)
covariates_eBird@data <- data.frame(apply(covariates_eBird@data, 2, scale))
# Save the data
save(
proj, PA, BBA_sp, BBS_sp, eBird_sp, covariates, covariates_eBird,
file = "Data/BTWarblerData.RData"
)
|
d903d680b917d2cf0f4248a15576b5790b31088c | b69ed244c07a3ada38a94b7cb79130dda3729e5c | /Part 6 - Reinforcement Learning/Section 32 - Upper Confidence Bound (UCB)/upper_confidence_bound_practice.R | 116a4894dc3f74b555f7506c8eb78f1546b19e79 | [] | no_license | ShubhamRoy96/Machine-Learning | 03b92fcb788d707adbf380396fb6fb3408b1b670 | 70ef90c9d60d50c85ea1bf5d1c2fc0427c071f17 | refs/heads/master | 2021-07-09T19:32:53.587927 | 2020-08-01T15:56:28 | 2020-08-01T15:56:28 | 242,486,683 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 962 | r | upper_confidence_bound_practice.R | dataset = read.csv('Ads_CTR_Optimisation.csv')
NumRows = nrow(dataset)
NumCol = ncol(dataset)
NtimeSelected = integer(NumCol)
SumofRewards = integer(NumCol)
ad_selected = integer(0)
total_reward = 0
for (row in 1:NumRows) {
ad = 0
max_UB = 0
for (lCol in 1:NumCol) {
if (NtimeSelected[lCol] > 0) {
avg_reward = SumofRewards[lCol] / NtimeSelected[lCol]
Delta_i = sqrt((3 / 2) * (log(row) / NtimeSelected[lCol]))
upper_bound = avg_reward + Delta_i
}
else
{
upper_bound = 10e400
}
if (upper_bound > max_UB)
{
max_UB = upper_bound
ad = lCol
}
}
ad_selected = append(ad_selected, ad)
NtimeSelected[ad] = NtimeSelected[ad] + 1
reward = dataset[row, ad]
SumofRewards[ad] = SumofRewards[ad] + reward
total_reward = total_reward + reward
}
hist(ad_selected,
col = "blue",
main = "Histogram of Selected ADs",
xlab = "AD",
ylab = "No of times selected")
|
a24ca92e25fedbd76bf31b6073ff297a1cfc3abe | 10e518cfefb3e44d245fa2ca35b809d4f0da9b38 | /tests/testthat/test-utils.R | 4f92f5be5928c3f488ca90e9d44ce2888ccf655c | [
"MIT"
] | permissive | bryanwhiting/bonds | e07048449ada74e40139c713209abd5f9f16913a | 0805a87b89b0554c811dd9cb8d7aed73ffc99254 | refs/heads/main | 2023-08-22T07:39:12.987012 | 2021-10-29T07:02:45 | 2021-10-29T07:02:45 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 442 | r | test-utils.R | test_that("extract_filenames() works", {
expect_equal(extract_file_idx(), 1:15)
})
test_that("create_filename() works", {
ans <- "/home/rstudio/data/data-challenge/data/interconnect_json/file_3.json"
obs <- as.character(create_filename(idx=3))
expect_equal(obs, ans)
})
test_that("read_parquet_table() works", {
x <- read_parquet_table('files', range=4:6)
expect_true(min(x$file_id) == 4)
expect_true(max(x$file_id) == 6)
})
|
dfeece8055fe5d381d3c65d785998b9c515f382f | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/mmsample/examples/mmatcher.Rd.R | e992f6d0b4aacce3a9c6f48b877b15b325c388c3 | [] | 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 | 691 | r | mmatcher.Rd.R | library(mmsample)
### Name: mmatcher
### Title: Multivariate Matching
### Aliases: mmatcher
### ** Examples
treat_n <- 100
control_n <- 300
n <- treat_n + control_n
set.seed(123)
df <- data.frame(age = round(c(rnorm(control_n, 40, 15), rnorm(treat_n, 60, 15)), 2),
male = c(rbinom(control_n, 1, 0.4), rbinom(treat_n, 1, 0.6)),
grp = c(rep(0, control_n), rep(1, treat_n)))
df$age[df$age < 20 | df$age > 95] <- NA
matched_df <- mmsample::mmatcher(df, "grp", c("age", "male"))
tapply(df$age, df$grp, quantile, na.rm = TRUE)
tapply(matched_df$age, matched_df$grp, quantile, na.rm = TRUE)
table(df$male, df$grp)
table(matched_df$male, matched_df$grp)
|
b1e3e4c3292f65ec8d79254978da6d35f1d0d0f6 | 038d8bd41fb3bed9cc4061db12d7d4ec71a62c37 | /man/AxisLabels.Rd | 3e801d65e67e34f30a757474f30c73c693762deb | [] | no_license | arnhew99/Jasper | 32af0ee0dc39199b7406c69d82d930d9f2c5440c | 56dff2546464b5dfed2e3704f60e8e5a32f86d45 | refs/heads/master | 2022-11-17T14:34:17.901352 | 2022-11-11T17:55:31 | 2022-11-11T17:55:31 | 248,270,015 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 557 | rd | AxisLabels.Rd | \name{AxisLabels}
\alias{AxisLabels}
\title{AxisLabels}
\description{Add X and Y axis labels to the current panel.}
\arguments{
\item{xlab}{X axis label}
\item{ylab}{Y axis label}
\item{mainfont}{Font scaling applied to cex (default: NULL)}
\item{xline}{Margin line of the X axis label (default: 3.5)}
\item{yline}{Margin line of the Y axis label (default: 4)}
\item{cex}{Font scaling factor (multiplies the underlying panel "unit" font size) (default: NULL)}
\item{adj}{Alignment of the axis labels, as adj in text() (default: 0.5)}
}
\author{Matt Arnold}
|
831822fea3c099c0b51b6c583fe4afc19718c4c7 | 16ca517e00f11cf74ace22122fbee214e12f9939 | /snp_pca.R | 2b7648b04302293d8e30649937dcca38aef3c3bc | [] | no_license | ODiogoSilva/vcf2PCA | 522c7d4afbab438b8cf423525bb604ac38948a7f | 403f99f3aacee27f233efed0ec65f0c7a65eded8 | refs/heads/master | 2022-05-18T02:13:20.866374 | 2022-04-15T14:29:42 | 2022-04-15T14:29:42 | 96,434,641 | 7 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,152 | r | snp_pca.R | #!/usr/bin/Rscript
# snp_pca.R performs a PCA using the SNPRelate R package using a VCF file
# and an option populations files
# Usage:
# snp_pca.R vcf_file output_file_name popupations_file[optional]
library("SNPRelate")
library("plotly")
library(htmlwidgets)
library(htmltools)
args <- commandArgs(trailingOnly = TRUE)
# Get arguments
vcf_file <- args[1]
output_name <- args[2]
pops_file <- args[3]
# Convert VCF to gds
snpgdsVCF2GDS(vcf_file, "temp.gds", method="biallelic.only")
# Open GDS file
genofile <- snpgdsOpen("temp.gds")
# Run PCA
pca <- snpgdsPCA(genofile, num.thread=1, autosome.only=F)
pc.percent<- pca$varprop * 100
print(round(pc.percent, 2))
# Open figure driver
#pdf(paste(output_name, ".pdf", sep=""))
# Plots PCA
if (!is.na(pops_file)) {
sample.id <- read.gdsn(index.gdsn(genofile, "sample.id"))
pop_code <- read.table(pops_file, sep=",")
sorted_pops <- pop_code$V2[order(match(pop_code$V1, sample.id))]
tab <- data.frame(sample.id = pca$sample.id,
pop = sorted_pops,
EV1 = pca$eigenvect[,1],
EV2 = pca$eigenvect[,2],
stringsAsFactors=F)
#save(tab, file=paste(output_name, ".Rdata", sep=""))
p <- plot_ly(tab, x=tab$EV1, y=tab$EV2, text=tab$sample.id, color=tab$pop, colors="Set2")
p <- layout(p, title="PCA",
xaxis=list(title=paste("PC 1(", round(pca$eigenval[1], d=2) , "%)")),
yaxis=list(title=paste("PC 1(", round(pca$eigenval[2], d=2) , "%)")))
htmlwidgets::saveWidget(as.widget(p), paste(output_name, ".html", sep=""))
} else {
tab <- data.frame(sample.id = pca$sample.id,
EV1 = pca$eigenvect[, 1],
EV2 = pca$eigenvect[, 2],
stringsAsFactors=F)
print(pca$sample.id)
print(tab$EV1)
print(tab$EV2)
p <- plot_ly(tab, x=tab$EV1, y=tab$EV2, text=tab$sample.id)
p <- layout(p, title="PCA",
xaxis=list(title=paste("PC 1(", round(pca$eigenval[1], d=2) , "%)"),
yaxis=list(title=paste("PC 2(", round(pca$eigenval[2], d=2) , "%)"))))
}
p <- htmlwidgets::appendContent(p,
htmltools::tags$input(id='inputText',
value='', ''),
htmltools::tags$button(id='buttonSearch',
'Search'))
p <- htmlwidgets::appendContent(p, htmltools::tags$script(HTML(
'document.getElementById("buttonSearch").addEventListener("click", function()
{
var i = 0;
var j = 0;
var found = [];
var myDiv = document.getElementsByClassName("js-plotly-plot")[0]
var data = JSON.parse(document.querySelectorAll("script[type=\'application/json\']")[0].innerHTML);
console.log(data.x.data)
for (i = 0 ;i < data.x.data.length; i += 1) {
for (j = 0; j < data.x.data[i].text.length; j += 1) {
if (data.x.data[i].text[j].indexOf(document.getElementById("inputText").value) !== -1) {
found.push({curveNumber: i, pointNumber: j});
}
}
}
Plotly.Fx.hover(myDiv, found);
}
);')))
htmlwidgets::saveWidget(as.widget(p), paste(output_name, ".html", sep=""))
# remove temporary gds file
file.remove("temp.gds")
|
5d1abba8674b5ee8f699caca63d18ae7c70a4ae0 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/Delta/examples/GetDeltaProblemType.Rd.R | 982706d09ff0352524895562e1b044b0ec43771c | [] | 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 | 269 | r | GetDeltaProblemType.Rd.R | library(Delta)
### Name: GetDeltaProblemType
### Title: Get Delta problem type function
### Aliases: GetDeltaProblemType
### Keywords: Mx
### ** Examples
GetDeltaProblemType(matrix(c(1,2,0,3,4,0,0,0,1),3,3))
GetDeltaProblemType(matrix(c(1,0,0,0,2,0,0,0,3),3,3))
|
ede9085ee6fb5a43bde3b1f4a9a6f09840ce0ea6 | bf8e155d3f6a835082c7a17d9c9fa2a8c4e0331e | /R/DataImportDialog.R | f3dc1782fe2e6eff8e81b8d422f061d1d985d083 | [] | no_license | sebkopf/dfv | 94ba5e2fab9013e42601eeff4ac8865a9969f1bc | 55fcc88a81e26ef039ef3dd9a6707386b306e02b | refs/heads/master | 2016-09-02T02:39:00.117472 | 2015-12-10T20:45:57 | 2015-12-10T20:45:57 | 14,060,261 | 0 | 0 | null | 2014-02-04T07:00:04 | 2013-11-02T03:40:37 | R | UTF-8 | R | false | false | 14,916 | r | DataImportDialog.R | #' @include ModalDialog.R
NULL
DataImportDialogGui <- setClass("DataImportDialogGui", contains="ModalDialogGui")
setMethod("getToolbarXML", "DataImportDialogGui", function(gui, module) {
return (
'<separator expand="true"/>
<toolitem action="Copy"/>
<separator expand="true"/>
<toolitem action="Run"/>
<separator expand="true"/>
<toolitem action="Ok"/>
<separator expand="true"/>
</toolbar>
<toolbar name="toolbar2">
<separator expand="true"/>
<toolitem action="FromCb"/>
<separator expand="true"/>
<toolitem action="FromExcel"/>
<separator expand="true"/>')
})
setMethod("getMenuXML", "DataImportDialogGui", function(gui, module) {
return (
'<menu name = "Import" action="Import">
<menuitem action="FromCb"/>
<menuitem action="FromExcel"/>
</menu>
<menu name = "Code" action="Code">
<menuitem action="Copy"/>
<menuitem action="Run"/>
</menu>'
)
})
setMethod("makeNavigation", "DataImportDialogGui", function(gui, module) {
uimanager <- callNextMethod()
# top toolbar
toolbarGrp <- getWidgets(gui, module, 'topToolbarGrp')
getToolkitWidget(toolbarGrp)$packStart (uimanager$getWidget ( "/toolbar2" ), TRUE) # add toolbar
return(uimanager)
})
setMethod("setNavigationActions", "DataImportDialogGui", function(gui, module, actionGrp) {
callNextMethod()
nav.actions <-
list(## name, icon, label , accelerator , tooltip , callback
list ("Import", NULL , "_Import" , NULL, NULL, NULL),
list ("FromCb", "gtk-convert", "From Clipboard", "<ctrl>P", "Paste data from clipboard",
function(...) {
getElements(gui, module, 'dataTable')$destroyGui()
getElements(gui, module, 'columnsTable')$setTableData(getElements(gui, module, 'columnsTable')$getTableData(0))
setSettings(gui, module, mode = 'clipboard')
getElements(gui, module, 'optionsTable')$changeColumnVisibility(c(3,4), c(TRUE, FALSE))
getModule(gui, module)$generateCode()
} ),
list ("FromExcel", "gtk-select-color", "From Excel", "<ctrl>E", "Import data from Excel file",
function(...) {
f=gfile("Select Excel file to import.", type="open", cont = getWindow(gui, module),
filter = list("Excel Files" = list(patterns=c("*.xls", "*.xlsx")), "All files" = list(patterns = c("*"))))
if (!is.na(f)){
getElements(gui, module, 'dataTable')$destroyGui()
getElements(gui, module, 'columnsTable')$setTableData(getElements(gui, module, 'columnsTable')$getTableData(0))
setData(gui, module, file = f)
setSettings(gui, module, mode = 'excel')
# add sheets in excel workbook to the options GUI (requires remaking the table)
getElements(gui, module, 'optionsTable')$destroyGui()
options <- getElements(gui, module, 'optionsTable')$getData('frame')
excel_sheets <- excel_sheets(f)
options$`Excel sheet` <- factor(excel_sheets[1], levels = excel_sheets)
getElements(gui, module, 'optionsTable')$setData(frame = options)
getElements(gui, module, 'optionsTable')$makeGui(
getWidgets(gui, module, 'optionsGrp'),
changedHandler = function(...){
# empty preview table
getElements(gui, module, 'columnsTable')$setTableData(getElements(gui, module, 'columnsTable')$getTableData(0))
# generate code
getModule(gui, module)$generateCode()
})
getElements(gui, module, 'optionsTable')$loadGui()
getElements(gui, module, 'optionsTable')$changeColumnVisibility(c(3,4), c(FALSE, TRUE))
# generate code
getModule(gui, module)$generateCode()
}
} ),
# list ("FromCSV", "gtk-copy", "From Clipboard", "<ctrl>P", "Import data from CSV file",
# function(...) {
# gmessage("sorry, work in progress...")
# } ),
list ("Code", NULL , "_Code" , NULL, NULL, NULL),
list ("Run", "gtk-execute", "Run code", "<ctrl>R", "Execute code for tab", function(...) getModule(gui, module)$runCode(global = TRUE) ),
list ("Copy", "gtk-copy", "Copy code", "<ctrl>C", "Copy code to clipboard",
function(...) {
copyToClipboard(getModule(gui, module)$getWidgetValue('code'))
showInfo(gui, module, msg="INFO: code copied to clipboard.", okButton = FALSE, timer = 2)
}))
actionGrp$addActions(nav.actions)
})
setMethod("makeMainGui", "DataImportDialogGui", function(gui, module) {
setMenuGroup(gui, module, ggroup(horizontal=FALSE, cont=getWinGroup(gui, module), spacing=0))
setWidgets(gui, module, topToolbarGrp = ggroup(horizontal=FALSE, cont=getWinGroup(gui, module), spacing=0))
mainGrp <- ggroup(horizontal=FALSE, cont=getWinGroup(gui, module), spacing=0, expand=TRUE)
# groups
optionsGrp <- ggroup(container = mainGrp)
columnsGrp <- gframe("Columns")
dataGrp <- gframe("Data (first 10 rows)")
codeGrp <- gframe("Code", expand=TRUE)
tbPane <- gpanedgroup(dataGrp, codeGrp, expand=TRUE, horizontal=FALSE)
tbPane2 <- gpanedgroup(columnsGrp, tbPane, container=mainGrp, expand=TRUE, horizontal=FALSE)
setWidgets(gui, module, tbPane2 = tbPane2, tbPane = tbPane, optionsGrp = optionsGrp, dataGrp = dataGrp)
# options table
options <- DataTable$new()
setElements(gui, module, optionsTable = options)
options$setSettings(editableColumns = names(options$getData('frame')))
options$makeGui(optionsGrp, changedHandler = function(...) getModule(gui, module)$generateCode())
options$changeColumnVisibility(c(3,4), xor(getSettings(gui, module, 'mode') == 'clipboard', c(FALSE, TRUE)))
# columns table
columns <- DataTable$new()
setElements(gui, module, columnsTable = columns)
columns$setSettings(editableColumns = c("Import", "Type"), resizable = TRUE)
columns$makeGui(columnsGrp, changedHandler = function(...) getModule(gui, module)$generateCode())
# data table
dataT <- DataTable$new()
setElements(gui, module, dataTable = dataT)
dataT$setSettings(sortable = TRUE, resizable = TRUE)
# code (attributes don't seem to work sadly)
setWidgets(gui, module, code = gtext('', wrap=TRUE, font.attr = c(style="normal", weights="bold",sizes="medium"), container = codeGrp, expand = TRUE, height=50))
})
DataImportDialog <- setRefClass(
'DataImportDialog',
contains = 'ModalDialog',
methods = list(
initialize = function(gui = new("DataImportDialogGui"), ...){
callSuper(gui = gui, ...)
### overwrite default setting for DataImportDialog
setSettings(
windowSize = c(450, 700),
windowTitle = "Import data",
ok.label = "Done",
ok.tooltip = "Close import window",
protect = TRUE
)
# new option (not protected, can be overwritten by user preference)
setSettings(
tbPane2 = 0.4,
tbPane = 0.3,
mode = 'clipboard'
)
# default data for the data import dialog and all its elements
setData(
file = "",
optionsTable = list(
frame = data.frame( # all the options for formats
Variable = 'data',
`Header row?` = TRUE,
Separator = factor("tab", levels = c(",", "tab", ";")),
`Excel sheet` = factor('Sheet1', levels = c('Sheet1')),
`Start row` = as.integer(1),
check.names = FALSE,
stringsAsFactors = FALSE),
selectedRows = 1
),
columnsTable = list(
frame = data.frame(
Name = character(0),
Import = logical(0),
Type = factor(levels=c("Text", "Number", "Date", "Date + Time", "Factor")),
Values = character(0),
stringsAsFactors = F
)),
dataTable = list(
frame = data.frame(Data = character(0), Frame = character(0)))
)
},
# ' Generate the code for excel import
generateCode = function() {
options <- getElements('optionsTable')$getTableData(rows = 1)
variable <- getElements('optionsTable')$getTableData(1, 'Variable')
if (getSettings('mode') == 'clipboard') {
code <- paste0(
"\n# Read data frame from clipboard\n",
sprintf("%s <- read.clipboard (\n\theader = %s, sep = '%s', skip = %s, comment.char='', \n\trow.names = NULL, stringsAsFactors = FALSE",
options[[1]], options[[2]], sub('tab', '\\\\t', options[[3]]), options[[5]] - 1))
code.1 <- paste0(code, ", nrows=1)") # code for 1 line excerpt to find data types
} else if (getSettings('mode') == 'excel') {
code <- paste0(
"\nlibrary(readxl) # only needed once in file",
"\n# Read data frame from Excel file\n",
sprintf("%s <- read_excel(\n\t'%s', \n\tsheet = '%s',\n\tcol_names = %s",
options[[1]], getData('file'), options[[4]], options[[2]]))
code.1 <- code #paste0(sub("read.xlsx2", "read.xlsx", code), ", rowIndex = ", options[[5]] + 1, ":", options[[5]] + 2, ")") # code for 1 line excerpt to find data types
code <- paste0(code, ", skip = ", options[[5]] - 1)
}
# check if there are columns defined yet
defined <- nrow(getElements('columnsTable')$getTableData()) > 0
if (defined) {
types <- getElements('columnsTable')$getTableData(columns = 'Type')
code <- paste0(code, ", \n\tcol_types = c('",
paste(sapply(types, function(type) {
switch(as.character(type),
'Date + Time' = 'date',
'Date' = 'date',
'Number' = 'numeric',
'text')
}), collapse = "', '"), "')")
} else {
# try to guess data types of the individual columns by running the script for the first column (silent if it doesn't work)
tryCatch({
eval(parse(text = code.1))
df <- get(variable)
code <- paste0(code, ", \n\tcol_types = c('", paste(sapply(df, function(col) { class (col)[1] }), collapse = "', '"), "')")
}, error = function(e) {}, warning = function(e) {})
}
code <- paste0(code, ")")
# initialize factors
if (defined) {
types <- getElements('columnsTable')$getTableData(columns = 'Type')
factors <- (paste0(sapply(1:length(types), function(i) {
if (as.character(types[i]) == 'Factor')
paste0('\n', variable, '[,', i,'] <- as.factor(', variable, '[,', i, '])')
else
''
}), collapse = ""))
if (factors != "")
code <- paste0(code, "\n\n# Convert factor columns", factors)
}
# remove unwanted columns
delColsCode <- ""
if (defined) {
import <- getElements('columnsTable')$getTableData(columns = 'Import')
if (length(exclude <- which(!import)) > 0)
delColsCode <- paste0("\n\n# Remove unwanted columns\n", variable, ' <- ', variable, '[, -c(', paste0(exclude, collapse=", "), ')]')
}
# set code and run it
setData(delColsCode = delColsCode) # need to know what this is to execute it separately
loadWidgets(code = paste0(code, delColsCode))
runCode(global = FALSE)
},
# Run the code
# ' @param global (whether to run in the global environment - warning! if TRUE, can change variables in global scope!)
runCode = function(global = FALSE) {
# get code
code <- getWidgetValue('code')
delColsCode <- getData('delColsCode')
importCode <- if (delColsCode == "") code else gsub(delColsCode, "", code, fixed=TRUE)
# variable name
variable <- getElements('optionsTable')$getTableData(1, 'Variable')
# error function when there is trouble with the code
errorFun<-function(e) {
err <- if (getSettings('mode') == 'clipboard') 'Make sure you have a data table copied to the clipboard.\n' else ''
showInfo(gui, .self, msg=paste0("ERROR: There are problems running this code.\n", err, capture.output(print(e))), type="error", timer=NULL, okButton = FALSE)
stop(e)
}
# try to run import (locally / globally)
tryCatch(eval(parse(text = importCode)), error = errorFun, warning = errorFun)
# check what's in data frame
df <- get(variable)
# update columns table if this is a different data frame
if (!identical(names(df), getElements('columnsTable')$getTableData(columns = 'Name'))) {
types <- sapply(df, function(x) {
switch(class(x)[1],
'integer' = 'Number',
'numeric' = 'Number',
'POSIXct' = 'Date + Time',
'Date' = 'Date',
'Text')})
getElements('columnsTable')$setTableData(
data.frame(
Name = names(df),
Import = TRUE,
Type = factor(types, levels=c("Text", "Number", "Date", "Date + Time", "Factor")),
Values = sapply(head(df, n=3), function(x) { paste0(paste(x, collapse=", "), ' ...') }),
stringsAsFactors = F))
}
# try to run delete code
if (delColsCode != "")
tryCatch(eval(parse(text = delColsCode)), error = errorFun, warning = errorFun)
df <- get(variable)
# show data frame in data table (need to convert dates first though)
showdf <- head(df, n=10)
types <- sapply(showdf, function(col) class(col)[1])
for (i in which(types == "Date"))
showdf[,i] <- format(showdf[,i], "%Y-%m-%d")
for (i in which(types == "POSIXct"))
showdf[,i] <- format(showdf[,i], "%Y-%m-%d %H:%M:%S")
dataTable <- getElements('dataTable')
dataTable$destroyGui()
dataTable$setData(frame = showdf)
dataTable$makeGui(getWidgets('dataGrp'))
dataTable$loadGui()
# store in global variable and show success message
if (global) {
assign(variable, df, envir=.GlobalEnv)
showInfo(gui, .self, msg=paste0("SUCCESS! Data Frame '", variable, "' created."), timer = NULL, okButton = FALSE)
} else
showInfo(gui, .self, msg="INFO: All clear, code can be run.", okButton = FALSE, timer = NULL)
}
)
)
# Testing
test <- function() {
t <- DataImportDialog$new()
t$setSettings(windowModal = FALSE, mode = 'excel') # easier for testing purposes
# t$setData(file = '/Users/sk/Dropbox/Tools/software/r/dfv/Workbook1.xlsx')
t$makeGui()
# Sys.sleep(1)
# t$generateCode()
}
|
9cca4f4df05c76c96dcc076196ed719768b554ba | ddc8c8f96c348abeccba5fc31ed01844d093b33b | /Shirley/Fig1G_gprofiler_barplot.R | 5aae35548b704eb110fd5f642b3a2288a9d6e0cb | [
"MIT"
] | permissive | hypdoctor/Lawson2020 | b47c4fa8c67ccfe5f2ccf7d55cc12ee464943fa2 | 82662ff8183307ec09439dc001834537ec00bda3 | refs/heads/master | 2023-03-16T04:18:55.757725 | 2020-09-23T16:45:18 | 2020-09-23T16:45:18 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,851 | r | Fig1G_gprofiler_barplot.R | # Date: Sep 28, 2018
# Author: Shirley Hui
# Takes pathway themes manually identified via a Cytoscape network created using the the core killing gprofiler results (see CoreKillingGProfiler.R). Pathways were grouped together to form themes if they contained 30% or more similar genes. Plot the pathway themes into bar plot.
# Input: core killing gprofiler results, core killing enrichment themes
# Output: Bar plot of core killing enriched themes
gprofilerResults<- read.delim("/Users/Keith/Desktop/Revision Docs/Pathway analysis/Output/gprofiler_results/coreCTLgenes_gprofiler.txt")
emThemes <- read.delim("/Users/Keith/Desktop/Revision Docs/Pathway analysis/Output/enr_file/coreCTLgenes_sim0.7_enrTheme.txt",header=FALSE)
themes <- as.character(unique(emThemes[,1]))
results <- c()
for (ixx in 1:length(themes)) {
ix <- which(emThemes[,1]==themes[ixx])
ixs <- c()
for (i in 1:length(ix)) {
goid <- as.character(emThemes[ix[i],2])
ixi <- which(gprofilerResults$term.id==goid)
ixs <- c(ixs,ixi)
}
mean_overlap <- mean(gprofilerResults[ixs,]$overlap.size/gprofilerResults[ixs,]$term.size)*100
mean_overlap.size <- mean(gprofilerResults[ixs,]$overlap.size)
mean_term.size <- mean(gprofilerResults[ixs,]$term.size)
min_pvalue <- -log(min(gprofilerResults[ixs,]$p.value))
results <- rbind(results,c(mean_overlap,min_pvalue,mean_overlap.size,mean_term.size))
}
rownames(results) <- themes
colnames(results) <- c("overlap","p.value","overlap.size","term.size")
library(ggplot2)
library(RColorBrewer)
#cbPalette <- c("#FED976", "#FD8D3C", "#FC4E2A", "#E31A1C", "#aa0022")
cbPalette <- c("#ededed", "#cccccc", "#969696", "#636363", "#252525") #http://colorbrewer2.org/#type=sequential&scheme=Greys&n=5
cols = cbPalette #<- brewer.pal(6, "YlOrRd")
df = data.frame(results)
df$ratio <- paste(round(df$overlap.size,1), round(df$term.size, 1), sep = "/") #this line adds the overlap/term size ratio, rounds up the term size to xx position after comma
g = ggplot(df, aes(x = reorder (rownames(df),p.value), y = overlap)) +
ylab("Mean Percentage Overlap") +
theme(plot.title = element_text(hjust = -0.9)) +
geom_col(aes(fill = p.value)) +
geom_text(aes(label = df$ratio, hjust=0))+
scale_fill_gradientn("-log p", colours = cols, limits=c(min(df$p.value), max(df$p.value))) +
scale_y_continuous(position = "right") +
theme(panel.background = element_rect(fill = "white"), axis.line.x = element_line(color="black"), axis.line.y = element_line(color="white"), axis.title.y = element_blank(),axis.ticks.y = element_blank()) +
coord_flip()
# Adjust aspect_ratio, height and width to output figure to pdf in the desired dimensions
aspect_ratio <- 1.75
ggsave(file="/Users/Keith/Desktop/Revision Docs/Pathway analysis/Output/coreCTLgenes_sim0.7.pdf",g, height = 4 , width = 5 * aspect_ratio)
|
197e9cff1cf0916b06733a75e13bb7f5860b5788 | 6eb980a9312f50491782a92875a52618dfbcffc6 | /tests/testthat/test-get_available_packages.R | 6364ab3398411eb8802c95bd036eb645db5fc26c | [] | no_license | cran/deepdep | d9636bb8dd22b64e86b893adb2c0873ea87068c4 | 74b4aafcb30d8d1bde5e212c6187d052180a7e94 | refs/heads/master | 2023-03-05T18:45:35.804669 | 2023-02-20T23:10:05 | 2023-02-20T23:10:05 | 245,601,598 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 366 | r | test-get_available_packages.R | test_that("getting available packages from both local and bioc returns an error", {
expect_error(get_available_packages(local = TRUE, bioc = TRUE),
"You cannot use both 'local' and 'bioc' options at once.")
})
test_that("chache is cleared without errors", {
expect_error(get_available_packages(local = TRUE, reset_cache = TRUE), NA)
})
|
8e247d836bc90b064c3f725b4f97bdb467984355 | 65938f7359b84cb41f0d1d5dc1ee5964bc7f6147 | /Algorithms/K-Nearest Neighbour Classifier/Glass Data/GlassKNN.R | b97b4652b08df73791682b23fdd31dd4c1550f79 | [] | no_license | Rashmi1404/Data-Science-R-code | d9565ad1d0fe62dfd25380b9367dd5cff17a769b | d7e1120569ba194bab7af947993e87c43eff6ef6 | refs/heads/master | 2020-12-29T14:52:21.155154 | 2020-08-07T15:17:16 | 2020-08-07T15:17:16 | 238,642,421 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 7,331 | r | GlassKNN.R | #K-Nearest Neighbour Classifier
#Prepare a model for glass classification using KNN
set.seed(123)
library(ggplot2)
#Lets Import the Data
glass <- read.csv(file.choose())
attach(glass)
summary(glass)# to get the Summary of the Dataset
str(glass) #Here we can see that Type variable is recognized as Integer. We have to change it into Categorical Variable
glass$Type <- as.factor(glass$Type)
colnames(glass) #Gives the Column names of the Dataset
dim(glass) #Gives the Number of Rows and COlumns of the Dataset
#Standard Deviation
sd(RI)
sd(Na)
sd(Mg)
sd(Al)
sd(Si)
sd(K)
sd(Ca)
sd(Ba)
sd(Fe)
#Variance
var(Ri)
var(Na)
var(Mg)
var(Al)
var(Si)
var(K)
var(Ca)
var(Ba)
var(Fe)
#Plots
ggplot(glass, aes(x=Na)) +geom_histogram( binwidth=0.5, fill="#69b3a2", color="#e9ecef", alpha=0.9) + ggtitle("Plot for Na") +theme_gray()
ggplot(glass, aes(x=Mg)) +geom_histogram( binwidth=0.3, fill="#69b3a2", color="#e9ecef", alpha=0.9) + ggtitle("Plot for Mg") +theme_gray()
ggplot(glass, aes(x=RI)) +geom_histogram( binwidth=0.0005, fill="#69b3a2", color="#e9ecef", alpha=0.9) + ggtitle("Plot for Refractive Index") +theme_gray()
ggplot(glass, aes(x=Fe)) +geom_histogram( binwidth=0.045, fill="#69b3a2", color="#e9ecef", alpha=0.9) + ggtitle("Plot for Fe") +theme_gray()
#Lets derive the Normalization Function
normalise <- function(x) {
return((x - min(x))/(max(x) - min(x)))
}
#Lets apply the Function on the Data
glas_n <- as.data.frame(lapply(glass[,-10], normalise))
glass_nl <- cbind(glas_n, glass$Type) #Combining the Normlized data and the Type Column
#Lets Divide the DataSet into Training and Testing Sets
library(caret)
indatapartition <- createDataPartition(glass_nl$`glass$Type`, p=.70, list = FALSE)
training <- glass_nl[indatapartition,]
testing <- glass_nl[-indatapartition,]
#Lets Build the KNN model
library(class)
class_identifier <- knn(train = training[,-10], test = testing[,-10], cl = training[,10], k=1) #cl stands for Classification
class_identifier
#Lets Evaluate the Accuracy of the Model
library(gmodels)
CrossTable(testing$`glass$Type`, class_identifier, prop.r = F, prop.c = F, prop.chisq = F)
tab <- table(testing$`glass$Type`, class_identifier)
Accuracy <- round(sum(diag(tab))/sum(tab)*100, digits = 2) #Here Digits attribute Specifies the Number of digits after Decimal Point
Accuracy
#Accuracy for k=1 is 65.57
#Lets see the Accuracy for Different K values
#For k= 3
class_identifier1 <- knn(train = training[,-10], test = testing[,-10], cl = training[,10], k=3)
CrossTable(testing$`glass$Type`, class_identifier1, prop.r = F, prop.c = F, prop.chisq = F)
tab <- table(testing$`glass$Type`, class_identifier1)
Accuracy <- round(sum(diag(tab))/sum(tab)*100, digits = 2)
Accuracy
#Accuracy for k= 3 is 62.3
#For k = 5
class_identifier2 <- knn(train = training[,-10], test = testing[,-10], cl = training[,10], k=5)
CrossTable(testing$`glass$Type`, class_identifier2, prop.r = F, prop.c = F, prop.chisq = F)
tab <- table(testing$`glass$Type`, class_identifier2)
Accuracy <- round(sum(diag(tab))/sum(tab)*100, digits = 2)
Accuracy
#Accuracy for k = 5 is 63.93
#For k=10
class_identifier3 <- knn(train = training[,-10], test = testing[,-10], cl = training[,10], k=11)
CrossTable(testing$`glass$Type`, class_identifier3, prop.r = F, prop.c = F, prop.chisq = F)
tab <- table(testing$`glass$Type`, class_identifier3)
Accuracy <- round(sum(diag(tab))/sum(tab)*100, digits = 2)
Accuracy
#Accuracy for k=10 is again 60.66
#So as we can see that the Accuracy is not Increasing for different k values
#Lets Improve the Model Performance
#Lets Scale the Values of the Dataset Using Scale() function
glass_sc <- as.data.frame(scale(glass[,-10]))
glass_scaled <- cbind(glass_sc, glass$Type)
#Lets Divide the Data in Training and Testing Sets
indatapartition1 <- createDataPartition(glass_scaled$`glass$Type`, p=.50, list = FALSE)
train_scaled <- glass_scaled[indatapartition1,]
test_scaled <- glass_scaled[-indatapartition1,]
#Lets Build the KNN Classifier Model for Scaled Values
class1 <- knn(train = train_scaled[,-10], test = test_scaled[,-10], cl = train_scaled[,10], k=2)
CrossTable(test_scaled$`glass$Type`, class1, prop.r = F, prop.c = F,prop.chisq = F)
tab1 <- table(test_scaled$`glass$Type`, class1)
Acc1 <- round(sum(diag(tab1))/sum(tab1)*100, digits = 3)
Acc1
#Accuracy for Scaled Model with k=2 is 71.429
#So here We can see that the Model has been Improved using Scale Function. Lets do it for Different k values
#For k=5
class2 <- knn(train = train_scaled[,-10], test = test_scaled[,-10], cl = train_scaled[,10], k=5)
CrossTable(test_scaled$`glass$Type`, class2, prop.r = F, prop.c = F,prop.chisq = F)
tab2 <- table(test_scaled$`glass$Type`, class2)
Acc2 <- round(sum(diag(tab2))/sum(tab2)*100, digits = 3)
Acc2
#For k=5 we got Accuracy as 64.762
#For k=6
class3 <- knn(train = train_scaled[,-10], test = test_scaled[,-10], cl = train_scaled[,10], k=6)
CrossTable(test_scaled$`glass$Type`, class3, prop.r = F, prop.c = F,prop.chisq = F)
tab3 <- table(test_scaled$`glass$Type`, class3)
Acc3 <- round(sum(diag(tab3))/sum(tab3)*100, digits = 3)
Acc3
#For k = 6 we got 70.476% Accuracy
#Lets see for k=11
class4 <- knn(train = train_scaled[,-10], test = test_scaled[,-10], cl = train_scaled[,10], k=11)
CrossTable(test_scaled$`glass$Type`, class4, prop.r = F, prop.c = F,prop.chisq = F)
tab4 <- table(test_scaled$`glass$Type`, class4)
Acc4 <- round(sum(diag(tab4))/sum(tab4)*100, digits = 3)
Acc4
#For k=11 we got Accuracy as 66.667%
#For k=16
class5 <- knn(train = train_scaled[,-10], test = test_scaled[,-10], cl = train_scaled[,10], k=16)
CrossTable(test_scaled$`glass$Type`, class5, prop.r = F, prop.c = F,prop.chisq = F)
tab5 <- table(test_scaled$`glass$Type`, class5)
Acc5 <- round(sum(diag(tab5))/sum(tab5)*100, digits = 3)
Acc5
#For k=16, the Accuracy is 69.524%
#for k=1
class6 <- knn(train = train_scaled[,-10], test = test_scaled[,-10], cl = train_scaled[,10], k=1)
CrossTable(test_scaled$`glass$Type`, class6, prop.r = F, prop.c = F,prop.chisq = F)
tab6 <- table(test_scaled$`glass$Type`, class6)
Acc6 <- round(sum(diag(tab6))/sum(tab6)*100, digits = 3)
Acc6
#The Accuracy for k=1 is 70.476%
#for k=21
class7 <- knn(train = train_scaled[,-10], test = test_scaled[,-10], cl = train_scaled[,10], k=21)
CrossTable(test_scaled$`glass$Type`, class7, prop.r = F, prop.c = F,prop.chisq = F)
tab7 <- table(test_scaled$`glass$Type`, class7)
Acc7 <- round(sum(diag(tab7))/sum(tab7)*100, digits = 3)
Acc7
#For k=21 the Accuracy is 63.81%
#Thus we Conclude that the model performs the Best for k= 1 and k=2
#Lets Construct a For Loop and Build Multiple Models for Different K values
accuracy <- c()
for (i in 1:25) #This will Take k values from 1 to 25
{
print(i)
class1 <- knn(train = training[,-10], test = testing[,-10], cl = training[,10], k=i)
CrossTable(testing$`glass$Type`, class1, prop.r = F, prop.c = F,prop.chisq = F)
tab1 <- table(testing$`glass$Type`, class1)
accuracy <- c(accuracy,round(sum(diag(tab1))/sum(tab1)*100, digits = 2))
}
summary(accuracy)
boxplot(accuracy)
AccuracyTable <- data.frame("K.value" = 1:25, "Accuracy" = accuracy)
attach(AccuracyTable)
ggplot(AccuracyTable, mapping = aes(K.value, Accuracy)) + geom_line(linetype = "dashed") + geom_point() + ggtitle("Model Accuracy for Different K-Value")
#Here k=8 has the Highest Accuracy |
06e20410a4b997a3cec5f05b0e36c4fedc0a699a | e1cbbf8791b0ac6d40f6d5b397785560105441d9 | /man/is.texp.Rd | 6737e7d5b1d3706a243a01ae5cc520d3a8f23c0b | [] | no_license | wasquith/lmomco | 96a783dc88b67017a315e51da3326dfc8af0c831 | 8d7cc8497702536f162d7114a4b0a4ad88f72048 | refs/heads/master | 2023-09-02T07:48:53.169644 | 2023-08-30T02:40:09 | 2023-08-30T02:40:09 | 108,880,810 | 2 | 0 | null | null | null | null | UTF-8 | R | false | false | 975 | rd | is.texp.Rd | \name{is.texp}
\alias{is.texp}
\title{Is a Distribution Parameter Object Typed as Truncated Exponential}
\description{
The distribution parameter object returned by functions of \pkg{lmomco} such as by \code{\link{partexp}} are typed by an attribute \code{type}. This function checks that \code{type} is \code{texp} for the Truncated Exponential distribution.
}
\usage{
is.texp(para)
}
\arguments{
\item{para}{A parameter \code{list} returned from \code{\link{partexp}} or \code{\link{vec2par}}.}
}
\value{
\item{TRUE}{If the \code{type} attribute is \code{texp}.}
\item{FALSE}{If the \code{type} is not \code{texp}.}
}
\author{W.H. Asquith}
\seealso{\code{\link{partexp}} }
\examples{
yy <- vec2par(c(123, 2.3, TRUE), type="texp")
zz <- vec2par(c(123, 2.3, FALSE), type="texp")
if(is.texp(yy) & is.texp(zz)) {
print(lmomtexp(yy)$lambdas)
print(lmomtexp(zz)$lambdas)
}
}
\keyword{utility (distribution/type check)}
\keyword{Distribution: Exponential (trimmed)}
|
619fec2b5433a052e83ce80bc0c19523618328c3 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/iemiscdata/examples/i18.Rd.R | af26d2e58f22ed3812098d9cd3f603be9d41ccde | [] | 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 | 147 | r | i18.Rd.R | library(iemiscdata)
### Name: i18
### Title: 18 Percent Effective Interest Table (Engineering Economy)
### Aliases: i18
### ** Examples
i18
|
3533da15a25223cce141435f2a2be1eaf258c144 | b47d96744beaae6875f4338f336c7f19f131d9f7 | /man/CopyTable.Rd | 6f695e13b42b99e210111ba5ed63eb17fd54264e | [] | no_license | eriqande/kalis | 8a3761d110e13b03d4d7e0b43c6e59d8e8e2bebe | 7de1672f0787f68e363db5109569ac33aa13bb30 | refs/heads/master | 2023-04-07T07:28:29.981455 | 2021-04-10T10:48:30 | 2021-04-10T10:48:30 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,704 | rd | CopyTable.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/TableMaker.R
\name{CopyTable}
\alias{CopyTable}
\title{Copy Forward/Backward tables}
\usage{
CopyTable(to, from)
}
\arguments{
\item{to}{a \code{kalisForwardTable} or \code{kalisBackwardTable} object
which is to be copied into.}
\item{from}{a \code{kalisForwardTable} or \code{kalisBackwardTable} object
which is to be copied from.}
}
\description{
Copies the contents of one forward/backward table into another.
}
\details{
The core code in kalis operates on forward and backward tables at a very low
level, both for speed (using low level CPU vector instructions) but also to
avoid unnecessary memory copies since these tables will tend to be very large
in serious genetics applications. As a result, if you attempt to copy a table
in the standard idomatic way in R:
\code{fwd2 <- fwd}
then these two variables merely point to the \emph{same} table: running the
forward algorithm on \code{fwd} would result in \code{fwd2} also changing.
This function is therefore designed to enable explicit copying of tables.
}
\examples{
# Examples
\dontrun{
# Create a forward table for the hidden Markov model incorporating all
# recipient and donor haplotypes
fwd <- MakeForwardTable()
# Propagate forward to variant 10:
Forward(fwd, pars, 10, nthreads = 8)
# This does **NOT** work as intended:
fwd2 <- fwd
Forward(fwd, pars, 20, nthreads = 8)
# Both tables are now at variant 20
fwd
fwd2
# Instead, to copy we create another table and use this function
fwd2 <- MakeForwardTable()
CopyTable(fwd2, fwd)
}
}
\seealso{
\code{\link{MakeForwardTable}}, \code{\link{MakeForwardTable}} to
create tables which can be copied into.
}
|
e08ab1fb1397031a1aff6b5a2a9b433059aa4d02 | 80004feacf40ae03f0dc823358756c0e54602776 | /SAMR.R | ae73a9db22f0a33b733b50701b9eda90a85b3b4d | [] | no_license | BaQBone/DNARepairAtlas | 9398992d7d8f2b5331ad117783adaa8c85d16a0b | 6707dce246a35f27a104f9f6d8e4e589496b2f0e | refs/heads/master | 2022-07-15T06:37:10.766153 | 2020-05-14T08:12:05 | 2020-05-14T08:12:05 | 261,547,191 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 17,642 | r | SAMR.R | library(samr)
library(dplyr)
library(reshape)
#library(reshape2)
library(ggplot2)
library(vsn)
library(limma)
library(smoothmest)
library(Biobase)
library(MSnbase)
library(matrixStats)
library(gplots)
library(fdrtool)
library(purrr)
library(LSD)
library(labeling)
library(munspace)
library(taRifx)
library(plotly)
#library(org.Sc.sgd.db)
library(stringr)
#install.packages("dplyr")
#install.packages("reshape")
#library(reshape2)
install.packages("ggplot2")
BiocManager::install("vsn")
BiocManager::install("limma")
BiocManager::install("smoothmest")
BiocManager::install("Biobase")
BiocManager::install("MSnbase")
BiocManager::install("matrixStats")
BiocManager::install("gplots")
BiocManager::install("fdrtool")
BiocManager::install("purrr")
BiocManager::install("LSD")
BiocManager::install("org.Sc.sgd.db")
BiocManager::install("stringr")
BiocManager::install("labeling")
BiocManager::install("taRifx")
##############################################################################################
########################################## FUNCTIONS #########################################
##############################################################################################
#Function Imputation: replace missing values by normal distribution
#-----------------------------------------------------------------
Imputation <- function(x, shift=1.8, width=0.3){
temp <- c()
inf.values <- is.na(x)
m <- mean(x[!inf.values])
s <- sd(x[!inf.values])
imputed <- rnorm(length(grep(T, is.na(x))), mean = (m-shift*s), sd = (s*width))
x[inf.values] <- imputed
if (length(temp) == 0){
temp <- x
}else{
temp <- cbind(temp, x)
}
return(temp)
}
##############################################################################################
# Data Import
#------------------
setwd("R:\\MS-Data\\DNA REPAIR ATLAS\\ATLAS INPUT")
# Import of the Metadata
#---------------------------
conditions <- read.table("CHROMASS - Experimental Conditions V5.txt",
header = T,
sep = "\t",
fill = T,
stringsAsFactors = F,
comment.char = "")
name.rep <- paste(conditions$Experiment.Series,conditions$Treatment,conditions$Time,sep=".")
# Import of the LFQ data
#-------------------------
LFQ <- read.table("Repair_Atlas_LFQ_Intensities_flipped_V7.txt", header = T, sep = "\t", fill = T, stringsAsFactors = F, comment.char = "")
# Transpose LFQ and map column labels from MetaData
#---------------------------------------------------------
LFQ <- as.data.frame(t(LFQ))
# Generate a lookup table to retrieve Experimental condition from MetaData with FILE_ID
columnHeader <- conditions$Group
names(columnHeader) <- paste("id_",conditions$FILE_ID,sep="")
# Map column name onto LFQ (Remember: last row of LFQ contains the FILE_ID)
names(LFQ) <- columnHeader[paste("id_",LFQ[nrow(LFQ),],sep="")]
# remove last row from LFQ containing the FILE_ID
LFQ<-LFQ[1:nrow(LFQ)-1,]
# Fix some column names:
colnames(LFQ)[grep("EXP08.NCA.30_01", colnames(LFQ))] <- "EXP07.NCA.30_03"
colnames(LFQ)[grep("EXP08.NCA.60_01", colnames(LFQ))] <- "EXP07.NCA.60_01"
colnames(LFQ)[grep("EXP08.NCA.60_02", colnames(LFQ))] <- "EXP07.NCA.60_02"
colnames(LFQ)[grep("EXP08.NCA.60_03", colnames(LFQ))] <- "EXP07.NCA.60_03"
groups <- unique(sub("_[0-9]{2}","",colnames(LFQ)))
write.table(groups,
"RepairAtlas name of replicates.txt", sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")
write.table(LFQ,
"LFQ_temp.txt", sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")
# Generate tables to append the reults of the T-Tests and imputed LFQ values
#-----------------------------------------------------------------------------
results <- LFQ[,1:2]
results[,1] <- 1:nrow(LFQ)
results[,2] <- rownames(LFQ)
colnames(results) <- c("prot.id", "prot.name")
rownames(results) <- results$prot.id
lfq.imp <- results
# Generate matrix for all the T-Test comparisons
#-------------------------------------------------------
#tTest <- matrix(c("LFQ.intensity.CAP","LFQ.intensity.CTR", "TRUE",
# "LFQ.intensity.LIN","LFQ.intensity.CTR", "TRUE",
# "LFQ.intensity.PHS","LFQ.intensity.CTR", "TRUE"),
# nrow = 3,
# ncol = 3,
# byrow = T)
#colnames(tTest) <- c("right_side","left_side","impute_left" )
tTest <- read.table("comparisons.test.txt",
header = T,
sep = "\t",
fill = T,
stringsAsFactors = F,
comment.char = "")
setwd("R:\\MS-Data\\DNA REPAIR ATLAS\\ATLAS INPUT\\TTEST ANALYSIS\\RESULTS")
for (i in 50:nrow(tTest)){
Int <- cbind(results[,1:2],LFQ[,c(grep(tTest[i,1],colnames(LFQ)),
grep(tTest[i,2],colnames(LFQ)))])
# Filter for at least three valid values in the right replicate
repRight.valid <- as.matrix(Int[,c(grep(tTest[i,2],colnames(Int)))])
repRight.valid[which(repRight.valid != 0)] <- 1
valid <- rowSums(repRight.valid)
Int <- subset(Int, valid > 2)
Int$valid <- NULL
# Impute values into the replicates of the "left side" of the volcano plot
if (tTest[i,3]){Int[,grep(tTest[i,1],names(Int))] <- Imputation(Int[,grep(tTest[i,1],names(Int))])}
lfq.imp <- merge(lfq.imp,Int, by.x = "prot.id", by.y = "prot.id", all.x = T )
# Define variables for the T-Tests
desc <- ""
min.fold <- 1.5
max.fdr <- 0.05
plots <- T
x<-as.matrix(Int[,c(grep(tTest[i,1],names(Int)),
grep(tTest[i,2],names(Int)))])
rep <- unique(sub("(.*)_[0-9]{2}","\\1",colnames(x)))
r1 <- grep(rep[1], colnames(x))
r2 <- grep(rep[2], colnames(x))
test_desc <- paste(tTest[i,2],"vs",tTest[i,1],sep="")
test_desc
input = list(
x = x,
y = c(rep(1, length(grep(tTest[i,1],colnames(Int)))), rep(2, length(grep(tTest[i,2],colnames(Int))))),
geneid = Int$prot.name,
genenames = Int$prot$id,
logged2 = T)
samr.obj <- samr(input,
resp.type = "Two class unpaired",#,center.arrays=TRUE) if arrays should be normalized
nperms = 1000)
output <- Int[,1:2]
output$DIFF <- apply(x,1,function(x){mean(x[r2]) - mean(x[r1])})
output$PVAL <- unlist(apply(x, 1, function(x) {-log10(t.test(
x = x[r1],
y = x[r2],
var.equal = T)$p.value)}))
colnames(output)[3] <- paste(test_desc, "_DIFF", sep="")
colnames(output)[4] <- paste(test_desc, "_PVAL", sep="")
write.table(output,
"output.txt", sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")
qplot(output[,3],output[,4])
delta.table <- samr.compute.delta.table(samr.obj, min.foldchange = min.fold, dels = c((1:200)/100))
s0 <- round(samr.obj$s0,2)
write.table(delta.table,
paste("Delta_table_", test_desc, "_","MFC_",min.fold,"_S0=",s0,".txt", sep=""), sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")
if (min(na.omit(delta.table[,5])) <= max.fdr){
# Retrieve the highest Delta so that fdr < max.fdr
j=1
while(na.omit(delta.table[j,5]) > max.fdr) {j<-j+1}
delta<-delta.table[j,1]
# compute Significant genes
siggenes <-samr.compute.siggenes.table(samr.obj, del = delta, input, delta.table, min.foldchange = min.fold)
siggenes_all <-samr.compute.siggenes.table(samr.obj, del = delta, input, delta.table, min.foldchange = min.fold, all.genes=T)
all_genes <-rbind(siggenes_all$genes.up,siggenes_all$genes.lo)
# Prepare Protein ID lookup table
# ----------------------------------
prot.id <- Int$prot.id
names(prot.id) <- paste("g",1:nrow(Int), sep="")
# Printing out tables
if (siggenes$ngenes.up > 0){
genes_up<-siggenes$genes.up
genes_up<-data.frame(genes_up)
genes_up$UP <- 1
colnames(genes_up)[ncol(genes_up)] <- paste(test_desc, "_UP", sep="")
genes_up$prot.id <- prot.id[paste(genes_up$Gene.ID, sep=",")]
write.table(genes_up,
paste("Genes_up_",test_desc,".txt", sep=""), sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")}
if (siggenes$ngenes.lo > 0){
genes_lo<-siggenes$genes.lo
genes_lo<-data.frame(genes_lo)
genes_lo$DOWN <- 1
colnames(genes_lo)[ncol(genes_lo)] <- paste(test_desc, "_DOWN", sep="")
genes_lo$prot.id <- prot.id[paste(genes_lo$Gene.ID, sep=",")]
write.table(data.frame(siggenes$genes.lo),
paste("Genes_lo_",test_desc,".txt", sep=""), sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")}
write.table(data.frame(all_genes),
paste("Genes_all_",test_desc,".txt", sep=""), sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")
# Plot
if (plots == T){
file.name <- paste("SAM_Plots_", test_desc, "_","MFC_",min.fold,".pdf", sep="")
pdf(file.name)
samr.plot(samr.obj, del=delta, min.foldchange=min.fold)
title(main=paste("SAM PLOT: ",
test_desc,
" (FDR=",
max.fdr,
"; s0=",
round(samr.obj$s0, digits = 2),
")",sep="" ))
delta.frame <- data.frame(delta.table)
plot(delta.frame$delta, delta.frame$median.FDR, cex = 0.2, xlab="Delta", ylab = "Median FDR")
title(main= "FDR PLOT", sub= paste("UP:",siggenes[[4]],", DOWN:",siggenes[[5]],", False Positives=",round(delta.table[i,2]),sep=""))
points(delta.frame$delta[i],delta.frame$median.FDR[i], col="red", cex=0.6)
text(delta.frame$delta[i],delta.frame$median.FDR[i], paste("Delta:",delta.table[i,1],", Fold Change:",min.fold,", FDR:",max.fdr,sep=""), col="red",pos=4, cex=0.75)
dev.off()}
if (siggenes$ngenes.up > 0 && siggenes$ngenes.lo > 0){
output <- merge(output, genes_up[,c(4,9:10)], by.x = "prot.id", by.y= "prot.id", all.x = T)
output <- merge(output, genes_lo[,c(4,9:10)], by.x = "prot.id", by.y= "prot.id", all.x = T)
colnames(output)[5] <- paste(test_desc, "_SCORE_UP", sep="")
colnames(output)[7] <- paste(test_desc, "_SCORE_DOWN", sep="")
output <- remove.factors(output) # requires library taRifix
output[,5:8][is.na(output[,5:8])] <- 0
output[,3]<-round(as.numeric(output[,3]), digits=3)
output[,4]<-round(as.numeric(output[,4]), digits=3)
output[,5]<-round(as.numeric(output[,5]), digits=3)
output[,7]<-round(as.numeric(output[,7]), digits=3)}
if (siggenes$ngenes.up > 0 && siggenes$ngenes.lo == 0){
output <- merge(output, genes_up[,c(4,9:10)], by.x = "prot.id", by.y= "prot.id", all.x = T)
output$SCORE_DOWN <- 0
output$DOWN <- 0
colnames(output)[5] <- paste(test_desc, "_SCORE_UP", sep="")
colnames(output)[7] <- paste(test_desc, "_SCORE_DOWN", sep="")
colnames(output)[8] <- paste(test_desc, "_DOWN", sep="")
output <- remove.factors(output) # requires library taRifix
output[,5:8][is.na(output[,5:8])]<-0}
if (siggenes$ngenes.up == 0 && siggenes$ngenes.lo > 0){
output$SCORE_UP <- 0
output$UP <- 0
output <- merge(output, genes_lo[,c(4,9:10)], by.x = "prot.id", by.y= "prot.id", all.x = T)
colnames(output)[5] <- paste(test_desc, "_SCORE_UP", sep="")
colnames(output)[6] <- paste(test_desc, "_UP", sep="")
colnames(output)[8] <- paste(test_desc, "_DOWN", sep="")
output <- remove.factors(output) # requires library taRifix
output[,5:8][is.na(output[,5:8])]<-0}
if (siggenes$ngenes.up == 0 && siggenes$ngenes.lo == 0){
output$SCORE_UP <- 0
output$UP <- 0
output$SCORE_DOWN <- 0
output$DOWN <- 0
colnames(output)[5] <- paste(test_desc, "_SCORE_UP", sep="")
colnames(output)[6] <- paste(test_desc, "_UP", sep="")
colnames(output)[7] <- paste(test_desc, "_SCORE_DOWN", sep="")
colnames(output)[8] <- paste(test_desc, "_DOWN", sep="")
output <- remove.factors(output) # requires library taRifix
output[,5:8][is.na(output[,5:8])]<-0}
}
if (min(na.omit(delta.table[,5]))>max.fdr){
output$SCORE_UP <- 0
output$UP <- 0
output$SCORE_DOWN <- 0
output$DOWN <- 0
colnames(output)[5] <- paste(test_desc, "_SCORE_UP", sep="")
colnames(output)[6] <- paste(test_desc, "_UP", sep="")
colnames(output)[7] <- paste(test_desc, "_SCORE_DOWN", sep="")
colnames(output)[8] <- paste(test_desc, "_DOWN", sep="")
output <- remove.factors(output) # requires library taRifix
output[,5:8][is.na(output[,5:8])]<-0
}
output$prot.name <- NULL
results <- merge(results, output, by.x = "prot.id", by.y = "prot.id", all.x = T)}
results[,3:ncol(results)][is.na(results[,3:ncol(results)])] <- 0
write.table(results,
"Repair_Atlas_Results.txt", sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")
# Volcano
res<- results[,c(1:4,6)]
res<- filter(res, res[,4] != 0)
res$SIG <- as.factor(res$SIG)
colnames(res)<-c("id","name","DIFF","PVAL","SIG")
p <- ggplot(data=res, aes(x=DIFF, y= PVAL, text=name, color=SIG )) +
geom_point(alpha=0.3, size=1.5) +
xlab("Log2 fold change") +
ylab("-Log10 p-value") +
ggtitle("Psoralen +/- Geminin, 45 Min")
ggplotly(p)
results.brief <- results[,1:2]
prot.sig <- results[,c(1:2,seq(from =6, to = nrow(tTest)*6 , by =6))]
prot.sig$COUNT_UP <- apply(prot.sig[,3:ncol(prot.sig)],1,sum)
results.brief$COUNT_UP <- prot.sig$COUNT_UP
# Number of proteins that score significant in at least one condition: (optimized S0)
nrow(subset(prot.sig, prot.sig$COUNT_UP >0))
# Calculate the protduct of all p-values that are associated with upregulated proteins
prot.pval <- results[,seq(from =6, to = nrow(tTest)*6 , by =6)-2]
prot.pval <- 10^-prot.pval
prot.diff <- results[,seq(from =6, to = nrow(tTest)*6 , by =6)-3]
prot.pval[prot.diff < 0] <- 1
prot.pval$prod <- -log10(apply(prot.pval,1,prod))
results.brief$PVAL_PROD <- prot.pval$prod
# Add tables with individual counts, pval-products and scores
prot.pval <- results[,seq(from =6, to = nrow(tTest)*6 , by =6)-2]
prot.score <-results[,seq(from =6, to = nrow(tTest)*6 , by =6)-1]
results.brief <- cbind(results.brief, prot.sig)
results.brief <- cbind(results.brief, prot.pval)
results.brief <- cbind(results.brief, prot.score)
write.table(results.brief,
"Repair_Atlas_Results.brief.txt", sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")
cols <- sapply(results, is.logical)
results[,cols] <- lapply(results[,cols], as.numeric)
write.table(lfq.imp,
"Repair_Atlas_Normalized_LFQ.txt", sep="\t",
col.names=TRUE, row.names=FALSE, quote=FALSE, na="NA")
#################
###### APPEND function
#################
Append.df<- function(df,data=mydata){
temp <- as.data.frame(data)
temp$id <- rownames(temp)
temp <- merge(df, temp, by.x = "id", by.y = "id", all.x = T)
}
|
0a74bf8e03058c18caa5212a940afb6f30f0e64e | 3c7a0a23a16deedbee4e0089c37635edd2a8433b | /man/runWaterValuesSimulation.Rd | fde3aeb2fe8c2c0428a932acbcedab0cdf2a0b6f | [
"MIT"
] | permissive | rte-antares-rpackage/antaresWaterValues | 7c97a4324e3fca6c87ef59dab235f128531ac1e7 | ff73940f1c73d2cacb978331d920681cbb3fb9b2 | refs/heads/main | 2023-08-17T10:08:36.446393 | 2023-08-16T08:36:45 | 2023-08-16T08:36:45 | 96,431,344 | 1 | 5 | null | 2019-11-29T16:45:13 | 2017-07-06T13:08:21 | R | UTF-8 | R | false | true | 2,794 | rd | runWaterValuesSimulation.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/runWaterValuesSimulation.R
\name{runWaterValuesSimulation}
\alias{runWaterValuesSimulation}
\title{Run a simulation for calculating water values for a specific area}
\usage{
runWaterValuesSimulation(
area,
simulation_name = "weekly_water_amount_\%s",
nb_disc_stock = 10,
nb_mcyears = NULL,
binding_constraint = "WeeklyWaterAmount",
fictive_area = NULL,
thermal_cluster = NULL,
path_solver = NULL,
wait = TRUE,
show_output_on_console = FALSE,
overwrite = FALSE,
link_from = NULL,
remove_areas = NULL,
opts = antaresRead::simOptions(),
shiny = F,
otp_dest = NULL,
file_name = NULL,
pumping = F,
efficiency = NULL,
launch_simulations = T,
reset_hydro = T,
constraint_values = NULL,
...
)
}
\arguments{
\item{area}{area}
\item{simulation_name}{character}
\item{nb_disc_stock}{integer}
\item{nb_mcyears}{list}
\item{binding_constraint}{character}
\item{fictive_area}{Name of the fictive area to create, argument passed to \code{\link{setupWaterValuesSimulation}}.}
\item{thermal_cluster}{Name of the thermal cluster to create, argument passed to \code{\link{setupWaterValuesSimulation}}.}
\item{path_solver}{Character containing the Antares Solver path, argument passed to \code{\link[antaresEditObject]{runSimulation}}.}
\item{wait}{Argument passed to \code{\link[antaresEditObject]{runSimulation}}.}
\item{show_output_on_console}{Argument passed to \code{\link[antaresEditObject]{runSimulation}}.}
\item{overwrite}{If area or cluster already exists, should they be overwritten?}
\item{link_from}{area that will be linked to the created fictive area. If it's
\code{NULL} it will takes the area concerned by the simulation.}
\item{remove_areas}{Character vector of area(s) to remove from the created district.}
\item{opts}{List of simulation parameters returned by the function
\code{antaresRead::setSimulationPath}}
\item{shiny}{Boolean. True to run the script in shiny mod.}
\item{otp_dest}{the path in which the script save Rdata file.}
\item{file_name}{the Rdata file name.}
\item{pumping}{Boolean. True to take into account the pumping.}
\item{efficiency}{in [0,1]. efficient ratio of pumping.}
\item{launch_simulations}{Boolean. True to to run the simulations.}
\item{reset_hydro}{Boolean. True to reset hydro inflow to 0 before the simulation.}
\item{constraint_values}{constraint values to use to run simulations, generated by the function \code{\link{constraint_generator}}}
\item{...}{further arguments passed to or from other methods.}
}
\description{
Run a simulation for calculating water values for a specific area
}
\note{
This function have side effects on the Antares study used, a fictive area is created and a new district as well.
}
|
68caea0d54e390924157dd8ca68e492dfa77fa26 | c36626e74b54e0c748f1da46904a58198415641e | /man/eco.genepop2df.Rd | 9ffff23f477f81a044d40c816dd4b88bd244fb44 | [] | no_license | jcassiojr/EcoGenetics | a3f3e5586bee15f2f87fc284b4ad8f3243db061e | 9256797efd715f3eb3de960dcec03aa31e53510f | refs/heads/master | 2021-01-24T08:32:49.115341 | 2016-07-15T20:02:10 | 2016-07-15T20:02:10 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 803 | rd | eco.genepop2df.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/eco.genepop2df.R
\name{eco.genepop2df}
\alias{eco.genepop2df}
\title{Importing a Genepop file}
\usage{
eco.genepop2df(genefile = NULL)
}
\arguments{
\item{genefile}{Genepop file.}
}
\value{
A list with the objects G (genetic matrix) and S (structures matrix).
}
\description{
This function converts a Genepop file into an object
with a genetic matrix (G) and a structures matrix (S).
}
\examples{
\dontrun{
# ingpop, file with Genepop format in the folder "/extdata" of the package
ecopath <- paste(path.package("EcoGenetics"), "/extdata/ingpop", sep = "")
ingpop <- eco.genepop2df(ecopath)
ingpop
}
}
\author{
Leandro Roser \email{leandroroser@ege.fcen.uba.ar}, adapting code
written by Emiel van Loon and Scott Davis
}
|
682c94d3d986303fcb0c6063db16024c2c9768f8 | 04c94cdeebdc2052e3023027fbd78e0578867ec6 | /man/latable.Rd | 28758c5414ed493dcf85382a89ad5e9200699e65 | [
"MIT"
] | permissive | emilelatour/latable | 587e4cb9542a526ca7b10a4b0bec2ec775cc9849 | 81e7795faafcccc00267c5a701f1126492b7f282 | refs/heads/master | 2022-09-21T13:05:41.997280 | 2022-08-25T17:13:22 | 2022-08-25T17:13:22 | 177,342,113 | 0 | 1 | null | null | null | null | UTF-8 | R | false | true | 342 | rd | latable.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/latable.R
\docType{package}
\name{latable}
\alias{latable}
\title{latable: Tools for making tables of results}
\description{
This package contains a variety of helper functions for making tables of
results easily.
}
\examples{
# Example usage:
library(latable)
}
|
e2be718f90ab4513dd4eec2a849de604ece384b5 | 6e5efc0b6b6b37c735c1c773531c41b51675eb10 | /man/Get.VIP.Rd | 81cae812cb423bf5b8d4aaf1dbde37ce707d9730 | [
"GPL-2.0-or-later"
] | permissive | xia-lab/MetaboAnalystR | 09aa09c9e57d7da7d73679f5a515eb68c4158e89 | 9edbbd1e2edda3e0796b65adf440ad827abb7beb | refs/heads/master | 2023-08-10T06:08:56.194564 | 2023-08-01T15:13:15 | 2023-08-01T15:13:15 | 109,994,826 | 268 | 165 | MIT | 2023-03-02T16:33:42 | 2017-11-08T15:38:12 | R | UTF-8 | R | false | true | 622 | rd | Get.VIP.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/biomarker_utils.R
\name{Get.VIP}
\alias{Get.VIP}
\title{Calculate variable importance of projection (VIP) score for PLS object}
\usage{
Get.VIP(pls.obj, comp = 2)
}
\arguments{
\item{pls.obj}{Input the PLS object}
\item{comp}{Numeric, input the number of components, by default it is 2}
}
\description{
Users give a pls object ('oscorespls'=T), function calculates VIP score
usually one VIP for each component, return is the average of all VIP
}
\author{
Jeff Xia \email{jeff.xia@mcgill.ca}
McGill University, Canada
License: GNU GPL (>= 2)
}
|
6da8b16cd77aa7de0e1612d84a35d35084a5ca09 | 8db902665b4c93d8f86a2381d917515de1b5b649 | /SOEP_Covid_19_data_merge_core.R | 2a7da73231621a57b080d059fc4991da0a257bc3 | [] | no_license | benkec/health-measures | 9fed200ab560d2e82bcdb8070df65878e0282685 | e1e6445557e66142fba15605975bb102cf51ba2d | refs/heads/main | 2023-03-13T19:11:34.993751 | 2021-03-05T17:42:43 | 2021-03-05T17:42:43 | 345,051,563 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,920 | r | SOEP_Covid_19_data_merge_core.R | # load harmonized dataset -----------------------------
load(str_c(temp_path,"soep_core_health.RData"))
#load RG data set -------------------
load(str_c(temp_path,"soep_core_risk.RData"))
# load other CORE varibales data set
load(str_c(temp_path,"soep_core_other.RData"))
# load SES and weights CORE varibales data set
load(str_c(temp_path,"soep_core_ses.RData"))
#behavioral data
load(str_c(temp_path,"health_covid_behavior.RData"))
#append data set with time varying variables ----------------------
# risk groups --------------------
crisis <- merge(dat_harmonized, soep_rg, by = c("pid"), all.x = T)
# other variables --------------------
crisis <- merge(crisis, soep_other, by = c("pid"), all.x = T) %>% mutate(sample_covpop = if_else(psample %in% c(1:16,20,21,99),1,0,NA_real_)) %>%
filter(sample_covpop==1)
## ses and weights, and behavior
crisis <- left_join(crisis, ses, by = c("pid", "syear")) %>% left_join(soep_behavior, by = c("pid", "syear"))
#### covid weights wide anmergen für sample_cov only analysen
#ses <- left_join(ses,covid_weights,by=c("pid","syear")) %>% mutate(phrf = if_else(syear==2020,phrf.y,phrf.x,NA_real_))
if (Sys.info()[["user"]] == "bootstrap"){
crisis <- left_join(crisis, select(covid_weights,pid,phrf), by = c("pid")) %>% rename(phrf= phrf.x, phrf_cati=phrf.y)
crisis <- left_join(crisis,covid_weights,by=c("pid","syear")) %>% mutate(phrf = if_else(syear==2020,phrf.y,phrf.x,NA_real_))
crisis <- crisis %>% mutate(soep_cov_ind = if_else(is.na(phrf_cati) | phrf_cati ==0,0,1))
} else {
crisis <- crisis %>% mutate(phrf_cati = 1) %>% select(-phrf) %>% mutate(phrf = 1)
}
#### set missing weights to zero ###
crisis <- crisis %>% mutate(phrf = if_else(is.na(phrf),0,phrf),phrf_cati = if_else(is.na(phrf_cati),0,phrf_cati))
#crisis <- filter(crisis,!is.na(phrf))
save(crisis, file = paste0(c(temp_path,"health_covid_soep_risk.RData"), collapse=""))
|
c320b4466bf02479d1bb994fe45611de6df8e095 | 02dbb451925f35d1abe781360968596eaa59bcbd | /R/lazy.text.format.R | 7bacc82c28e1e2cd8be19825c6416fa2e5bf47ac | [] | no_license | nutterb/lazyWeave | ad68c57edd703e83124fa7267314de1902050c47 | fe7ba16ff61dabcace079a9399050b2610224bac | refs/heads/master | 2021-06-06T04:26:31.480092 | 2018-01-25T00:19:56 | 2018-01-25T00:19:56 | 4,657,725 | 1 | 0 | null | 2015-07-27T00:59:17 | 2012-06-14T00:34:01 | R | UTF-8 | R | false | false | 2,340 | r | lazy.text.format.R | #' @name lazy.text.format
#' @export lazy.text.format
#'
#' @title Format Text
#' @description Applies italic, bold, or underlining to a piece of text.
#' May be used within \code{lazy.text} to add emphasis when the entire
#' paragraph does not need to be formatted
#'
#' @param text Text to be formatted
#' @param italic Logical. Specifies if text should be italic
#' @param bold Logical. Specifies if text should be bold
#' @param underline Logical. Specifies if text should be underlined
#' @param translate Logical. Specifies if text should be passed through
#' \code{latexTranslate} before printing
#'
#' @details This function differs from \code{lazy.text} in that
#' \code{lazy.text} produces a paragraph of formatted text while
#' \code{lazy.text.format} produces smaller blocks. This allows for
#' smaller bits of text to be formatted for emphasis
#' (see the last example below).
#'
#' @author Benjamin Nutter
#'
#' @examples
#' lazy.text.format("This is the text")
#' lazy.text.format("This is the text", italic=TRUE)
#' lazy.text.format("This is the text", bold=TRUE)
#' lazy.text.format("This is the text", italic=TRUE, bold=TRUE)
#'
#' lazy.text("The percentage of defective lightbulbs in this sample was ",
#' lazy.text.format("30\%", italic=TRUE),
#' ". Clearly, this is unacceptable.")
#'
lazy.text.format <- function(text, italic=FALSE, bold=FALSE,
underline=FALSE, translate=TRUE){
#*** retrieve the report format
reportFormat <- getOption("lazyReportFormat")
if (!reportFormat %in% c("latex", "html", "markdown")) stop("option(\"lazyReportFormat\") must be either 'latex', 'html', or 'markdown'")
if (reportFormat == "latex"){
if (translate) text <- Hmisc::latexTranslate(text)
if (underline) text <- paste("\\ul{", text, "}", sep="")
if (bold) text <- paste("\\textbf{", text, "}", sep="")
if (italic) text <- paste("\\emph{", text, "}", sep="")
}
if (reportFormat == "html"){
if (underline) text <- paste("<ul>", text, "</ul>")
if (italic) text <- paste("<i>", text, "</i>")
if (bold) text <- paste("<b>", text, "</b>")
}
if (reportFormat == "markdown"){
if (italic) text <- paste0("_", text, "_")
if (bold) text <- paste0("**", text, "**")
}
return(text)
}
|
e3ab1d63bebdbe16716e22bd414dd98f7704aaad | 0723a23b109a236de4a6a0d3fdb97a102130c9f6 | /server_mode/run_cplex.R | 88414d4502415e2762e0776e41671fa7c85c83a8 | [
"MIT"
] | permissive | raunakms/hitndrive-R | eb154b31cf5ed3507ad21db9dd5ba4bc80de34bb | 2e341638211453eb4c3047289d9155d32b811874 | refs/heads/master | 2020-12-02T22:09:36.970820 | 2017-07-03T08:59:09 | 2017-07-03T08:59:09 | 96,090,477 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 446 | r | run_cplex.R | run.cplex <- function(file.bash.script){
cat(paste(Sys.time()), "STARTING CPLEX TO SOLVE ILP ...","PLEASE WAIT ...","\n", sep="\t")
#path.cplex <- "/Data/Raunak/CPLEX/cplex/bin/x86_sles10_4.1/cplex"
path.cplex <- "/home/stas/Software/CPLEX/cplex/bin/x86-64_linux/cplex"
cmd <- paste(path.cplex, "<", file.bash.script, ">", file.cplex.log, sep=" ")
system(cmd)
cat(paste(Sys.time()), "TERMINATING CPLEX ...","\n", sep="\t")
}
|
53fff082f0ae20d07a0dcdf91d100bd8ff689304 | dc46dc7b43520abca7bd495852390ad01dfbde57 | /project2/ny_plot.R | d566f83317a9ff320c98c147e6173b91d43a854b | [] | no_license | datasci611/project-1-mingywang18 | df7ed0a8fa8128a981eda33cbfa9b7a4a132823b | 5df2db944692f32afe2006d315691e157d7241ca | refs/heads/master | 2020-03-29T16:09:54.716909 | 2018-10-22T21:59:23 | 2018-10-22T21:59:23 | 150,100,831 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 222 | r | ny_plot.R | library(tidyverse)
library(gridExtra)
library(kableExtra)
source("/Users/wmy/Desktop/data611/plot_yrtemp_function.R")
nc <- read.csv("/Users/wmy/Desktop/data611/KNYC.csv")
plot_temp(ny,"New York")
ggsave("ny_plot.png")
|
af4e673693fbd4dee1cf227afa007b0bbd62a827 | 3ad3ce5f38d636b649abd6e2e8741d482d8f6d72 | /man/prevsymbol_fn.Rd | 9e780f4883e625278c70541cb7d849bf69ce6181 | [] | no_license | cran/pubmed.mineR | 279ce024df5b7913885ec96ad906226aa78633ce | 7612a2d68f503794f8dee8479e8b388949e4b70d | refs/heads/master | 2021-12-09T18:39:44.578225 | 2021-11-26T14:50:03 | 2021-11-26T14:50:03 | 17,919,888 | 5 | 6 | null | null | null | null | UTF-8 | R | false | false | 1,179 | rd | prevsymbol_fn.Rd | \name{prevsymbol_fn}
\alias{prevsymbol_fn}
\title{
To extract the sentences containing Previous symbols of HGNC genes.
}
\description{
\code{prevsymbol_fn} will return the sentences containing previous symbols of the genes from the abstracts using HGNC data.
}
\usage{
prevsymbol_fn(genes, data, abs, filename, terms)
}
\arguments{
\item{genes}{
\code{genes} is output of gene_atomization, or a table containing HGNC gene symbols in first column with its frequency in second column.
}
\item{data}{
\code{data} is HGNC data
table with all 49 features (columns) available from the web site https://www.genenames.org/
}
\item{abs}{
\code{abs} an S4 object of class Abstracts.
}
\item{filename}{
\code{filename} specify the name of output file
}
\item{terms}{
\code{terms} second query term to be searched in the same sentence (co-occurrence) of abstracts.
}
}
\value{
It returns a text file containing gene symbol with corresponding previous symbols.
}
\author{
S.Ramachandran
}
\seealso{
\code{\link{names_fn}}, \code{\link{official_fn}}
}
\examples{
\dontrun{
prevsymbol_fn(genes, data, diabetes_abs, "prevsym", c("diabetic nephropathy", "DN"))
}
}
\keyword{function}
|
40fa26912fe33d41711a9f0473757e3c4a9fc32b | 14e05de4dfaf028a5ebaca3ac04e969cafdee5e8 | /demo-jarque.R | d33ef8c2603670fcb3801c1486e0106c38a82ab1 | [] | no_license | spip333/demos-statistik | c7e4d9603aa0e4f10213ec084dcbea1775eb4f1a | ae7d07544ff3e3716c8fcc60a84e76c0bfca8a97 | refs/heads/master | 2020-04-10T00:44:25.444320 | 2019-01-22T16:11:28 | 2019-01-22T16:11:28 | 160,694,789 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 588 | r | demo-jarque.R | library(faithful)
eruption.lm <- lm(eruptions~waiting , data = faithful)
summary(eruption.lm)
# Sind die reste normalverteilt ? TEST
library(moments)
jarque.test(eruption.lm$residuals)
?jarque.test
#
# generate random numbers from normal distribution
v1 <- rnorm(10000, mean=10, sd=3)
jarque.test(v1)
#JB = 0.85028, p-value = 0.6537
v1 <- rnorm(10000, mean=10, sd=2)
jarque.test(v1)
# JB = 2.4359, p-value = 0.2958
v1 <- rnorm(10000, mean=10, sd=1)
jarque.test(v1)
#JB = 5.8373, p-value = 0.05401
v1 <- rnorm(10000, mean=10, sd=0.1)
jarque.test(v1)
#JB = 0.97278, p-value = 0.6148
|
a5e19c23db745b4cd7075b3cb866c3ca3e54d557 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/proxyC/examples/simil.Rd.R | 2eb159211744bb33dadc515da3802769e6181d85 | [] | 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 | 334 | r | simil.Rd.R | library(proxyC)
### Name: simil
### Title: Compute similiarty/distance between raws or columns of large
### matrices
### Aliases: simil dist
### ** Examples
mt <- Matrix::rsparsematrix(100, 100, 0.01)
simil(mt, method = "cosine")[1:5, 1:5]
mt <- Matrix::rsparsematrix(100, 100, 0.01)
dist(mt, method = "euclidean")[1:5, 1:5]
|
6ef7ce1b161d90dd8bd7984a015d292b02d34130 | e3cce5b3c80a9e1df678ef1d9e42dcb8d22b9fa1 | /Lineweaver Burk FINAL.R | 68483eed37aeb8c1dd85ec65021abd2c53453c97 | [] | no_license | JiangQunyang/Mypackage | fcef798d37813d0d6d60ebffa6654565e047d04f | 816163ec20c5902c097e6000bb9459d35a59102d | refs/heads/master | 2020-01-23T21:06:41.062531 | 2016-11-27T16:23:41 | 2016-11-27T16:23:41 | 74,576,383 | 1 | 1 | null | 2016-11-24T16:26:51 | 2016-11-23T12:50:21 | R | UTF-8 | R | false | false | 2,841 | r | Lineweaver Burk FINAL.R | ## Test data
S <- c(0,1,2,5,8,12,30,50) #0's no longer need to be removed
V <- c(0,11.1,25.4,44.8,54.5,58.2,72.0,60.1)
#Alternative Test Data
#S <- c(2.5,3.5,5,10,20,50)
#V <- c(32.3,40,50.8,72,87.7,115.4)
## Read in to a data frame
ReadIn <- function(S, V){
Inv.V <- 1/V # Lineweaver-Burk (y)
Inv.S <- 1/S #Lineweaver-Burk (x)
V.div.S <- V/S # Eadie-Hofstee
S.div.V <- S/V # Hanes-Woolf
enz.data <- data.frame(S, V, Inv.V, Inv.S, V.div.S, S.div.V) # read into df
enz.data <- enz.data[order(S),]
names(enz.data)[3] <- "1/V"
names(enz.data)[4] <- "1/S"
names(enz.data)[5] <- "V/S"
names(enz.data)[6] <- "S/V"
return(enz.data)
}
enz.data <- ReadIn(S, V)
#### Lineweaver-Burke Plot Function ####
LineweaverBurk <- function(enz.data) {
library(ggplot2)
if (enz.data[1,1]==0 && enz.data[1,2]==0) enz.data<-enz.data[-1,] # if the first measurement S or V is the enz.data dataframe is equal to 0, the whole row gets deleted because the linear model cannot deal with values that are NA/NaN/Inf
#which is what you get if you try and divide things by 0
LBdata<-data.frame(enz.data[,4],enz.data[,3])
LBmodel <- lm(enz.data[,3] ~ enz.data[,4])
Y.intercept <- c(0, LBmodel$coefficients[[1]])
X.intercept <- c(-LBmodel$coefficients[[1]]/LBmodel$coefficients[[2]], 0)
LBplot <- ggplot(LBdata, aes(x=enz.data[,4] , y=enz.data[,3])) +
geom_point(size=3, shape=20) +
ggtitle("Lineweaver Burk Plot") +
xlab("[1/S]") +
ylab("[1/v]") +
xlim(X.intercept[1], max(enz.data[,4])) +
ylim(0, max(enz.data[,3])) +
theme_bw()+
theme(plot.title = element_text(hjust=0.5))+
geom_abline(intercept = LBmodel$coefficients[[1]], slope = LBmodel$coefficients[[2]], color = "blue", size = 1)+
geom_vline(xintercept = 0, size=0.5)
return (LBplot)
}
#PRINT
LineweaverBurk(enz.data)
# LB formula -Gives the equation of the line as well as the x and y intercepts
LB.formula <- function(enz.data){
if (enz.data[1,1]==0 && enz.data[1,2]==0) enz.data<-enz.data[-1,] #again, we have to get rid of any 0 values because it can't make a model when there are NA/NaN/Inf values in 'x'
LBmodel <- lm(enz.data[,3] ~ enz.data[,4])
LB.Y.intercept <- paste("y intercept = (", 0,", ", (signif(LBmodel$coefficients[[1]], 3)), ")", collapse="", sep="")
LB.X.intercept <- paste("x intercept = (", signif(c(-LBmodel$coefficients[[1]]/LBmodel$coefficients[[2]]), 3), ", ", 0, ")", collapse="", sep="")
LB.equation <- paste("y = ", (signif(LBmodel$coefficients[[2]], 3)), "x + ", (signif(LBmodel$coefficients[[1]], 3)), collapse="", sep="")
LB.data <- c(LB.X.intercept, LB.Y.intercept, LB.X.intercept, LB.equation)
return(LB.data)
}
#PRINT
LB.formula(enz.data)
|
01af19e1137a65d065a405395dc9943d31fd44aa | 2a002aa01c0bfa6041298b5f8b7fb017c6277501 | /man/br_temp.Rd | da01d1f13ddb4be402982e4f7f7eabe5983c48f8 | [] | no_license | RichardLemoine/LSTtools | 185fdd168eb0ccf80fb28a7de4894e6d926d1dda | 4cd5a3b90d954c7f3b7dc99449268f7d4e94f6f7 | refs/heads/master | 2022-12-29T02:40:06.582598 | 2020-10-15T14:13:24 | 2020-10-15T14:13:24 | 285,254,084 | 7 | 3 | null | null | null | null | UTF-8 | R | false | true | 2,089 | rd | br_temp.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/landsat_preprocessing.R
\name{br_temp}
\alias{br_temp}
\title{br_temp}
\usage{
br_temp(
x,
band = "",
conv = TRUE,
mult = NULL,
add = NULL,
k1 = NULL,
k2 = NULL
)
}
\arguments{
\item{x}{Image band in DN to be converted.}
\item{band}{Character. Number of the Landsat band to convert.}
\item{conv}{Logical; if TRUE, units are converted to Celsius degrees.}
\item{mult}{Radiance multiplicative band rescaling factor.}
\item{add}{Radiance additive band rescaling factor.}
\item{k1}{k1 thermal conversion constant.}
\item{k2}{k2 thermal conversion constant.}
}
\value{
Raster layer with TOA brightness temperature values
in Kelvin or Celsius degrees.
}
\description{
Convert the DN contained in a Landsat TIR band
to TOA brightness temperature.
}
\details{
Convert the DN of a Landsat TIR band to TOA brightness
temperature in Kelvin or Celsius degrees employing the radiance
multiplicative and additive band rescaling factors and K1 and K2
constants. If band is specified, the function reads the
metadata (.txt) directly from the work directory (folder
containing bands as downloaded from NASA EarthExplorer) and
automatically extracts the multiplicative and additive rescaling
factors and k1 and k2 constants. These scaling factors and
constants can be manually defined employing mult, add, k1 and
k2 parameters. In this case band is ignored. If parameter
conv = TRUE, temperature units are convert to Celsius degrees.
This is the default.
}
\examples{
\dontrun{# For Landsat 8 band 10 defining band and extracting scaling
factors and constants from metadata
brtempB10 <- br_temp(B10, band = "10", conv = TRUE)
# For Landsat 8 band 10 defining manually the multiplicative
and additive scaling factors and the k1 and k2 constants
brtempB10 <- br_temp(B10, conv = TRUE, mult = 0.00033420, add = 0.1, k1 = 774.8853, k2 = 1321.0789)}
}
\references{
USGS. (2019). Landsat 8 data users handbook version 4.
USGS Earth Resources Observation and Science (EROS). Sioux Falls,
South Dakota. USA. 106.
}
|
254097991511835084359aaf8064a319b43d2341 | c4b195fe15bd50be87eee1d9461221ae4dfdebb7 | /tests/testthat/test_plotJunctionDist.R | 99e77f9f708428ebae84d4f187ececaa07a8e52e | [] | no_license | ischeller/FraseR | 1c3f758d220109efc33afa09d5ebc7ff4ad0ef22 | 34dc4fb9713c37edda30a2ea06efc2c0777e8ab7 | refs/heads/master | 2020-08-09T00:28:56.164226 | 2019-10-08T14:24:42 | 2019-10-08T14:24:42 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 449 | r | test_plotJunctionDist.R | context("Test distribution plots for given results/junction")
test_that("Main junction distribution plot", {
# get results
fds <- getFraseR()
res <- results(fds, fdrCut=1)
# plot distributions
expect_silent(plotJunctionDistribution(fds, res[res$type == "psi5"][1]))
expect_silent(plotJunctionDistribution(fds, res[res$type == "psi3"][1]))
expect_silent(plotJunctionDistribution(fds, res[res$type == "psiSite"][1]))
})
|
6ac4ea627ae28d54e20e0c085301c3c5748fc387 | 725a33f27fce430ee481a3542aae5bb81a94dfc0 | /man/print.PTXQC_table.Rd | c5e4699e41ecdce6ded1b74c5eaea35ef7db7678 | [
"BSD-3-Clause"
] | permissive | cbielow/PTXQC | fac47ecfa381737fa0cc36d5ffe7c772400fb24e | f4dc4627e199088c83fdc91a1f4c5d91f381da6c | refs/heads/master | 2023-07-20T00:39:45.918617 | 2023-05-17T14:23:03 | 2023-05-17T14:23:03 | 20,481,452 | 41 | 30 | NOASSERTION | 2023-05-17T14:23:04 | 2014-06-04T11:53:49 | HTML | UTF-8 | R | false | true | 469 | rd | print.PTXQC_table.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fcn_plots.R
\name{print.PTXQC_table}
\alias{print.PTXQC_table}
\title{helper S3 class, enabling print(some-plot_Table-object)}
\usage{
\method{print}{PTXQC_table}(x, ...)
}
\arguments{
\item{x}{Some Grid object to plot}
\item{...}{Further arguments (not used, but required for consistency with other print methods)}
}
\description{
helper S3 class, enabling print(some-plot_Table-object)
}
|
b22f39fba4e068e8ab15482558bff3dd40e39729 | 8ea1bbb1155daab7511033f7837830f45764c136 | /MinneМудак.R | a7bc2e12bbcf87fa392daca95bd194f67d8825f0 | [] | no_license | hssmikey/MinniMUDAC | 536a8848d3ee1b3f47dd369dfeee4259db0c1393 | 94756f4a12bc567c32c86efb5d8f9dc942e26b7e | refs/heads/master | 2021-01-04T13:40:33.264745 | 2018-11-03T02:55:55 | 2018-11-03T02:55:55 | 240,578,300 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 196 | r | MinneМудак.R | library(readr)
library(haven)
df <- read_sav("Downloads/anes_timeseries_cdf_sav/anes_timeseries_cdf.sav")
write_csv(df, "anes_timeseries.csv")
df <- read_csv("anes_timeseries.csv")
View(head(df))
|
3138f4d3d11684d44fcaa01e0796677d34f3cc8f | 50c60b91d6f6ea69474431f60500ee64e6597345 | /Amazon_Cellphone_Review/Final_Project.R | 4535c5c725f5243168d2bff0ee834ec8babc70ef | [] | no_license | LvNintyThousand/Artificial-Intelligence | 7cd52be780877835bc721d580743f14bfc239885 | befe15010e4fd15fdf1e84f500eba9f3553df385 | refs/heads/master | 2021-05-18T00:32:47.754994 | 2021-03-28T21:27:43 | 2021-03-28T21:27:43 | 251,024,893 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 7,947 | r | Final_Project.R | ## Data Analysis of Amazon Cellphone review
#1. library prep:
library(tidyverse) # general utility & workflow functions
library(tidytext) # tidy implimentation of NLP methods
library(topicmodels) # for LDA topic modelling
library(tm) # general text mining functions, making document term matrixes
library(SnowballC) # for stemming
#2. import csv.file:
items <- read.csv(file = file.choose(), header = TRUE)
reviews <- read.csv(file = file.choose(), header = TRUE)
View(items)
View(reviews)
#3. pre-processing raw data:
items <- items %>% mutate(class = case_when(originalPrice == 0 & price == 0 ~ "used",
originalPrice != 0 & price != 0 ~ "promotion",
originalPrice == 0 & price != 0 ~ "new"))
reviews$helpfulVotes <- reviews$helpfulVotes %>% replace_na(0)
reviews <- na.omit(reviews)
View(items)
View(reviews)
#4. brief statistical analysis
##4.1: the number of brands of cellphones:
items %>% distinct(asin) %>% nrow()
##4.2: the number of different classes of cellphones:
items$class %>% factor() %>% summary()
##4.3: the number of people involved:
reviews$name %>% unique() %>% length()
#5 NLP Top Topic Analysis
##5.1: pretest by using LDA model without 2nd pre-processing data:
top_terms_by_topic_LDA <- function(input_text, plot = TRUE, number_of_topics = 4){
corpus <- Corpus(VectorSource(input_text))
DTM <- DocumentTermMatrix(corpus)
unique_indexes <- unique(DTM$i)
DTM <- DTM[unique_indexes, ]
lda <- LDA(DTM, k = number_of_topics, control = list(seed = 1234))
topics <- tidy(lda, matrix = "beta")
top_terms <- topics %>%
filter(term != "phone.,") %>%
group_by(topic) %>%
top_n(10, beta) %>%
ungroup() %>%
arrange(topic, desc(beta))
if(plot == TRUE){
top_terms %>%
mutate(term = reorder(term, beta)) %>%
ggplot(aes(term, beta, fill = factor(topic))) +
geom_col(show.legend = FALSE) +
facet_wrap(~ topic, scales = "free") +
labs(x = NULL, y = "Beta") +
coord_flip()
}else{
return(top_terms)
}
}
top_terms_by_topic_LDA(reviews$body, number_of_topics = 2)
##5.2: 2nd pre-processing data for NLP LDA model:
usable_reviews <- str_replace_all(reviews$body,"[^[:graph:]]", " ")
# because we need to remove non-graphical characters to use tolower()
reviewsCorpus <- Corpus(VectorSource(usable_reviews))
reviewsDTM <- DocumentTermMatrix(reviewsCorpus)
reviewsDTM_tidy <- tidy(reviewsDTM)
ntlk_stop_words <- tibble(word = c("i", "me", "my", "myself", "we", "our",
"ours", "ourselves", "you", "your", "yours",
"yourself", "yourselves", "he", "him", "his",
"himself", "she", "her", "hers", "herself",
"it", "its", "itself", "they", "them", "their",
"theirs", "themselves", "what", "which", "who",
"whom", "this", "that", "these", "those", "am",
"is", "are", "was", "were", "be", "been", "being",
"have", "has", "had", "having", "do", "does", "did",
"doing", "a", "an", "the", "and", "but", "if", "or",
"because", "as", "until", "while", "of", "at",
"by", "for", "with", "about", "against", "between",
"into", "through", "during", "before", "after",
"above", "below", "to", "from", "up", "down", "in",
"out", "on", "off", "over", "under", "again",
"further", "then", "once", "here", "there", "when",
"where", "why", "how", "all", "any", "both", "each",
"few", "more", "most", "other", "some", "such", "no",
"nor", "not", "only", "own", "same", "so", "than",
"too", "very", "s", "t", "can", "will", "just", "don",
"should", "now"))
ntlk_stop_words$word <- paste(ntlk_stop_words$word, ",", sep = "")
ntlk_stop_words2 <- ntlk_stop_words
ntlk_stop_words2$word <- paste(ntlk_stop_words2$word, ",", sep = "")
ntlk_stop_words3 <- ntlk_stop_words
ntlk_stop_words3$word <- paste(ntlk_stop_words3$word, ".", sep = "")
ntlk_stop_words_total <- rbind(ntlk_stop_words, ntlk_stop_words2, ntlk_stop_words3)
custom_stop_words <- tibble(word = c("phone", "phone,", "phone.,", "===>", "amazon", "it.,"))
reviewsDTM_tidy_cleaned <- reviewsDTM_tidy %>%
anti_join(stop_words, by = c("term" = "word")) %>%
anti_join(ntlk_stop_words_total, by = c("term" = "word")) %>%
anti_join(custom_stop_words, by = c("term" = "word"))
cleaned_documents <- reviewsDTM_tidy_cleaned %>%
group_by(document) %>%
mutate(terms = toString(rep(term, count))) %>%
select(document, terms) %>%
unique()
head(cleaned_documents) # to have a quick look at cleaned_documents
View(cleaned_documents) # to view the whole picture of cleaned_documents
top_terms_by_topic_LDA(cleaned_documents$terms, number_of_topics = 2)
reviewsDTM_tidy_cleaned <- reviewsDTM_tidy_cleaned %>%
mutate(stem = wordStem(term))
cleaned_documents <- reviewsDTM_tidy_cleaned %>%
group_by(document) %>%
mutate(terms = toString(rep(stem, count))) %>%
select(document, terms) %>%
unique()
top_terms_by_topic_LDA(cleaned_documents$terms, number_of_topics = 4)
## from the right subplot of the result, we can see that the hottest topic about cellphone
## in customer's review on Amazon are:
## screen, battery, buy, app, android(operation system), day, camera, time, call
top_terms_by_topic_tfidf <- function(text_df, text_column, group_column, plot = TRUE){
group_column <- enquo(group_column)
text_column <- enquo(text_column)
words <- text_df %>%
unnest_tokens(word, !!text_column) %>%
count(!!group_column, word) %>%
ungroup()
total_words <- words %>%
group_by(!!group_column) %>%
summarize(total = sum(n))
words <- left_join(words, total_words)
tf_idf <- words %>%
bind_tf_idf(word, !!group_column, n) %>%
select(-total) %>%
arrange(desc(tf_idf)) %>%
mutate(word = factor(word, levels = rev(unique(word))))
if(plot == TRUE){
group_name <- quo_name(group_column)
tf_idf %>%
group_by(!!group_column) %>%
top_n(10) %>%
ungroup %>%
ggplot(aes(word, tf_idf, fill = as.factor(group_name))) +
geom_col(show.legend = FALSE) +
labs(x = NULL, y = "tf-idf") +
facet_wrap(reformulate(group_name), scales = "free") +
coord_flip()
}else{
return(tf_idf)
}
}
reviews <- as_tibble(reviews)
reviews <- mutate(reviews, body = as.character(body))
# because tokenizer function doesn't recognize factor data type,
# we need to convert from factor into normal character.
usable_reviews2 <- reviews
usable_reviews2$body <- gsub("[^[:alnum:]]", " ", usable_reviews2$body)
top_terms_by_topic_tfidf(text_df = usable_reviews2,
text_column = body,
group_column = verified,
plot = TRUE)
## then we find a more interesting things: when verified is TRUE, we can see that the hottest topics are described by Spanish.
## after translation, we know that through tf-idf model, the customers are concerned about:
## battery, recommendation, load, great, quick(speed), past experience (nunca = never or ever), fascination and user's gender (sus = his) |
15e33c1ea94bb1a2291b847d07e1810d908a22fc | a8ec0c59d2bca0fe0f571e7b3d358aad4ef43360 | /transmission.error.R | 5088daf98559044ebe083899cfc6ce4f3d15a03b | [] | no_license | dyurovsky/EvoLang | 97e0659be6f40de6cecc3c5a2a4b7f38852021be | 637e450381ed4c4635e1c091e44bbda0eb257e91 | refs/heads/master | 2016-09-06T09:48:40.725172 | 2014-08-15T00:04:46 | 2014-08-15T00:04:46 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 598 | r | transmission.error.R | #Normalized Levenshtein distance function
normLev.fnc <- function(a, b) {
drop(adist(a, b) / nchar(attr(adist(a, b, counts = TRUE), "trafos")))
}
#Read in data. Row 1 = input data. Row 2 = participant 1.
data <- read.table("data/words.csv",sep=",",header=TRUE, row.names=1,
stringsAsFactors=FALSE)
#Segment out just the participants's responses.
responses <- data[,2:27]
#Assign participants to a list for comparison.
L1 <- responses[74,]
L2 <- responses[75,]
#Calculate the normLD between the two sets of responses.
normLD <- diag(normLev.fnc(L1,L2))
mean(normLD[])
|
5f70c529cf38bd8be5d3c004cb359e06915ae164 | f339641cefa9025ef94fe53c9d23856b4ac69933 | /R/MakeTable.R | 743b9b90f5cda0d3222b31839bf4e35f67d80b04 | [
"MIT"
] | permissive | sjbeckett/localcovid19now | 8ba7f044d8e7458cb4c8c490c8389b596624c84f | af7979dd7e4b1f73751617bd2bae17bdbd285184 | refs/heads/main | 2023-04-17T21:06:30.905493 | 2023-01-23T18:31:06 | 2023-01-23T18:31:06 | 413,489,189 | 4 | 4 | MIT | 2022-12-23T18:10:25 | 2021-10-04T15:53:44 | R | UTF-8 | R | false | false | 3,571 | r | MakeTable.R | #' Calculate Risk
#'
#' @description Calculates the percentage probability that one or more persons in a group, of a particular size g, may be infectious given the underlying prevalence of disease.
#'
#' @param p_I Probability one individual in a population is infectious.
#' @param g Event size.
#'
#' @return The risk (%) one or more individuals at an event of size g will be infectious.
#' @export
#' @seealso [estRisk()]
#' @examples
#' risk <- calcRisk(.001, 50)
#'
calcRisk <- function(p_I, g) {
stopifnot("`g` must be a positive value." = is.numeric(g) & g>0)
r <- 1 - (1 - p_I)**g
return(r * 100)
}
#' Create Table of Risk Estimates
#'
#' @description Creates a table showing the estimated risk that one or more people will be infectious for the given input locations, event sizes and ascertainment biases.
#'
#' @param df_in Input data.
#' @param risk_output Name of output file.
#' @param output_prefix Folder location to store table file.
#' @param event_size Event size(s) to calculate risk for.
#' @param asc_bias_list Ascertainment bias(es) to calculate risk for, must be named.
#'
#' @return Creates, and writes to file, a table showing estimated risk that one or more people will be infectious for the given input locations, event sizes and ascertainment biases.
#' @export
#'
#' @importFrom rlang :=
#'
#' @examples
#' \dontrun{
#' Canada <- LoadData("LoadCanada")
#' create_c19r_data(Canada)
#' }
create_c19r_data <- function(df_in,
risk_output = sprintf("world_risk_regions_%s.csv", stringr::str_replace_all(lubridate::today(), "-", "")),
output_prefix = ".",
event_size = c(10, 15, 20, 25, 50, 100, 500, 1000, 5000),
asc_bias_list = cbind(AB1 = 3, AB2 = 4, AB3 = 5)) {
if (!all(is.numeric(event_size)) & !all(event_size > 0)) {
stop("'event_size' must be a vector of positive numbers")
}
if (!all(is.numeric(asc_bias_list)) & !all(asc_bias_list > 0)) {
stop("'asc_bias_list' must be a vector of positive numbers")
}
risk_output <- file.path(output_prefix, risk_output)
if (file.access(dirname(risk_output), mode = 2) != 0) {
stop("Directory for risk_output file does not appear to be writeable.")
}
pInf <- Nr <- geoid <- risk <- NULL
df_in <- data.frame(df_in)
df_in$geometry <- NULL
risk_data <- list()
# bind the ascertainment bias list
df_in <- cbind(df_in, asc_bias_list)
CN <- colnames(asc_bias_list)
asc_bias_list <- as.matrix(df_in[, (ncol(df_in) - ncol(as.matrix(asc_bias_list)) + 1):ncol(df_in)])
colnames(asc_bias_list) <- CN
for (aa in 1:ncol(asc_bias_list)) {
AB <- asc_bias_list[, aa]
data_Nr <- df_in %>%
dplyr::mutate(Nr = pInf * AB)
for (size in event_size) {
cn <- glue::glue("{colnames(asc_bias_list)[aa]}_{size}")
riskdt <- data_Nr %>%
dplyr::mutate(
risk = round(calcRisk(
Nr, size
), 0),
risk = dplyr::case_when(
risk < 1 ~ 0,
TRUE ~ risk
),
"asc_bias" = aa,
"event_size" = size
)
risk_data[[cn]] <- riskdt %>%
dplyr::select(geoid, "{cn}" := risk)
id <- paste(colnames(asc_bias_list)[aa], size, sep = "_")
}
}
risk_data_df <- purrr::reduce(.x = append(list(df_in), risk_data), .f = dplyr::left_join, by = "geoid") %>%
dplyr::mutate(updated = lubridate::ymd(gsub("-", "", Sys.Date())))
utils::write.csv(risk_data_df,
risk_output,
quote = T,
row.names = F
)
}
|
f6eba41092ae6388637ce42788bdf6769028d328 | b9db037ee7bc2ebf9c228ad1f66fecabccfa70be | /R/data.R | 28021d9cd9efdf1942ce714734b278d7ad87605d | [] | no_license | IsaakBM/prioritizr | 924a6d8dcc7c8ff68cd7f5a2077de2fa1f300fe7 | 1488f8062d03e8736de74c9e7803ade57d6fcc29 | refs/heads/master | 2020-12-10T06:23:19.437647 | 2019-12-22T00:04:20 | 2019-12-22T00:04:20 | 233,524,401 | 1 | 0 | null | 2020-01-13T06:13:19 | 2020-01-13T06:13:18 | null | UTF-8 | R | false | false | 6,284 | r | data.R | #' @include internal.R
NULL
#' Simulated conservation planning data
#'
#' Simulated data for making spatial prioritizations.
#'
#' \describe{
#'
#' \item{\code{sim_pu_raster}}{Planning units are represented as raster data.
#' Pixel values indicate planning unit cost and \code{NA} values indicate
#' that a pixel is not a planning unit.}
#'
#' \item{\code{sim_pu_zones_stack}}{Planning units are represented as raster
#' stack data. Each layer indicates the cost for a different management
#' zone. Pixels with \code{NA} values in a given zone indicate that a
#' planning unit cannot be allocated to that zone in a solution.
#' Additionally, pixels with \code{NA} values in all layers are not a
#' planning unit.}
#'
#' \item{\code{sim_locked_in_raster}}{Planning units are represented as raster
#' data. Pixel values are binary and indicate if planning units should be
#' locked in to the solution.}
#'
#' \item{\code{sim_locked_out_raster}}{Planning units are represented as
#' raster data. Pixel values are binary and indicate if planning units
#' should be locked out from the solution.}
#'
#' \item{\code{sim_pu_polygons}}{Planning units represented as polygon data.
#' The attribute table contains fields (columns) indicating the expenditure
#' required for prioritizing each planning unit ("cost" field), if the
#' planning units should be selected in the solution ("locked_in" field),
#' and if the planning units should never be selected in the solution
#' ("locked_out" field).}
#'
#' \item{\code{sim_pu_points}}{Planning units represented as point data.
#' The attribute table follows the same conventions as for
#' \code{sim_pu_polygons}.}
#'
#' \item{\code{sim_pu_lines}}{Planning units represented as line data.
#' The attribute table follows the same conventions as for
#' \code{sim_pu_polygons}.}
#'
#' \item{\code{sim_pu_zone_polygons}}{Planning units represented as polygon
#' data. The attribute table contains fields (columns) indicating the
#' expenditure required for prioritizing each planning unit under different
#' management zones ("cost_1", "cost_2", and "cost_3" fields), and a series
#' of fields indicating the value that each planning unit that should be
#' assigned in the solution ("locked_1", "locked_2", "locked_3" fields).
#' In these locked fields, planning units that should not be locked to a
#' specific value are assigned a \code{NA} value.}
#'
#' \item{\code{sim_features}}{The simulated distribution of ten species.
#' Pixel values indicate habitat suitability.}
#'
#' \item{\code{sim_features_zones}}{The simulated distribution for five
#' species under three different management zones.}
#'
#' \item{\code{sim_phylogeny}}{The phylogenetic tree for the ten species.}
#'
#' }
#'
#' @docType data
#'
#' @aliases sim_pu_polygons sim_pu_zones_polygons sim_pu_points sim_pu_lines sim_pu_raster sim_locked_in_raster sim_locked_out_raster sim_pu_zones_stack sim_features sim_features_zones sim_phylogeny
#'
#' @usage data(sim_pu_polygons)
#'
#' @usage data(sim_pu_zones_polygons)
#'
#' @usage data(sim_pu_points)
#
#' @usage data(sim_pu_lines)
#'
#' @usage data(sim_pu_raster)
#'
#' @usage data(sim_locked_in_raster)
#'
#' @usage data(sim_locked_out_raster)
#'
#' @usage data(sim_pu_zones_stack)
#'
#' @usage data(sim_features)
#'
#' @usage data(sim_features_zones)
#'
#' @usage data(sim_phylogeny)
#'
#' @format
#' \describe{
#'
#' \item{sim_pu_polygons}{\code{\link[sp]{SpatialPolygonsDataFrame-class}}
#' object.}
#'
#' \item{sim_pu_zones_polygons}{
#' \code{\link[sp]{SpatialPolygonsDataFrame-class}} object.}
#'
#' \item{sim_pu_lines}{\code{\link[sp]{SpatialLinesDataFrame-class}} object.}
#'
#' \item{sim_pu_points}{\code{\link[sp]{SpatialPointsDataFrame-class}}
#' object.}
#'
#' \item{sim_pu_raster}{\code{\link[raster]{RasterLayer-class}} object.}
#'
#' \item{sim_pu_zones_stack}{\code{\link[raster]{RasterStack-class}} object.}
#'
#' \item{sim_locked_in_raster}{\code{\link[raster]{RasterLayer-class}}
#' object.}
#'
#' \item{sim_locked_out_raster}{\code{\link[raster]{RasterLayer-class}}
#' object.}
#'
#' \item{sim_features}{\code{\link[raster]{RasterStack-class}} object.}
#'
#' \item{sim_features_zones}{\code{\link{ZonesRaster}} object.}
#'
#' \item{sim_phylogeny}{\code{\link[ape]{phylo}} object.}
#'
#' }
#'
#' @keywords datasets
#'
#' @examples
#' # load data
#' data(sim_pu_polygons, sim_pu_lines, sim_pu_points, sim_pu_raster,
#' sim_locked_in_raster, sim_locked_out_raster, sim_phylogeny,
#' sim_features)
#'
#' # plot example planning unit data
#' \donttest{
#' par(mfrow = c(2, 3))
#' plot(sim_pu_raster, main = "planning units (raster)")
#' plot(sim_locked_in_raster, main = "locked in units (raster)")
#' plot(sim_locked_out_raster, main = "locked out units (raster)")
#' plot(sim_pu_polygons, main = "planning units (polygons)")
#' plot(sim_pu_lines, main = "planning units (lines)")
#' plot(sim_pu_points, main = "planning units (points)")
#'
#' # plot example phylogeny data
#' par(mfrow = c(1, 1))
#' ape::plot.phylo(sim_phylogeny, main = "simulated phylogeny")
#'
#' # plot example feature data
#' par(mfrow = c(1, 1))
#' plot(sim_features)
#'
#' # plot example management zone cost data
#' par(mfrow = c(1, 1))
#' plot(sim_pu_zones_stack)
#'
#' # plot example feature data for each management zone
#' plot(do.call(stack, sim_features_zones),
#' main = paste0("Species ",
#' rep(seq_len(number_of_zones(sim_features_zones)),
#' number_of_features(sim_features_zones)),
#' " (zone ",
#' rep(seq_len(number_of_features(sim_features_zones)),
#' each = number_of_zones(sim_features_zones)),
#' ")"))
#' }
#' @name sim_data
NULL
#' @rdname sim_data
"sim_features"
#' @rdname sim_data
"sim_features_zones"
#' @rdname sim_data
"sim_pu_polygons"
#' @rdname sim_data
"sim_pu_zones_polygons"
#' @rdname sim_data
"sim_pu_zones_polygons"
#' @rdname sim_data
"sim_pu_lines"
#' @rdname sim_data
"sim_pu_points"
#' @rdname sim_data
"sim_pu_raster"
#' @rdname sim_data
"sim_pu_zones_stack"
#' @rdname sim_data
"sim_phylogeny"
#' @rdname sim_data
"sim_locked_in_raster"
#' @rdname sim_data
"sim_locked_out_raster"
|
d87c729fe0c7ad0132c118e69f6d61f2a8340558 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/doremi/examples/predict.doremi.Rd.R | f2fa74ee398575c8660ab9ba0cc41e042dd40ca3 | [] | 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 | 867 | r | predict.doremi.Rd.R | library(doremi)
### Name: predict.doremi
### Title: S3 method to predict signal values in a DOREMI object when
### entering a new excitation
### Aliases: predict.doremi
### ** Examples
myresult <- remi(data = cardio[id == 1],
input = "load",
time = "time",
signal = "hr",
embedding = 5)
#Copying cardio into a new data frame and modifying the excitation column
new_exc <- cardio[id == 1, !"id"]
et <- generate.excitation(amplitude = 100,
nexc = 6,
duration = 2,
deltatf = 1,
tmax = 49,
minspacing = 2)
new_exc$load <- et$exc
new_exc$time <- et$t
predresult <- predict(myresult, newdata = new_exc)
plot(predresult)
|
89f9a3272668416a049eb28a069d65cc3f78cc81 | f2a039179f24429d35067d9b9a2a5c594d1ca409 | /bayes-env/stan-italy.R | 62b47e3e30f28976f0747041bfe125f6cbe53e09 | [] | no_license | stemkov/Tyrell | 673de757cf675c2435f43b7f2d06689521ef8b0a | 8995d9d20025b75ecbc81ae942fc6db22977f178 | refs/heads/master | 2022-10-10T02:59:03.185572 | 2020-06-08T16:58:15 | 2020-06-08T16:58:15 | 266,138,726 | 0 | 0 | null | 2020-05-22T15:03:28 | 2020-05-22T15:03:28 | null | UTF-8 | R | false | false | 3,628 | r | stan-italy.R | # Headers
source("../../src/packages.R")
source('Italy/code/utils/read-data-subnational.r')
source('Italy/code/utils/process-covariates-italy.r')
args = c('base-italy', 'google', 'interventions',
'~ -1 + residential + transit + averageMobility',
'~ -1 + residential + transit + averageMobility'
)
cat(sprintf("Running:\nMobility = %s\nInterventions = %s\nFixed effects:%s\nRandom effects:%s\n\n",
args[2],args[3], args[4],args[5]))
# Read deaths data for regions
d <- read_obs_data()
regions<-unique(as.factor(d$country))
# Read ifr
ifr.by.country <- read_ifr_data(unique(d$country))
ifr.by.country <- ifr.by.country[1:22,]
# Read google mobility, apple mobility, interventions, stringency
google_mobility <- read_google_mobility("Italy")
mobility<-google_mobility[which(google_mobility$country!="Italy"),]
# Read interventions
interventions <- read_interventions()
interventions<-interventions[which(interventions$Country!="Italy"),]
# Table 1 and top 7
regions_sum <- d %>% group_by(country) %>% summarise(Deaths=sum(Deaths)) %>%
inner_join(ifr.by.country) %>% mutate(deathsPer1000=Deaths/popt) %>%
arrange(desc(deathsPer1000))
regions_sum <- regions_sum[,-which(colnames(regions_sum) %in% c("X"))]
regions_sum$ifr<-signif(regions_sum$ifr*100,2)
regions_sum$deathsPer1000 <- signif(regions_sum$deathsPer1000*1000,2)
top_7 <- regions_sum[1:7,]
forecast <- 7 # increaseto get correct number of days to simulate
# Maximum number of days to simulate
N2 <- (max(d$DateRep) - min(d$DateRep) + 1 + forecast)[[1]]
formula = as.formula(args[4])
formula_partial = as.formula(args[5])
processed_data <- process_covariates(regions = regions, mobility = mobility, intervention = interventions,
d = d , ifr.by.country = ifr.by.country, N2 = N2, formula = formula, formula_partial = formula_partial)
stan_data <- processed_data$stan_data
dates <- processed_data$dates
reported_deaths <- processed_data$deaths_by_country
reported_cases <- processed_data$reported_cases
# Add envirionmental data
states <- readRDS("../../clean-data/gadm-states.RDS")
states <- states[states$NAME_0=="Italy",]
states$NAME_1 <- gsub(" ", "_", states$NAME_1)
states$NAME_1[states$NAME_1=="Lombardia"] <- "Lombardy"
states$NAME_1[states$NAME_1=="Trentino-Alto_Adige"] <- "Trento"
states$NAME_1[states$NAME_1=="Piemonte"] <- "Piedmont"
states$NAME_1[states$NAME_1=="Sardegna"] <- "Sardinia"
states$NAME_1[states$NAME_1=="Toscana"] <- "Tuscany"
states$NAME_1[states$NAME_1=="Valle_d'Aosta"] <- "Aosta"
match <- match(regions, states$NAME_1)
# Manually add in Bolzano, which is a city
match[is.na(match)] <- which(states$NAME_1=="Trento")
states <- states[match,]
env_dat <- readRDS("../../clean-data/worldclim-states.RDS")[states$GID_1,,"tmean"]
env_dat <- env_dat[,rep(1:6, c(4,29,31,30,30,6))]
stan_data$env_dat <- scale(t(env_dat))
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)
m = stan_model('stan-models/stan-italy.stan')
fit = sampling(m,data=stan_data,iter=2000,warmup=1500,chains=4,thin=1,control = list(adapt_delta = 0.95, max_treedepth = 15))
out <- rstan::extract(fit)
estimated_cases_raw <- out$prediction
estimated_deaths_raw <- out$E_deaths
estimated_deaths_cf <- out$E_deaths0
regions <- unique(d$country)
# This is a hack to get it to save
states = regions
covariate_data = list(interventions, mobility)
save(fit, dates, reported_cases, reported_deaths, regions, states,
estimated_cases_raw, estimated_deaths_raw, estimated_deaths_cf, stan_data, covariate_data,
file='results/env-italy-stanfit.Rdata')
|
19d8522e60077d2d6794d8baa53ab9eae808f992 | b12c8e086b5cf7791b77c863c22a5ce57c6e3a82 | /extract/Process Landcover.R | 01d6f7c07981898580f8725535d0b5b2c711f6b9 | [] | no_license | mcooper/lc-malnutrition | c3ff1121515af86360032d3808e1aa2e5a9805fa | 5b515745b3148bc129c79d7309d6a51042a72f1b | refs/heads/master | 2021-06-19T14:08:28.535796 | 2021-02-02T22:25:14 | 2021-02-02T22:25:14 | 176,567,490 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,389 | r | Process Landcover.R | setwd('G://My Drive/DHS Processed')
library(dplyr)
lc <- read.csv('landcover.csv')
ag <- paste0('cci_', c('10', '11', '12', '20', '30', '200', '201', '202', '220'))
urban <- 'cci_190'
natural <- paste0('cci_', c('40', '50', '60', '61', '62', '70', '71', '80', '90', '100', '110', '120', '121', '122',
'130', '140', '150', '152', '153', '160', '170', '180', '210'))
nat_water <- 'cci_210'
nat_grass <- paste0('cci_', c('110', '120', '121', '122', '130', '140', '150', '152', '153', '180'))
nat_trees <- paste0('cci_', c('40', '50', '60', '61', '62', '70', '71', '80', '90', '100', '160', '170'))
getPercentCover <- function(selcols, allcolmatch, df){
if(length(selcols) > 1){
selcolsum <- rowSums(df[ , selcols[selcols %in% names(df)]], na.rm=T)
} else{
selcolsum <- df[ , selcols]
}
allcolsum <- rowSums(df[ , grepl(allcolmatch, names(df))], na.rm=T)
return(selcolsum/allcolsum)
}
lc$ag <- getPercentCover(ag, 'cci_', lc)
lc$urban <- getPercentCover(urban, 'cci_', lc)
lc$natural <- getPercentCover(natural, 'cci_', lc)
lc$nat_water <- getPercentCover(nat_water, 'cci_', lc)
lc$nat_grass <- getPercentCover(nat_grass, 'cci_', lc)
lc$nat_trees <- getPercentCover(nat_trees, 'cci_', lc)
lc <- lc %>%
select(ag, urban, natural, interview_year, code, nat_water, nat_grass, nat_trees)
write.csv(lc, 'landcover_processed.csv', row.names=F)
|
742f7bc125ec3f45eeb8311df7c3dc83bebcffc2 | 34b84a3e020f89620baf815005070771ad0d3718 | /tests/future_eapply.R | d5a92d23b0b6e571b1323cabb85159b6ca30f9f3 | [] | no_license | HenrikBengtsson/future.apply | bf6f2d4c2fbb676413f6fd35ce779a48f1f17223 | f91d4650a488666f8fb66d9482e2ee2e41e8a0c3 | refs/heads/develop | 2023-08-05T16:12:09.837448 | 2023-05-26T20:56:42 | 2023-05-26T20:57:10 | 101,941,395 | 212 | 16 | null | 2023-09-06T09:59:06 | 2017-08-31T00:28:31 | R | UTF-8 | R | false | false | 964 | r | future_eapply.R | source("incl/start.R")
message("*** future_eapply() ...")
message("- From example(eapply) ...")
for (strategy in supportedStrategies()) {
message(sprintf("*** strategy = %s ...", sQuote(strategy)))
plan(strategy)
env <- new.env(hash = FALSE)
env$a <- 1:10
env$beta <- exp(-3:3)
env$logic <- c(TRUE, FALSE, FALSE, TRUE)
y0 <- unlist(eapply(env, mean, USE.NAMES = FALSE))
y1 <- unlist(future_eapply(env, mean, USE.NAMES = FALSE))
stopifnot(all.equal(y1, y0))
y0 <- eapply(env, quantile, probs = 1:3/4)
y1 <- future_eapply(env, quantile, probs = 1:3/4)
stopifnot(all.equal(y1, y0))
y0 <- eapply(env, quantile)
y1 <- future_eapply(env, quantile)
stopifnot(all.equal(y1, y0))
y2 <- future_eapply(env, "quantile")
stopifnot(all.equal(y2, y0))
plan(sequential)
message(sprintf("*** strategy = %s ... done", sQuote(strategy)))
} ## for (strategy in ...)
message("*** future_eapply() ... DONE")
source("incl/end.R")
|
a2b24cd72a3bfd3cb59c28c4575714eb860c52b6 | 0a56f9c7da7b2a7ff77a0e91693a6bbb2c6a5a79 | /plot3.R | 50487462b779ec4308c442df20cae9bed698f017 | [] | no_license | aman2000jaiswal14/ExData_Plotting1 | 9f9f193354fbc9381e5efc551bfc80c9c064528b | bafacfd5cfe94b7d6a6be628feabc5acc37a7793 | refs/heads/master | 2022-11-13T10:12:05.213517 | 2020-07-02T07:52:35 | 2020-07-02T07:52:35 | 276,296,186 | 0 | 0 | null | 2020-07-01T06:31:59 | 2020-07-01T06:31:59 | null | UTF-8 | R | false | false | 746 | r | plot3.R | library(dplyr)
library(lubridate)
path<-"household_power_consumption.txt"
df <- read.table(path,header=T,sep=";",na.strings="?")
df<-rename(df,date=Date,time=Time)
df$date=dmy(df$date)
df<-subset(df,date==dmy("01022007") | date==dmy("02022007"))
df$datetime<-paste(as.character(df$date),df$time,sep=" ")
df$datetime<-ymd_hms(df$datetime)
png(file="plot3.png",width=480, height=480)
par(mfrow=c(1,1))
with(df,plot(datetime,Sub_metering_1,col="grey",type='l',lwd=1,ylab="Energy sub metering",xlab=""))
lines(df$datetime,df1$Sub_metering_2,col="red",lwd=1)
lines(df$datetime,df1$Sub_metering_3,col="blue",lwd=1)
legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3")
,lty=1,lwd=2,col=c("grey","red","blue"))
dev.off()
|
fae650bc3e462431f9a2fe7b7d1ae04e5bb6b401 | cf03069c7517b72c355283060a1d9b030947160e | /man/gerar_gatito.Rd | da39a7762390cf1dc4fede71b71fea1d9ea8a255 | [
"MIT"
] | permissive | curso-r/gatitos | 70b28a07a62483518f880beb4eb466e4210a4a82 | 6f41d5d2a4cf21dcb7b9b3405ff9433c12446559 | refs/heads/main | 2023-08-18T06:04:38.247200 | 2021-09-18T20:54:13 | 2021-09-18T20:54:13 | 407,944,311 | 1 | 0 | null | null | null | null | UTF-8 | R | false | true | 283 | rd | gerar_gatito.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/gerar-gatito.R
\name{gerar_gatito}
\alias{gerar_gatito}
\title{Gerar gatito aleatório}
\usage{
gerar_gatito()
}
\value{
Não retorna nada. Apenas plota o gatito.
}
\description{
Gerar gatito aleatório
}
|
3bbd16eaf6ebe5f9182f144a9f73e99ab2a59665 | 3aa5f28626782b046730018b9727f3bcd1ce024b | /ch_2__vec_and_dfs/10__Vectorized_operations.R | fa8380ba8bd8032c3413a9de1aa9dfd7f74e09ca | [] | no_license | asamadgithub/R__complete | 1c854d56f4f3add69256c011c8871b911a108886 | 3d3899aa77958e305bc8a523ed4afd946822bf15 | refs/heads/master | 2022-11-26T23:19:17.183332 | 2020-08-04T15:36:35 | 2020-08-04T15:36:35 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 503 | r | 10__Vectorized_operations.R | # why previously used is not so much used in R
v1 = seq(1,10,1)
v2 = seq(11,20,1)
# additionof vector-a , vector-b
v3 = v1 + v2
# For numerical concatination
v_num = c(v1,v2)
# boolean operation between vectors
v4 <- v1 > v2
# if vector lengths are not equal, then "R"
# will perform recycling of smaller vector i.e. repeat it
# if smaller vector is not multiple of greater one, .. recyclling wirh
v5 <- seq(1,5,1)
v6 <- v1 + v5
# its very natural to send a vector to f() and return from f() |
cea57b8649c542aa5eee746caf13a27da22d54e5 | de22f36730a47e4e0933f34369b2a60b59f9c68b | /Lekcja 4/L4.R | c8bc797ba321b1844503a9a9c0c80f449f891501 | [] | no_license | JohnyP41/STA | 0ae0a2a687bcda82e3aacb3776546736358bdd97 | f7ef5546079d4fa5150ddb9400e16992e2bc0143 | refs/heads/master | 2020-04-04T20:11:38.102821 | 2019-03-31T13:49:01 | 2019-03-31T13:49:01 | 156,237,190 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,564 | r | L4.R | #Zadanie 1
#b
awarie <- read.table('Awarie.txt')
library(EnvStats)
eexp(awarie$V1, ci = TRUE, ci.type = "two-sided", conf.level = 0.95)
#Zadanie 2
#a
load("Pomiary.RData")
head(Pomiary)
qqnorm(Pomiary$V1)
qqline(Pomiary$V1,col='red')
#b
library(EnvStats)
enorm(Pomiary$V1, ci = TRUE, ci.type = "two-sided", conf.level = 0.95, ci.param = "mean")
enorm(Pomiary$V1, ci = TRUE, ci.type = "two-sided", conf.level = 0.95, ci.param = "variance")
#Zadanie 3
#a
lambda.cint <- function(x,conf.level) {
title<-c("lambda")
a <-1-conf.level
est<-sum(x^2)/length(x)
l<-(sum(x^2)/length(x))*(1-(qnorm(1-a/2)/sqrt(length(x))))
r<-(sum(x^2)/length(x))*(1+(qnorm(1-a/2)/sqrt(length(x))))
b<-list(title=title,est=est,l=l,r=r,conf.level=conf.level)
class(b)<-"confint"
return(b)
}
#b
print.confint <- function(x){
cat(x$conf.level*100, "percent confidence interval:", "\n")
cat(x$l, " ", x$r, "\n")
}
summary.confint <- function(x){
cat("\n", "Confidence interval of", x$title, "\n", "\n")
cat(x$conf.level*100, "percent confidence interval:", "\n")
cat(x$l, " ", x$r, "\n")
cat("sample estimate", "\n")
cat(x$est, "\n")
}
#wywolania
x<-c(0.9,6.2, 2.1 ,4.1, 7.3,1.0, 4.6 ,6.4 ,3.8 ,5.0,2.7, 9.2, 5.9, 7.4 ,3.0, 4.9, 8.2 ,5.0, 1.2 ,10.1,12.2, 2.8, 5.9 ,8.2, 0.5)
l<-lambda.cint(x,0.95)
print.confint(l)
summary.confint(l)
#Zadanie 4
Energia <- read.table("Energia.txt", dec = ".",header=TRUE)
head(Energia)
attach(Energia)
model <- lm(energia~produkcja, data = Energia)
nowy <- data.frame(produkcja=8)
predict(model, nowy, interval = 'prediction')
|
863483e22f643920d78c2477927404f768bf8e6f | cb54eb7a09f528f3ba692e1ee0b1801b5f38f859 | /scripts/post_gres.R | 135d250bf447cfc22058f1a05441f269c1f3a9a7 | [
"MIT"
] | permissive | martin-gleason/training_postgres_r | f7948c55d292b8d2557e16852381e97cc760b457 | 4d70e297ba7f0eccf7bf8e35f2711afe05e4f5df | refs/heads/master | 2020-05-20T14:39:11.805590 | 2019-06-10T21:39:57 | 2019-06-10T21:39:57 | 185,627,239 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 50 | r | post_gres.R | #Postgres
library(tidyverse)
library(RPostgreSQL)
|
5fba54de3977a96e4a32c184e85c267e6921637e | 1d7b001652c4a29fd464e9795f17f4353cd5ceeb | /man/multistate.Rd | c8017bcbbd7b692d8bdacb445eeccd5ddccc4d0a | [] | no_license | amayer2010/lsttheory | b1d0cc2150634bfd0c85692f2585ec91f788abf5 | 2e1f868e6afca0f6e6955b3e82e8e162ff9e405b | refs/heads/master | 2022-12-02T14:24:28.412614 | 2022-11-21T20:01:55 | 2022-11-21T20:01:55 | 14,995,999 | 3 | 3 | null | null | null | null | UTF-8 | R | false | true | 381 | rd | multistate.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/00documentation.R
\docType{data}
\name{multistate}
\alias{multistate}
\title{Dataset multistate.}
\format{
A data frame with 400 rows and 4 variables
}
\description{
A simulated dataset. The variables are:
}
\details{
\itemize{
\item y11.
\item y21.
\item y12.
\item y22.
}
}
\keyword{datasets}
|
674e31dcd66df845abcb06801cf5921cce42f0d8 | 279175ef2e145e1d4caaba1f4fa0743de6948582 | /R/tidycols.R | 63238feda00030b41e0377db070879af93599b72 | [] | no_license | neugelb/fb2ga | ed896bd544fc42a3d4beb2acd62874db3bdf5706 | f15be850a0e6642182bf774daf4c1e5949ee1a4e | refs/heads/master | 2020-05-27T01:35:53.756739 | 2019-06-06T09:41:07 | 2019-06-06T09:41:07 | 188,439,309 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 417 | r | tidycols.R | #' tidycols
#'
#' An easy function for cleaning up column names
#' @param df Your data frame
#' @export
tidycols <- function(df) {
require(snakecase)
dfnames <- colnames(df)
dfnames <- to_snake_case(dfnames,sep_out = "_")
dfnames <- tolower(gsub(" ","_",dfnames))
dfnames <- gsub(".","_",dfnames,fixed=TRUE)
dfnames <- gsub("/","_per_",dfnames,fixed=TRUE)
colnames(df) <- dfnames
return(df)
}
|
89f7cbce0034e1c36287920a173290234385abab | 9690857dc27aedec79cb4b71b0edaebcfee3c65b | /brownian_stuff/BrownianFractar.R | 4ed4ad5a384d8fb07f10357546fc351ebb2d58a7 | [] | no_license | inuzm/Funsies | f1920cd8d9e287192f79f16dd0e8fbda8bf4c7c2 | e14f1277cefb12779ee900f60862396092f12680 | refs/heads/master | 2020-04-24T17:17:57.309217 | 2020-03-11T23:28:10 | 2020-03-11T23:28:10 | 172,141,969 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,647 | r | BrownianFractar.R | require(pracma)
require(ggplot2)
brownian.xy <- function(n = 1, Time = 1, x, y){
vtime <- seq(from = 0, to = Time, by = Time / n)
brown <- c(0, cumsum(rnorm(n = n, sd = sqrt(Time / n))))
bridge <- x + brown - vtime * (brown[length(brown)] + x - y) / Time
return(bridge)
}
rare.brown <- function(n = 1e4, Time = 1){
index1 <- c(floor(seq(1, 1e4, by = 1e4/1458))[-1], 1e4 + 1)
index2 <- c(1, index1[-1458])
X <- do.call(rbind.data.frame, fractalcurve(n = 5, which = "molecule"))
X[1, ] <- X[1, ] + rnorm(n = 1459, sd = 1e-2)
X[2, ] <- X[2, ] + rnorm(n = 1459, sd = 1e-2)
result <- data.frame(x = numeric(1e4 + 1), y = numeric(1e4 + 1))
for(i in 1:1458){
result$x[index2[i]:index1[i]] <- brownian.xy(n = index1[i] - index2[i],
Time = Time * (index1[i] - index2[i])/1e4,
x = X[1, i], y = X[1, i+1])
result$y[index2[i]:index1[i]] <- brownian.xy(n = index1[i] - index2[i],
Time = Time * (index1[i] - index2[i])/1e4,
x = X[2, i], y = X[2, i+1])
}
return(result)
}
rare.brown2 <- function(n = 1e5, Time = 1){
index1 <- c(floor(seq(1, 1e5, by = 1e5/1458))[-1], 1e5 + 1)
index2 <- c(1, index1[-1458])
X <- do.call(rbind.data.frame, fractalcurve(n = 5, which = "molecule"))
X[1, ] <- X[1, ] + rnorm(n = 1459, sd = 1e-2)
X[2, ] <- X[2, ] + rnorm(n = 1459, sd = 1e-2)
result <- data.frame(x = numeric(1e5 + 1), y = numeric(1e5 + 1))
for(i in 1:1458){
result$x[index2[i]:index1[i]] <- brownian.xy(n = index1[i] - index2[i],
Time = Time * (index1[i] - index2[i])/1e4,
x = X[1, i], y = X[1, i+1])
result$y[index2[i]:index1[i]] <- brownian.xy(n = index1[i] - index2[i],
Time = Time * (index1[i] - index2[i])/1e4,
x = X[2, i], y = X[2, i+1])
}
return(result)
}
X <- rare.brown2(Time = 0.1)
ggplot(data = X, aes(x = x, y = y)) +
geom_path(alpha = 1)
p <- ggplot() +
theme_void() +
theme(plot.background = element_rect(fill = "#fdf6e3", colour = "#fdf6e3"))
timey <- txtProgressBar(min = 0, max = 500, style = 3)
for(i in 1:300){
X <- rare.brown(Time = 1)
p <- p +
geom_path(data = X, aes(x = x, y = y), alpha = 0.009, colour = "darkorchid1")
setTxtProgressBar(timey, i)
}
close(timey)
plot(p)
|
f3671c3fcafb0d5038139485c9bd412ff8f2087e | 12cdcabbc263d7dd18823feb5f59e3449fe57649 | /Cluster/Cluster.R | 6329d4d4af94396f19d179b4243ebed968e87c9a | [] | no_license | saraselis/Machine-Learning-em-R-IESB | cb2d96d0d1bdbd79ddb8d311921181e4022b9230 | d4fa94911c9db34677d68034b1c07821f4f22c0f | refs/heads/master | 2020-06-14T03:01:13.905315 | 2019-08-10T01:06:22 | 2019-08-10T01:06:22 | 193,600,144 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,445 | r | Cluster.R | #Pacotes necessario
#install.packages('stringr')
library(stringr)
#install.packages('dplyr')
library(dplyr)
#install.packages("data.table")
library(data.table)
#install.packages('randomForest')
library(randomForest)
#install.packages('caret')
library(caret)
#install.packages('caTools')
library(caTools)
#install.packages('ggplot2')
library(ggplot2)
#install.packages('lattice')
library(lattice)
#install.packages('e1071')
library('e1071')
getwd()
setwd('C:/Users/1712082018/Documents/R/Cluster')
#importando
trem <- read.csv(file = 'dados_adolescentes.csv', sep=',', stringsAsFactors = FALSE,
encoding='UTF-8')
dados <- trem
summary(dados)
table(dados$gender, useNA = 'ifany')
#ados_limpos <- dados[dados$age >=13 & dados$age <20,]
summary(dados_limpos)
dados_limpos <- dados
dados_limpos$age <- ifelse(dados_limpos$age >= 13 & dados_limpos$age <20, dados_limpos$age, NA)
summary(dados_limpos$age)
medias <- ave( dados_limpos$age, dados_limpos$gradyear, FUN=function(x) mean(x, na.rm=TRUE))
medias
dados_limpos$age <- ifelse(is.na(dados_limpos$age), medias, dados_limpos$age)
table(dados_limpos$gender, useNA = 'ifany')
dados_limpos <- dados_limpos[!is.na(dados_limpos$gender),]
interesses <- dados_limpos[,5:40]
clusters <- kmeans(interesses, 5)
dados_limpos$cluster <- clusters$cluster
aggregate(data=dados_limpos, age ~cluster, mean)
|
ddda840aae6156bdd8648e38e2da9d698dfbb68b | 7e9b94827b22ec9ff83315a74952325fd3d0036e | /app/server.R | 59e4de4ee078f5ab4a00510858781f8cb94cf407 | [] | no_license | kwhitehall/Shiny_app_Azure | 95f670965111e04535e031b39d27fe9714cc92f7 | 49ae28ac92b1060df4f5db733cc0cc42814a2b02 | refs/heads/master | 2020-05-01T01:02:16.638411 | 2019-04-03T19:24:38 | 2019-04-03T19:24:38 | 177,185,015 | 10 | 8 | null | null | null | null | UTF-8 | R | false | false | 3,087 | r | server.R | #
# This ShinyApp shows how to evaluate and compare
# the quality of linear models.
#
library(shiny)
shinyServer(function(input, output) {
# Reactive value that triggers plot update and stores fitted values
v <- reactiveValues(fitted_values = NULL,
r2 = NULL)
# When action button was triggered...
observeEvent(input$trigger_estimation, {
# Add progress bar
withProgress(message = 'Please wait',
detail = 'Run estimation...', value = 0.6,
{
# Run estimation depending on the model specification
if (input$model == "linear"){
estimation <- lm(data[, input$dataset] ~ data$x)
}
else if (input$model == "quadratic"){
estimation <- lm(data[, input$dataset] ~ data$x + data_helper$x2)
}
else if (input$model == "root"){
estimation <- lm(data[, input$dataset] ~ data_helper$sqrt_x)
}
else {
estimation <- lm(data[, input$dataset] ~ data$x + data_helper$x2 + data_helper$x3)
}
# Increase progress bar to 0.8
incProgress(0.8, detail="Store results")
v$fitted_values <- estimation$fitted.values
v$residuals <- estimation$residuals
v$adjr2 <- round(summary(estimation)$adj.r.squared,4)*100
# Increase progress bar to 1
incProgress(1, detail="Finish")
})
})
# Estimation Results
output$estimation_results <- renderText(
v$adjr2
)
# Accuracy Box
output$accuracy_box <- renderValueBox({
valueBox(
paste0(v$adjr2, "%"), "Accuracy (Adj. R2)", icon = icon("tachometer"),
color = "light-blue"
)
})
# Overview Plot
output$plot <- renderPlot({
plot(data$x, data[, input$dataset],
main = "Estimation of random points",
xlab = "x variable",
ylab = "y variable")
lines(v$fitted_values,
col ="red",
lwd = 3
)
})
# Residual Summary
output$residuals_mean <- renderText(
if (is.null(v$fitted_values)) "No estimation has been computed, yet"
else paste("Mean:", round(mean(v$residuals),4))
)
output$residuals_minmax <- renderUI(
if (is.null(v$fitted_values)) "No estimation has been computed, yet"
else {
str1 <- paste("Min value:", round(min(v$residuals),4))
str2 <- paste("Max value:", round(max(v$residuals),4))
HTML(paste(str1, str2, sep = '<br/>'))
}
)
# Residual plot
output$residual_plot <- renderPlot(
if (is.null(v$fitted_values)) return()
else {
plot(data$x, v$residuals,
xlab = "x variable",
ylab = "Residuals")
abline(h=0,
col="red")
}
)
# Residual histogram
output$residuals_histogram <- renderPlot(
if (is.null(v$fitted_values)) return()
else {
hist(v$residuals,
breaks = 20,
main = "",
xlab = "Residuals",
ylab = "Frequency")
abline(v=0,
col="red")
}
)
# Show Data Table
output$data_table <- renderDataTable(data)
}) |
f07a49a02de77131e20c210c2c194e76728df945 | 744eb9be6455f86de1c53c571a5051a8ce7d1ac4 | /DabblingSK.R | db416a4ceef09e558028ee5d99dedce5b7b964e7 | [] | no_license | derek-corcoran-barrios/Meta | 77037a4bb48a9ef8a2a216369609e90c470f3e0f | 7794a07c4ddb4f1c3136786882bd3f62095157ab | refs/heads/master | 2021-03-19T13:24:17.685664 | 2017-03-27T01:00:13 | 2017-03-27T01:00:13 | 82,729,469 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 6,963 | r | DabblingSK.R | #Load the data
newDat <- readRDS("newDat.rds")
SK <- readRDS("SK.prairie.banding.rds")
#Load packages
library(lme4)
library(boot)
library(merTools)
library(ggplot2)
library(dplyr)
#Group Birds by year
SK.by.year <- group_by(SK, year)
#Calculate the Observed proportion of youngs by yeat
SK.by.year <- summarise(SK.by.year, prop = weighted.mean(Young, Count.of.Birds), pond.count = mean(pond.count), summerfallow = mean(summerfallow), natural.area = mean(natural.area))
#Set "mean" location
SK.by.year$location <- as.factor(551475)
#fit glmer model
fit1 <- glmer(Young ~ pond.count + (1|year/location), family = "binomial", weight = Count.of.Birds, data = SK)
#Create the bootstrap for the line + ribbon part of the graph
bootfit2 <- bootMer(fit1, FUN=function(x)predict(x, newDat, allow.new.levels=T, type = "response"),nsim=100)
apply(bootfit2$t, 2, sd)
newDat$lci <- apply(bootfit2$t, 2, quantile, 0.025)
newDat$uci <- apply(bootfit2$t, 2, quantile, 0.975)
newDat$Youngprop <- predict(fit1, newDat, allow.new.levels=T, type ="response")
#Pred is the predicted value for the 51 observed points
SK.by.year$pred <- predict(fit1, SK.by.year, allow.new.levels=T, type ="response")
#Create a separate Bootfit for the prediction over observed yearly points
bootfit3 <- bootMer(fit1, FUN=function(x)predict(x, SK.by.year, allow.new.levels=T, type = "response"),nsim=100)
#Use them to get the standard error and standard deviation for each point
SK.by.year$se <- (apply(bootfit3$t, 2, sd)/sqrt(length(bootfit3$t)))
SK.by.year$SD <- apply(bootfit3$t, 2, sd)
#Change the years to numeirc in order to generate the Decadal binning
SK$B.Year <- as.numeric(as.character(SK$B.Year))
SK.by.year$year <- as.numeric(as.character(SK.by.year$year))
#Bin the decades for both databases SK and SK.by.year
SK$decade <- ifelse(SK$B.Year < 1970, as.character("1960s"), ifelse(SK$B.Year >= 1970 & SK$B.Year < 1980, as.character("1970s"), ifelse(SK$B.Year >= 1980 & SK$B.Year < 1990, as.character("1980s"), ifelse(SK$B.Year >= 1990 & SK$B.Year < 2000, as.character("1990s"), ifelse(SK$B.Year >= 2000 & SK$B.Year < 2010, as.character("2000s"), as.character("2010s"))))))
SK.by.year$Decade <- ifelse(SK.by.year$year < 1970, as.character("1960s"), ifelse(SK.by.year$year >= 1970 & SK.by.year$year < 1980, as.character("1970s"), ifelse(SK.by.year$year >= 1980 & SK.by.year$year < 1990, as.character("1980s"), ifelse(SK.by.year$year >= 1990 & SK.by.year$year < 2000, as.character("1990s"), ifelse(SK.by.year$year >= 2000 & SK.by.year$year < 2010, as.character("2000s"), as.character("2010s"))))))
#Create a color palet, in this case it goes from Paleturquoise to blue 4, spanning 6 colors
#for more colors go to http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf
cc <- scales::seq_gradient_pal("paleturquoise1", "blue4", "Lab")(seq(0,1,length.out=6))
cc <- scales::seq_gradient_pal("paleturquoise1", "blue4", "Lab")(seq(0,1,length.out=6))
#####GGPLOTS###########
#######################
#non summarised plot binomial with jittering
p1 <- ggplot(data = newDat, aes(x = pond.count, y = Youngprop))+ geom_line(size = 1, color = "black")+ geom_ribbon(aes(ymin = lci, ymax= uci), fill = "red", alpha = 0.5) + xlab("Pond count") + ylab("Proportion of juveniles") +geom_point(data = SK, aes(y = Young, x = pond.count, color = decade), alpha = 0.5,position=position_jitter(width=0, height=0.15))+
theme(legend.position="bottom") +scale_color_manual(values =cc)
#The selected plot, with points and standard errors
p2 <- ggplot(data = newDat, aes(x = pond.count, y = Youngprop))+ geom_line(size = 1, color = "black")+ geom_ribbon(aes(ymin = lci, ymax= uci), fill = "grey", alpha = 0.5) + xlab("Pond count") + ylab("Proportion of juveniles") +
theme(legend.position="bottom") + ylim(c(0,1))
p2 <- p2 + geom_errorbar(size = 0.3,inherit.aes = FALSE , data= SK.by.year, aes(x = pond.count),ymin = (SK.by.year$pred - SK.by.year$SD), ymax =(SK.by.year$pred + SK.by.year$SD), width = 0.07)+geom_point(data = SK.by.year, aes(x = pond.count, y = pred, color = Decade), size = 1.5)+ theme(
panel.background = element_rect(fill = "transparent",colour = NA), # or theme_blank()
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
plot.background = element_rect(fill = "transparent",colour = NA)
)+
theme(axis.line.x = element_line(color="black", size = 0.5),
axis.line.y = element_line(color="black", size = 0.5))
# x = year, y = Porportion of young
p3 <- ggplot(data = newDat, aes(x = as.numeric(as.character(year)), y = Youngprop)) + geom_smooth(data = SK.by.year,aes(x = year, y = prop))+ xlab("Year") + ylab("Proportion of young") +geom_point(data = SK.by.year, aes(x = year, y = prop, color = pond.count), alpha = 0.5)+
theme(legend.position="bottom")
#If you want to combine many ggplots you use gridextra
library(gridExtra)
#Just list the names of the plots and add number of columns
grid.arrange(p1, p2, p3, ncol = 2)
######Surface plots
#Load packages
library(caret)
library(lme4)
library(rgl)
library(scatterplot3d)
#Load data
newDat <- readRDS("newDat.rds")
M11z <- readRDS("M11z.rds")
SK <- readRDS("SK.prairie.banding.rds")
#Fit model
fit2 <- glmer(Young ~ summerfallow + natural.area + pond.count + (1|year/location), family = "binomial", weight = Count.of.Birds, data = SK)
#Expand grid makes an all possible combination dataframe to predict on
Surfacegrid <- expand.grid(summerfallow = seq(from = min(SK$summerfallow), to = max(SK$summerfallow), length.out = 50), natural.area = seq(from = min(SK$natural.area), to = max(SK$natural.area), length.out = 100))
#Fix all other variables to the mean
Surfacegrid$pond.count <- 0.1853
Surfacegrid$year <- as.factor(1987)
Surfacegrid$location <- as.factor(551475)
#Predict the Proportion of youngs for the 3D plot
Surfacegrid$Young <- predict(fit2, Surfacegrid, re.form = NA, type = "response")
#plot moving 3d for personal visualization and gifs
plot3d(x =Surfacegrid$natural.area, y = Surfacegrid$Young, Surfacegrid$summerfallow, col = "red",xlab = "Summerfallow", ylab ="Proportion of youngs", zlab = "Natural Area")
#Actuall 3d surface for plot
scat3d <- scatterplot3d(x =Surfacegrid$natural.area, y = Surfacegrid$summerfallow, Surfacegrid$Young, pch = 1, xlab = "Natural area", ylab = "Summerfallow", zlab = "Proportion of youngs", highlight.3d = TRUE, grid = FALSE, angle = 200, x.ticklabs = seq(from = -1.5, to = 1.5, by = 0.5))
#Add observed points to the plot
scat3d$points3d(x = SK.by.year$natural.area, y = SK.by.year$summerfallow, SK.by.year$prop,
col="blue", pch=16)
#If you want to test angles this is the loop I made
for (i in seq(from =0, to = 270, by = 2)){
Title = as.character(i)
scatterplot3d(x =Surfacegrid$natural.area, y = Surfacegrid$summerfallow, Surfacegrid$Young, color = "red", pch = 1, xlab = "Natural area", ylab = "Summerfallow", zlab = "Proportion of youngs", highlight.3d = TRUE, grid = FALSE, angle = i, main = Title)
}
|
23d56e3610a8e958dbc64ab3b9dda6f60c855b68 | fd6f271a68c5bf575c3db49a828be1e40bfc8856 | /man/taxaExtent.Rd | a4e049eae90f407050e5a74b244f878bab2d70d6 | [] | no_license | cran/soilDB | 57df11e3b59c4d575fe796de0abfaec1f7ac34b6 | 7e0bd1a50c268319003d47376c4525da51ac7b0d | refs/heads/master | 2023-09-06T04:30:47.133326 | 2023-08-29T06:20:02 | 2023-08-29T08:31:36 | 17,699,760 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 9,829 | rd | taxaExtent.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/taxaExtent.R
\name{taxaExtent}
\alias{taxaExtent}
\title{Get SoilWeb 800m Major Component Soil Taxonomy Grids}
\usage{
taxaExtent(
x,
level = c("order", "suborder", "greatgroup", "subgroup"),
formativeElement = FALSE,
timeout = 60,
as_Spatial = getOption("soilDB.return_Spatial", default = FALSE)
)
}
\arguments{
\item{x}{single taxon label (e.g. \code{haploxeralfs}) or formative element (e.g. \code{pale}), case-insensitive}
\item{level}{the taxonomic level within the top 4 tiers of Soil Taxonomy, one of \code{'order'}, \code{'suborder'}, \code{'greatgroup'}, \code{'subgroup'}}
\item{formativeElement}{logical, search using formative elements instead of taxon label}
\item{timeout}{time that we are willing to wait for a response, in seconds}
\item{as_Spatial}{Return raster (\code{RasterLayer}) classes? Default: \code{FALSE}.}
}
\value{
a \code{SpatRaster} object (or \code{RasterLayer} when \code{as_Spatial=TRUE})
}
\description{
This function downloads a generalized representation of the geographic extent of any single taxon from the top 4 levels of Soil Taxonomy, or taxa matching a given formative element used in Great Group or subgroup taxa. Data are provided by SoilWeb, ultimately sourced from the current SSURGO snapshot. Data are returned as \code{raster} objects representing area proportion falling within 800m cells. Currently area proportions are based on major components only. Data are only available in CONUS and returned using an Albers Equal Area / NAD83(2011) coordinate reference system (EPSG: 5070).
}
\details{
See the \href{https://ncss-tech.github.io/AQP/soilDB/taxa-extent.html}{Geographic Extent of Soil Taxa} tutorial for more detailed examples.
\subsection{Taxon Queries}{
Taxon labels can be conveniently extracted from the \code{"ST_unique_list"} sample data, provided by the \href{https://github.com/ncss-tech/SoilTaxonomy}{SoilTaxonomy package}.
}
\subsection{Formative Element Queries}{
\subsection{Greatgroup:}{
The following labels are used to access taxa containing the following formative elements (in parentheses)
\itemize{
\item acr: (acro/acr) extreme weathering
\item alb: (alb) presence of an albic horizon
\item anhy: (anhy) very dry
\item anthra: (anthra) presence of an anthropic epipedon
\item aqu: (aqui/aqu) wetness
\item argi: (argi) presence of an argillic horizon
\item calci: (calci) presence of a calcic horizon
\item cry: (cryo/cry) cryic STR
\item dur: (duri/dur) presence of a duripan
\item dystr: (dystro/dystr) low base saturation
\item endo: (endo) ground water table
\item epi: (epi) perched water table
\item eutr: (eutro/eutr) high base saturation
\item ferr: (ferr) presence of Fe
\item fibr: (fibr) least decomposed stage
\item fluv: (fluv) flood plain
\item fol: (fol) mass of leaves
\item fragi: (fragi) presence of a fragipan
\item fragloss: (fragloss) presence of a fragipan and glossic horizon
\item frasi: (frasi) not salty
\item fulv: (fulvi/fulv) dark brown with organic carbon
\item glac: (glac) presence of ice lenses
\item gloss: (glosso/gloss) presence of a glossic horizon
\item gypsi: (gypsi) presence of a gypsic horizon
\item hal: (hal) salty
\item hemi: (hemi) intermediate decomposition
\item hist: (histo/hist) organic soil material
\item hum: (humi/hum) presence of organic carbon
\item hydr: (hydro/hydr) presence of water
\item kandi: (kandi) presence of a kandic horizon
\item kanhap: (kanhaplo/kanhap) thin kandic horizon
\item luvi: (luvi) illuvial organic material
\item melan: (melano/melan) presence of a melanic epipedon
\item moll: (molli/moll) presence of a mollic epipedon
\item natr: (natri/natr) presence of a natric horizon
\item pale: (pale) excessive development
\item petr: (petro/petr) petrocalcic horizon
\item plac: (plac) presence of a thin pan
\item plagg: (plagg) presence of a plaggen epipedon
\item plinth: (plinth) presence of plinthite
\item psamm: (psammo/psamm) sandy texture
\item quartzi: (quartzi) high quartz content
\item rhod: (rhodo/rhod) dark red colors
\item sal: (sali/sal) presence of a salic horizon
\item sapr: (sapr) most decomposed stage
\item sombri: (sombri) presence of a sombric horizon
\item sphagno: (sphagno) presence of sphagnum moss
\item sulf: (sulfo/sulfi/sulf) presence of sulfides or their oxidation products
\item torri: (torri) torric/aridic SMR
\item ud: (udi/ud) udic SMR
\item umbr: (umbri/umbr) presence of an umbric epipedon
\item ust: (usti/ust) ustic SMR
\item verm: (verm) wormy, or mixed by animals
\item vitr: (vitri/vitr) presence of glass
\item xer: (xero/xer) xeric SMR
}
}
\subsection{Subgroup:}{
The following labels are used to access taxa containing the following formative elements (in parenthesis).
\itemize{
\item abruptic: (abruptic) abrupt textural change
\item acric: (acric) low apparent CEC
\item aeric: (aeric) more aeration than typic subgroup
\item albaquic: (albaquic) presence of albic minerals, wetter than typic subgroup
\item albic: (albic) presence of albic minerals
\item alfic: (alfic) presence of an argillic or kandic horizon
\item alic: (alic) high extractable Al content
\item anionic: (anionic) low CEC or positively charged
\item anthraquic: (anthraquic) human controlled flooding as in paddy rice culture
\item anthropic: (anthropic) an anthropic epipedon
\item aquic: (aquic) wetter than typic subgroup
\item arenic: (arenic) 50-100cm sandy textured surface
\item argic: (argic) argillic horizon
\item aridic: (aridic) more aridic than typic subgroup
\item calcic: (calcic) presence of a calcic horizon
\item chromic: (chromic) high chroma colors
\item cumulic: (cumulic) thickened epipedon
\item duric: (duric) presence of a duripan
\item durinodic: (durinodic) presence of durinodes
\item dystric: (dystric) lower base saturation percentage
\item entic: (entic) minimal surface/subsurface development
\item eutric: (eutric) higher base saturation percentage
\item fibric: (fibric) >25cm of fibric material
\item fluvaquentic: (fluvaquentic) wetter than typic subgroup, evidence of stratification
\item fragiaquic: (fragiaquic) presence of fragic properties, wetter than typic subgroup
\item fragic: (fragic) presence of fragic properties
\item glacic: (glacic) presence of ice lenses or wedges
\item glossaquic: (glossaquic) interfingered horizon boundaries, wetter than typic subgroup
\item glossic: (glossic) interfingered horizon boundaries
\item grossarenic: (grossarenic) >100cm sandy textured surface
\item gypsic: (gypsic) presence of gypsic horizon
\item halic: (halic) salty
\item haplic: (haplic) central theme of subgroup concept
\item hemic: (hemic) >25cm of hemic organic material
\item humic: (humic) higher organic matter content
\item hydric: (hydric) presence of water
\item kandic: (kandic) low activity clay present
\item lamellic: (lamellic) presence of lamellae
\item leptic: (leptic) thinner than typic subgroup
\item limnic: (limnic) presence of a limnic layer
\item lithic: (lithic) shallow lithic contact present
\item natric: (natric) presence of sodium
\item nitric: (nitric) presence of nitrate salts
\item ombroaquic: (ombroaquic) surface wetness
\item oxyaquic: (oxyaquic) water saturated but not reduced
\item pachic: (pachic) epipedon thicker than typic subgroup
\item petrocalcic: (petrocalcic) presence of a petrocalcic horizon
\item petroferric: (petroferric) presence of petroferric contact
\item petrogypsic: (petrogypsic) presence of a petrogypsic horizon
\item petronodic: (petronodic) presence of concretions and/or nodules
\item placic: (placic) presence of a placic horizon
\item plinthic: (plinthic) presence of plinthite
\item rhodic: (rhodic) darker red colors than typic subgroup
\item ruptic: (ruptic) intermittent horizon
\item salic: (salic) presence of a salic horizon
\item sapric: (sapric) >25cm of sapric organic material
\item sodic: (sodic) high exchangeable Na content
\item sombric: (sombric) presence of a sombric horizon
\item sphagnic: (sphagnic) sphagnum organic material
\item sulfic: (sulfic) presence of sulfides
\item terric: (terric) mineral substratum within 1 meter
\item thapto: (thaptic/thapto) presence of a buried soil horizon
\item turbic: (turbic) evidence of cryoturbation
\item udic: (udic) more humid than typic subgroup
\item umbric: (umbric) presence of an umbric epipedon
\item ustic: (ustic) more ustic than typic subgroup
\item vermic: (vermic) animal mixed material
\item vitric: (vitric) presence of glassy material
\item xanthic: (xanthic) more yellow than typic subgroup
\item xeric: (xeric) more xeric than typic subgroup
}
}
}
}
\examples{
\dontshow{if (curl::has_internet() && requireNamespace("terra")) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
\dontshow{\}) # examplesIf}
\dontrun{
library(terra)
# soil order
taxa <- 'vertisols'
x <- taxaExtent(taxa, level = 'order')
# suborder
taxa <- 'ustalfs'
x <- taxaExtent(taxa, level = 'suborder')
# greatgroup
taxa <- 'haplohumults'
x <- taxaExtent(taxa, level = 'greatgroup')
# subgroup
taxa <- 'Typic Haploxerepts'
x <- taxaExtent(taxa, level = 'subgroup')
# greatgroup formative element
taxa <- 'psamm'
x <- taxaExtent(taxa, level = 'greatgroup', formativeElement = TRUE)
# subgroup formative element
taxa <- 'abruptic'
x <- taxaExtent(taxa, level = 'subgroup', formativeElement = TRUE)
# coarsen for faster plotting
a <- terra::aggregate(x, fact = 5, na.rm = TRUE)
# quick evaluation of the result
terra::plot(a, axes = FALSE)
}
}
\author{
D.E. Beaudette and A.G. Brown
}
|
fde3c789f3e3bb787107d48dfa60a59d05dc81e4 | fbcdb1aae40c7296f5b5edfc2bc59a5669496df2 | /R/TextAndWebMining/sample4.R | e1ba97e7378e565e129fb75efd331378b98a6424 | [] | no_license | Fr4nc3/code-hints | b9db1e6b4697fc6932d92e5977a8fbc8d2a8d591 | 931575a9bd7f843fca006c6616754b49161dcb50 | refs/heads/master | 2023-02-05T23:07:24.085366 | 2022-08-11T13:00:59 | 2022-08-11T13:00:59 | 52,673,727 | 5 | 3 | null | 2023-01-31T22:44:42 | 2016-02-27T15:37:48 | HTML | UTF-8 | R | false | false | 16,941 | r | sample4.R | ##########################################
# Francia Riesco Assignment 3
# 09/21/2017 (LAST HOMEWORK)
##########################################
##########################################
# Francia Riesco Assignment4
# 10/02/2017
##########################################
setwd("D:/studies/2017-fall/CS688/hw/")
getwd()
### --- From the Module 3 ----
library(tm) # Framework for text mining.
library(SnowballC) # Provides wordStem() for stemming.
library(qdap) # Quantitative discourse analysis of transcripts.
library(qdapDictionaries)
library(dplyr) # Data preparation and pipes %>%.
library(RColorBrewer) # Generate palette of colors for plots.
library(ggplot2) # Plot word frequencies.
library(scales) # Common data analysis activities.
# Text Classification
library(class) # Using kNN
#D:\studies\2017-fall\CS688\hw\hw3\20Newsgroups\20news-bydate-train
pathTrain <- file.path(getwd(),"20Newsgroups", "20news-bydate-train")
pathTest <- file.path(getwd(),"20Newsgroups", "20news-bydate-test")
pathTrain
#a) For each subject select:
Temp1 <- DirSource(file.path(pathTrain,"sci.space/") )
#load 100 train documents
Doc1.Train <- Corpus(URISource(Temp1$filelist[1:100]),readerControl=list(reader=readPlain))
Temp1 <- DirSource(file.path(pathTest,"sci.space/") )
Doc1.Test <- Corpus(URISource(Temp1$filelist[1:100]),readerControl=list(reader=readPlain))
Temp1 <- DirSource(file.path(pathTrain,"rec.autos/") )
Doc2.Train <- Corpus(URISource(Temp1$filelist[1:100]),readerControl=list(reader=readPlain))
Temp1 <- DirSource(file.path(pathTest,"rec.autos/") )
Doc2.Test <- Corpus(URISource(Temp1$filelist[1:100]),readerControl=list(reader=readPlain))
#tm::inspect(Doc1.Train)
#b) Obtain the merged Corpus (of 400 documents), please keep the order as
doc <- c(Doc1.Train,Doc1.Test,Doc2.Train,Doc2.Test)
corpus <- VCorpus(VectorSource(doc))
#tm::inspect(corpus)
# c) Implement preprocessing (clearly indicate what you have used)
corpus.temp <- tm_map(corpus, removePunctuation) # Remove Punctuation
corpus.temp <- tm_map(corpus.temp, stripWhitespace)
#convert to the lower case
corpus.temp <- tm_map(corpus.temp, content_transformer(tolower))
#remove punctuation
corpus.temp <- tm_map(corpus.temp, removePunctuation)
#remove numbers
corpus.temp <- tm_map(corpus.temp, removeNumbers)
#delete non-content-bearing words using a predefined stop word list.
corpus.temp <- tm_map(corpus.temp,removeWords,stopwords("english"))
# Perform Stemming
corpus.temp <- tm_map(corpus.temp, stemDocument, language = "english")
# d) Create the Document-Term Matrix using the following arguments
dtm <-DocumentTermMatrix(corpus.temp) # Document term matrix
dtmImproved <- DocumentTermMatrix(corpus.temp, control=list(minWordLength = 2, minDocFreq=5))
tm::inspect(dtm)
tm::inspect(dtmImproved)
#e) Split the Document-Term Matrix into
train.doc<-as.matrix(dtmImproved[c(1:100,201:300),])
test.doc<-as.matrix(dtmImproved[c(101:200,301:400),])
#trainMatrix
#f) Use the abbreviations "Sci" and "Rec" as tag factors in your classification.
Tags <- factor(c(rep("Sci",100), rep("Rec",100))) # Tags - Correct answers for the training dataset
Tags
set.seed(0)
#g) Classify text using the kNN() function
prob.test<- knn(train.doc, test.doc, Tags, k = 2, prob=TRUE) # k-number of neighbors considered
# Display Classification Results
#h) Display classification results as a R dataframe and name the columns as:
a <- 1:length(prob.test)
b <- levels(prob.test)[prob.test]
c <- attributes(prob.test)$prob
d <- as.vector(matrix(1,nrow=length(c))) # create a vector with 1 size of Prob
f <- c == d # compare two vectors
result <- data.frame(Doc=a, Predict=b,Prob=c, Correct=f)
result
sum(c)/length(Tags) # Overall probability
#i) What is percentage of correct (TRUE) classifications?
sum(prob.test==Tags)/length(Tags) # % Correct Classification
########################################################################
# Part 4A
# For the newsgroup classification problem in Assignment 3, estimate
# the effectiveness of your classification:
# . Create the confusion matrix
# . Clearly mark the values TP, TN, FP, FN
TP<-sum(prob.test[1:100]==Tags[1:100])
FP<-sum(prob.test[1:100]!=Tags[1:100])
FN<-sum(prob.test[101:200]!=Tags[101:200])
TN<-sum(prob.test[101:200]==Tags[101:200])
table(prob.test,Tags)
# . Calculate Precision
# . Calculate Recall
# . Calculate F-score
precision<-(TP/(TP+FP))*100
recall<-(TP/(TP+FN))*100
fscore<-(2*precision*recall)/(precision+recall)
precision
recall
fscore
doc <- c(Doc1.Train,Doc1.Test,Doc2.Train,Doc2.Test)
corpus <- VCorpus(VectorSource(doc))
#tm::inspect(corpus)
corpus.temp <- tm_map(corpus.temp, stripWhitespace)
#convert to the lower case
#delete non-content-bearing words using a predefined stop word list.
corpus.temp <- tm_map(corpus.temp,removeWords,stopwords("english"))
# Perform Stemming
corpus.temp <- tm_map(corpus.temp, stemDocument, language = "english")
dtm <-DocumentTermMatrix(corpus.temp) # Document term matrix
dtmImproved <- DocumentTermMatrix(corpus.temp, control=list(minWordLength = 2, minDocFreq=5))
tm::inspect(dtm)
tm::inspect(dtmImproved)
train.doc<-as.matrix(dtmImproved[c(1:100,201:300),])
test.doc<-as.matrix(dtmImproved[c(101:200,301:400),])
Tags <- factor(c(rep("Sci",100), rep("Rec",100))) # Tags - Correct answers for the training dataset
Tags
set.seed(0)
prob.test<- knn(train.doc, test.doc, Tags, k = 2, prob=TRUE) # k-number of neighbors considered
a <- 1:length(prob.test)
b <- levels(prob.test)[prob.test]
c <- attributes(prob.test)$prob
d <- as.vector(matrix(1,nrow=length(c))) # create a vector with 1 size of Prob
f <- c == d # compare two vectors
result <- data.frame(Doc=a, Predict=b,Prob=c, Correct=f)
result
sum(c)/length(Tags) # Overall probability
sum(prob.test==Tags)/length(Tags) # % Correct Classification
TP<-sum(prob.test[1:100]==Tags[1:100])
FP<-sum(prob.test[1:100]!=Tags[1:100])
FN<-sum(prob.test[101:200]!=Tags[101:200])
TN<-sum(prob.test[101:200]==Tags[101:200])
table(prob.test,Tags)
precision<-(TP/(TP+FP))*100
recall<-(TP/(TP+FN))*100
fscore<-(2*precision*recall)/(precision+recall)
precision
recall
fscore
#Forecast_kWh_Demand.R wih my moficications
library("RSNNS")
library("jsonlite")
### Pre-Process Data & Call Neural Network
Parse.JSON.Input <- function (inputs)
{
ix <- grep("Relative_Humidity",inputs$historian$TagName); InputData <-data.frame(inputs$historian$Samples[[ix]]$TimeStamp,stringsAsFactors = FALSE);
InputData <-cbind(InputData, as.numeric(inputs$historian$Samples[[ix]]$Value),stringsAsFactors = FALSE)
ix <- grep("Outdoor_Dewpoint",inputs$historian$TagName); InputData <- cbind(InputData, as.numeric(inputs$historian$Samples[[ix]]$Value),stringsAsFactors = FALSE)
ix <- grep("Outdoor_Temperature",inputs$historian$TagName); InputData <- cbind(InputData, as.numeric(inputs$historian$Samples[[ix]]$Value),stringsAsFactors = FALSE)
ix <- grep("BUE_Stud_Electric_Demand_kW",inputs$historian$TagName); InputData <- cbind(InputData, as.numeric(inputs$historian$Samples[[ix]]$Value),stringsAsFactors = FALSE)
ix <- grep("Optimal_Electric_Demand_kW",inputs$historian$TagName); InputData <- cbind(InputData, as.numeric(inputs$historian$Samples[[ix]]$Value),stringsAsFactors = FALSE)
ix <- grep("Outputs.Predicted_Electric_Demand",inputs$parameters$Name); InputData <- cbind(InputData, inputs$parameters$Tag[[ix]],stringsAsFactors = FALSE)
colnames(InputData) <- c("DATE","Relative_Humidity","Outdoor_Dewpoint","Outdoor_Temperature","Electric_Demand_kW","Optimal_Electric_Demand_kW","TagName")
return (InputData) # Returned object
}
Forecast.Electric.Demand <- function (Raw_Data)
{
library("RSNNS")
print("2. Inputs sent to function: Forecast.Electric.Demand()")
# Convert Time Stemps
Num.Data.Points <- dim(Raw_Data)[1]
Time.Stamp <- strptime(Raw_Data$DATE,"%Y-%m-%dT%H:%M:%S")
# Select Training Range
StartTime <- 1 # which(Time.Stamp=="2014-03-01 01:00:00 EST")
TrainRange <- StartTime:Num.Data.Points
print(paste0("Training data start date: ",Time.Stamp[StartTime]))
# Extract Hours field from Time.Stamp
Hours <- as.numeric(format(Time.Stamp,'%H')) # Replace this Line
# Insert your code here
Day.Date <- as.numeric(format(Time.Stamp,'%d'))
# Extract Days field from Time.Stamp
Day.Number <- as.numeric(format(Time.Stamp, '%w'))# Replace this Line
# Insert your code here
Day.Number[Day.Number==0]=7
Day.Name <- weekdays(Time.Stamp)
# Modify Hours & Days
temp <- 12-Hours; temp[temp>=0] = 0
Hours.Modified <- Hours + 2*temp
Day.Number.Modified <- Day.Number
# Insert your code here
Day.Number.Modified[Day.Number<6]=1
Day.Number.Modified[Day.Number==6]=2
print("Extracting Hour_of_Day & Day_of_Week fields from the DATE field Time Stamp ")
# Choose Data to Process
Dependent.Ix <- c(2:4) # Select dependent columns
Dependent.Data <- cbind(Hours.Modified, Day.Number.Modified, Raw_Data[TrainRange,Dependent.Ix]); # X ()
Independent.Ix <- c(5) # Select Independent columns
Independent.Data <- Raw_Data[TrainRange,Independent.Ix]; # Y (Actual Electric Demand )
print("Dependent data tags: "); print(names(Dependent.Data))
print("Independent data tags: "); print(names(Raw_Data[Independent.Ix]))
# Define NuNet Inputs
inputs <- Dependent.Data # Actual Consumption - used for training
targets <- Independent.Data # Expected Consumption (Regression data) used as Tags
Percent.To.Test <- 0.30 # Split the input data into train and test
print("Define NuNet Inputs: "); print(paste0("Percent of input data to test: ", 100*Percent.To.Test, " %"))
# Train NuNet & Get Predictions
print("Train NuNet & Get Predictions, please wait... ");
Predicted.Electric.Demand <- TrainNuNet(inputs,targets,Percent.To.Test)
# Predicted.Electric.Demand <- list(rep(0,Num.Data.Points)) # Populate with zero
print("NuNet Training finished!");
# Actual.Electric.Demand <- Independent.Data
# Output <- list(Predicted.Electric.Demand)
Output <- data.frame("TimeStamp"=Time.Stamp,"Value"=unlist(Predicted.Electric.Demand),"Quality"=3)
return (Output) # Returned object
}
TrainNuNet <- function (inputs,targets,Percent.To.Test)
{
# Normalize the Data
if (is.null(dim(inputs))) # Single Column Input
{
z <- max(inputs, na.rm=TRUE) # find Max in Single Input Column
inputs.scale <- z; targets.scale <- max(targets)
inputs.normalized <- inputs/inputs.scale # Normalize Data
targets.normalized <- targets/targets.scale # Normalize Data
}
else # Multi Colum Input
{
z <- apply(inputs, MARGIN = 2, function(x) max(x, na.rm=TRUE)) # find Max in Each Input Column
inputs.scale <- as.vector(z); targets.scale <- max(targets);
inputs.normalized <- sweep(inputs, 2, inputs.scale, `/`) # Normalize Data
targets.normalized <- targets/targets.scale # Normalize Data
}
# Split the Data into Train and Test
patterns <- splitForTrainingAndTest(inputs.normalized, targets.normalized, ratio = Percent.To.Test)
set.seed(13);
# Train NN to folow Actual
# The use of an Elman network (Elman 1990) for time series regression.
model <- elman(patterns$inputsTrain, patterns$targetsTrain,
size = c(10, 10), learnFuncParams = c(0.1), maxit = 1300,
inputsTest = patterns$inputsTest, targetsTest = patterns$targetsTest,
linOut = FALSE)
# model <- elman(patterns$inputsTrain, patterns$targetsTrain,
# size = c(8, 8), learnFuncParams = c(0.1), maxit = 500,
# inputsTest = patterns$inputsTest, targetsTest = patterns$targetsTest,
# linOut = FALSE)
NN.fitted.Train <- model$fitted.values*targets.scale
NN.fitted.Test <- model$fittedTestValues*targets.scale
Predicted.Electric.Demand <- c(NN.fitted.Train,NN.fitted.Test)
result <- list(Predicted.Electric.Demand)
return (result) # Returned object
}
wrapper <- function(inputJSON.Data){
# # Import data
inputs <- fromJSON(inputJSON.Data, flatten=TRUE)
InputData <- Parse.JSON.Input(inputs) # Turn JSON Input to DataFrame
print("1. Historian Database input tags imported to R Script:")
print(names(InputData))
Output <- Forecast.Electric.Demand(InputData)
temp <- as.character( Output$TimeStamp); Output$TimeStamp <- paste0(sub(" ","T",temp),"Z")
# In Historian Format
z <- list("TagName"=InputData$TagName[1],ErrorCode=0,"DataType"="DoubleFloat" ,"Samples"=Output)
Predicted.Electric.Demand <- toJSON(list(z),pretty=TRUE)
print("3. Predicted Electric Demand from NuNet saved to Historian Database")
return(Predicted.Electric.Demand)
}
# Example: Shiny app that search Wikipedia web pages
# File: server.R
library(shiny)
library(tm)
library(stringi)
library(proxy)
library(wordcloud)
library(ggplot2)
source("WikiSearch.R")
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
# Progress Bar while executing function
withProgress({
setProgress(message = "Mining Wikipedia ...")
result <- SearchWiki(input$select)
})
#result
wf <- data.frame(word=names(result), freq=result)
wf<- head(wf,50)
#freq.fifty <- head(result,50)
#plot(result, labels = input$select, sub = "",main="Wikipedia Search")
#wordcloud(names(freq.fifty), freq.fifty, min.freq=5, colors=brewer.pal(6, "Dark2"))
ggplot(subset(wf, freq>50), aes(x = reorder(word, -freq), y = freq)) +
geom_bar(stat = "identity") +
theme(axis.text.x=element_text(angle=45, hjust=1))
})
})
### --- Example 8: Search Wikipedia web pages. --------
# Save these 3 files separately in the same folder (Related to HW#4)
# Example: Shiny app that search Wikipedia web pages
# File: ui.R
library(shiny)
titles <- c("Web_analytics","Text_mining","Integral", "Calculus",
"Lists_of_integrals", "Derivative","Alternating_series",
"Pablo_Picasso","Vincent_van_Gogh","Lev_Tolstoj","Web_crawler")
# Define UI for application
shinyUI(fluidPage(
# Application title (Panel 1)
titlePanel("Wiki Pages"),
# Widget (Panel 2)
sidebarLayout(
sidebarPanel(h3("Search panel"),
# Where to search
selectInput("select",
label = h5("Choose from the following Wiki Pages on"),
choices = titles,
selected = titles, multiple = TRUE),
# Start Search
submitButton("Results")
),
# Display Panel (Panel 3)
mainPanel(
h1("Display Panel",align = "center"),
plotOutput("distPlot")
)
)
))
# Wikipedia Search
# Mofified by friesco
library(tm)
library(stringi)
library(WikipediR)
# library(proxy)
SearchWiki <- function (titles) {
wiki.URL <- "https://en.wikipedia.org/wiki/"
articles <- lapply(titles,function(i) stri_flatten(readLines(stri_paste(wiki.URL,i)), col = " "))
# articles <- lapply(titles,function(i) page_content("en","wikipedia", page_name = i,as_wikitext=TRUE)$parse$wikitext)
docs <- VCorpus(VectorSource(articles)) # Get Web Pages' Corpus
remove(articles)
# Text analysis - Preprocessing
transform.words <- content_transformer(function(x, from, to) gsub(from, to, x))
temp <- tm_map(docs, transform.words, "<.+?>", " ")
temp <- tm_map(temp, transform.words, "\t", " ")
temp <- tm_map(temp, content_transformer(tolower)) # Conversion to Lowercase
temp <- tm_map(temp, PlainTextDocument)
temp <- tm_map(temp, stripWhitespace)
temp <- tm_map(temp, removeWords, stopwords("english"))
temp <- tm_map(temp, removePunctuation)
temp <- tm_map(temp, stemDocument, language = "english") # Perform Stemming
remove(docs)
# Create Dtm
dtm <- DocumentTermMatrix(temp)
dtm <- removeSparseTerms(dtm, 0.4)
dtm$dimnames$Docs <- titles
docsdissim <- dist(as.matrix(dtm), method = "euclidean") # Distance Measure
#h <- hclust(as.dist(docsdissim), method = "ward.D2") # Group Results
freq <- sort(colSums(as.matrix(dtm)), decreasing=TRUE)
# h <- head(freq, 50)
h <- freq
# max(freq) # Max appearance frequency of a term (84)
# findFreqTerms(dtm,max.Freq,max(freq))
# ord <- order(freq) # Ordering the frequencies (ord contains the indices))
# freq[tail(ord)] # Most frequent terms & their frequency (most frequent term "the" appearing 85 times)
#
# findFreqTerms(dtm, lowfreq=10) # List terms (alphabetically) with frequency higher than 10
}
|
6decbb630008bd9c8744069880c3c3b484b5c2d5 | 4438b9d57caabb783f10b974965328e57e7b371b | /man/input_db_runID.Rd | 02f4eafce9b6a998c912308960899c8ef2cab91e | [] | no_license | UniK-INES/dexR | 77a16689127f4c8fad1f6c866874603ca0d8f9e2 | 4e344b1cdc6aa08196777d5cbc988c3f8e38fe96 | refs/heads/master | 2023-06-06T10:06:11.977871 | 2021-06-30T15:21:44 | 2021-06-30T15:21:44 | 262,249,253 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 396 | rd | input_db_runID.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dexr_input_db.R
\name{input_db_runID}
\alias{input_db_runID}
\title{Generate run ID string of the given database configuration.}
\usage{
input_db_runID(dexpa)
}
\arguments{
\item{dexpa}{}
}
\value{
run ID string
}
\description{
Generate run ID string of the given database configuration.
}
\author{
Sascha Holzhauer
}
|
962154532206500afa529b1c8fd1f11f29a2ee63 | 9e47bdcdaf8ab743c82637964d65e9bf3dfda8b5 | /scripts/2_criar_tabela_candidatos.R | e0d1e089614ef250999fe50c43fe2d94c7cb6a27 | [] | no_license | tatianass/meu-prefeito | 0968219e80b2308977ce6f86907ab02f27cb1881 | d77c8a9e4d58055f43d75316bfc52d1548de717b | refs/heads/master | 2021-01-12T12:42:13.338614 | 2016-11-10T20:04:07 | 2016-11-10T20:04:07 | 69,097,794 | 3 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,571 | r | 2_criar_tabela_candidatos.R | source("imports.R")
source("util.R")
# Informacoes pessoais dos candidatos
informacoes_pessoais_candidatos <- read.csv("../data/2016/consulta_cand_2016_PB.txt", sep=";", header = F, stringsAsFactors = F, encoding = "latin1", col.names = c("Data_geracao","Dora_geracao","Ano_eleicao","Num_turno","Descricao_eleicao","Sigla_uf","Sigla_ue","Descricao_ue","Codigo_cargo","Descricao_cargo","Nome_candidato","Sequencial_candidato", "Numero_candidato_urna","CPF_candidato","Nome_urna_candidato","Cod_situacao_candidatura","Descricao_situacao_candidatura","Numero_partido","Sigla_partido","Nome_partido","Codigo_legenda","Sigla_legenda","Composicao_legenda","Nome_legenda", "Codigo_ocupacao","Descricao_ocupacao","Data_nascimento","Num_titulo_eleitoral_candidato","Idade_data_eleicao","Codigo_sexo","Descricao_sexo","Cod_grau_instrucao","Descricao_grau_instrucao","Codigo_estado_civil","Descricao_estado_civil","Codigo_cor_raca", "Descricao_cor_raca","Codigo_nacionalidade","Descricao_nacionalidade","Sigla_uf_nascimento","Codigo_municipio_nascimento","Nome_municipio_nascimento","Despesa_max_campanha","Cod_situacao_totalizacao_turno","Descricao_situacao_totalizacao_turno","Email"))
informacoes_pessoais_candidatos <- carrega_informacoes_pessoais_candidatos(informacoes_pessoais_candidatos)
# Adiciona cargo, partido, coligação e votação dos candidatos
todos_candidatos <- read.csv("../data/2016/eleicao_todos_candidatos.csv", sep=";", stringsAsFactors = F, encoding = "UTF-8")
todos_candidatos <- carrega_todos_candidatos(todos_candidatos)
candidatos <- informacoes_pessoais_candidatos %>% inner_join(todos_candidatos, by = c("Descricao_ue" = "Localidade", "Numero_candidato_urna" = "Numero_candidato"))
# Adiciona limite de despesas para cada cargo e municipio
limite_despesas_candidatos_pb <- read.csv("../data/2016/limite_gastos_campanha_eleitoral_2016.csv", sep=";", dec=",", stringsAsFactors = F, encoding = "UTF-8")
limite_despesas_candidatos_pb <- carrega_limite_depesas_candidatos_pb(limite_despesas_candidatos_pb)
candidatos <- candidatos %>% inner_join(limite_despesas_candidatos_pb, by = c("Descricao_ue" = "Municipio", "Cargo" = "Cargo"))
# Adiciona gastos para cada candidato
gastos_candidatos_pb <- read.csv("../data/2016/despesas_candidatos_2016_PB.txt", sep=";", encoding = "latin1", dec = ",", stringsAsFactors = F)
gastos_candidatos_pb <- carrega_gastos_candidatos_pb(gastos_candidatos_pb)
candidatos <- gastos_candidatos_pb %>% right_join(candidatos, by = c("CPF.do.candidato" = "CPF_candidato"))
candidatos$Soma_gastos <- with(candidatos, ifelse(is.na(Soma_gastos),0,Soma_gastos))
# Adiciona abstencao
abstencao <- read.csv("../data/2016/comparecimento_abstencao_localidade.csv", sep=";", dec = ",", stringsAsFactors = F, encoding = "UTF-8", header = T) %>%
select(Localidade, Cargo, Comparecimento, Abstenção)
abstencao$Localidade <- iconv(abstencao$Localidade, from="UTF-8", to="ASCII//TRANSLIT")
candidatos <- candidatos %>% inner_join(abstencao, by = c("Descricao_ue" = "Localidade", "Cargo" = "Cargo"))
# Adiciona despesas dos candidatos
eleitorado_apto <- read.csv("../data/2016/eleitorado_2016_mun.csv", sep=";") %>% filter(UF=="PB")
eleitorado_apto$MUNICIPIO <- iconv(eleitorado_apto$MUNICIPIO, from="UTF-8", to="ASCII//TRANSLIT")
candidatos <- candidatos %>% inner_join(eleitorado_apto, by = c("Descricao_ue" = "MUNICIPIO"))
# Adiciona informacoes das cidades
cidades <- read.csv("../data/municipios.csv", sep=";", dec=",", stringsAsFactors = F) %>%
filter(ANO == 2010, UF == 25) %>%
select(Municipio, Esperanca_vida = ESPVIDA, IDHM, IDHM_E, IDHM_L, IDHM_R) %>%
mutate(Municipio=replace(Municipio, Municipio=="SAO DOMINGOS", "SAO DOMINGOS DE POMBAL"))
candidatos <- candidatos %>% inner_join(cidades, by = c("Descricao_ue" = "Municipio"))
write.table(candidatos, "../data/2016/candidatos.csv" ,sep=";", row.names = F, quote = F)
### word cloud
# configura_conjunto_palavras <- function(x){
# gastosCorpus <- Corpus(VectorSource(x)) %>%
# tm_map(PlainTextDocument) %>% tm_map(removePunctuation) %>%
# tm_map(removeWords, stopwords('portuguese')) %>% tm_map(stemDocument, language = "portuguese")
#
# gastosCorpus
# }
#
# configura_conjunto_palavras(gastos_candidatos_pb$Descrição.da.despesa) %>% wordcloud(max.words = 100, random.order = FALSE)
# configura_conjunto_palavras(gastos_vereadores_pb$Descrição.da.despesa) %>% wordcloud(max.words = 100, random.order = FALSE)
# configura_conjunto_palavras(gastos_prefeitos_pb$Descrição.da.despesa) %>% wordcloud(max.words = 100, random.order = FALSE) |
e15421521c4f4af138f02300cfde3d09e6160350 | 4a0d267ab45daf3e675a3e6e8a73f8c6457fb582 | /R/assert-internal.R | 0c55a6be5d867713bd9432449377e0cdf5c3903b | [
"MIT"
] | permissive | chitrita/bcbioSingleCell | 4409799bef87b6ef70776e189a6636d0ba83b146 | 8907332b9193cae538106b2b52a03656fcfbb651 | refs/heads/master | 2020-04-10T22:45:28.143142 | 2018-12-01T18:06:53 | 2018-12-01T18:06:53 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 249 | r | assert-internal.R | .isAggregate <- function(object, stop = FALSE) {
logical <- "aggregate" %in% colnames(object)
if (
identical(logical, FALSE) &&
identical(stop, TRUE)
) {
stop("`aggregate` column is required")
}
logical
}
|
e6188a4e9b3c8762122a9cabcd9f37ed7c611288 | cbe44f0dca20bba077801c4b14cf8c64d5b7d352 | /man/question_1a_003_charts_latitude_longitude_min_temp.Rd | 18f4c3011eaaae54065e0c0ae4259984e1637df2 | [] | no_license | s1888637/weathr | 1ced821f4bec8bf39cb38123960d9b59d3cc80d0 | 3adfd7fd3149ee2b8a2f32577d6ed5695b7450b4 | refs/heads/master | 2020-05-29T19:49:21.974074 | 2019-06-05T19:15:26 | 2019-06-05T19:15:26 | 189,339,729 | 0 | 1 | null | null | null | null | UTF-8 | R | false | true | 428 | rd | question_1a_003_charts_latitude_longitude_min_temp.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/question-1a-003-charts-latitude-longitude.R
\name{question_1a_003_charts_latitude_longitude_min_temp}
\alias{question_1a_003_charts_latitude_longitude_min_temp}
\title{question_1a_003_charts_latitude_longitude_min_temp}
\usage{
question_1a_003_charts_latitude_longitude_min_temp()
}
\description{
question_1a_003_charts_latitude_longitude_min_temp
}
|
58fc67a83d8e8e371ec84c99899b7019ca676a0f | 4b02f42b79947ee0014fb3478fa255d1ee363314 | /bin_crush/gcc4DingY_20121022.R | 3c14b6f113d5dcc0a6ef673358b9cbe442d22594 | [] | no_license | mavishou/project | 0893b82135322570abd3e5b2373e570f717b0318 | 4b8943a40924ca61b90f1f8ca66b7ed3c18975ef | refs/heads/master | 2021-01-22T05:33:34.865770 | 2014-11-14T14:35:24 | 2014-11-14T14:35:24 | 24,197,639 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,448 | r | gcc4DingY_20121022.R |
#get gcc between 2 genes
#from R package rsgcc v1.0.4, edit by Hou Mei
gcc <- function( x, y ) {
if (!is.vector(x))
stop("x must be a vector.")
len = length(x)
if (!is.vector(y) || len != length(y))
stop("x is a vector; y should be a vector of the same length")
#sort x
tmp <- sort.int(x, na.last = NA, decreasing = FALSE, index.return = TRUE)
valuex_x <- tmp$x
valuey_x <- y[tmp$ix] #y sorted by the rank of x
#sort y
tmp <- sort.int(y, na.last = NA, decreasing = FALSE, index.return = TRUE)
valuey_y <- tmp$x
valuex_y <- x[tmp$ix] #x sorted by the rank of y
weight <- t(2*seq(1,len,1) - len - 1)
gccxy <- sum(weight*valuex_y)/sum(weight*valuex_x)
gccyx <- sum(weight*valuey_x)/sum(weight*valuey_y)
#edit by Hou Mei
#return( data.frame(gccxy, gccyx) )
gccs <- c(gccxy,gccyx)
#return the abs max of gccs
return(max(gccs[abs(gccs)== max(abs(gccs))]))
}
#get the GCC between a given gene and the whole genes
#oneGene is the name of a given gene
#exprsMatrix is the exression matrix of selected samples, each row represent a gene, each column represent a sample
getGCCor <- function(oneGene, exprsMatrix){
oneGene_exprs <- exprsMatrix[oneGene,]
gcc_result <- rep(0,nrow(exprsMatrix))
names(gcc_result) <- rownames(exprsMatrix)
for(i in 1:nrow(exprsMatrix)){
gcc_result[i] <- gcc(oneGene_exprs, exprsMatrix[i,])
}
return(gcc_result)
}
|
1743f03f881c06e3c8257b349ac8b5b2b46b37fc | fa6104f6253d9e1b950b4ff5afb2a067ff1fcebe | /R/udfs/raster_percentile_reclassifier.R | 2728cb7e13c287cc338bd9d75082bf750025c122 | [] | no_license | l5d1l5/Hotspots | 513b947091198f27b8233d77489f1307e4e78c6f | 8930ef8cc52a733998dd47a1d510df0412d82615 | refs/heads/master | 2023-08-16T15:05:25.100593 | 2021-10-20T22:03:23 | 2021-10-20T22:03:23 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,131 | r | raster_percentile_reclassifier.R | # RasterAreaPercentiles ----
# Reclassify a raster into area-weighted percentiles
RasterAreaPercentiles <- function(RasterToClassify, WeightRaster, MaskRaster, clipToExtent, CRS.set, ext.set){
# @RasterToClassify: Input raster
# @WeightRaster: Typically representing cell area
# @MaskRaster: Binary raster indicating cells to mask
# @clipToExtent: If == "clip", use MaskRaster
# @CRS.set: Coordinate reference system
# @ext.set: Optional, if wanting to specify the extent of the output raster
PercentileRaster <- raster(RasterToClassify) # Initialize percentile raster
crs(RasterToClassify) <- CRS.set
extent(RasterToClassify) <- ext.set
message(paste0("CRS and extent set to: ", crs(RasterToClassify), " & ",
extent(RasterToClassify), sep = ""))
RasterToClassify[MaskRaster != 1] <- NA
m.df <- raster::stack(RasterToClassify, WeightRaster, MaskRaster) %>%
as.data.frame() %>%
set_colnames(c("Input", "Weight", "Mask"))
m.df <- m.df[complete.cases(m.df$Input),]
if(clipToExtent == "clip"){
m.df <- m.df %>% dplyr::filter(Mask == 1)
}
pb <- txtProgressBar(min = 0, max = 99, style = 3)
for(i in 0:99){
j = 1 - (i*0.01)
k = 0.99 - (i*0.01)
# Upper bound
ub = as.numeric(unname(spatstat::weighted.quantile(m.df$Input,
m.df$Weight,
j,
na.rm = TRUE)))
# Lower bound
lb = as.numeric(unname(spatstat::weighted.quantile(m.df$Input,
m.df$Weight,
k,
na.rm = TRUE)))
PercentileRaster[RasterToClassify <= ub & RasterToClassify > lb] <- j
setTxtProgressBar(pb, i)
}
PercentileRaster[is.na(PercentileRaster)] <- 0
PercentileRaster[is.na(MaskRaster) | MaskRaster != 1] <- NA # mask classified by mask raster
plot(PercentileRaster)
return(PercentileRaster)
} |
270c4a25a38596f8f106571eb9e8635c7758923e | 364d3c7f7b87095baadbbacefb69a0a7c107c87c | /man/set_hparams_glmnet.Rd | 164a6d06c2ec18a2bb9c50d6661c729a0e37472b | [
"MIT",
"CC-BY-4.0"
] | permissive | SchlossLab/mikropml | 32c9d0cd7351d667b2fc7522eabdcfb73e28d699 | 3dcc9bc0c49e0e65714fd9a1e0045a749ada76e8 | refs/heads/main | 2023-06-11T15:23:19.409104 | 2023-04-15T17:02:49 | 2023-04-15T17:02:49 | 226,981,416 | 41 | 12 | NOASSERTION | 2023-08-21T15:44:37 | 2019-12-09T22:37:38 | R | UTF-8 | R | false | true | 456 | rd | set_hparams_glmnet.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/hyperparameters.R
\name{set_hparams_glmnet}
\alias{set_hparams_glmnet}
\title{Set hyperparameters for regression models for use with glmnet}
\usage{
set_hparams_glmnet()
}
\value{
default lambda & alpha values
}
\description{
Alpha is set to \code{0} for ridge (L2). An alpha of \code{1} would make it lasso (L1).
}
\author{
Zena Lapp, {zenalapp@umich.edu}
}
\keyword{internal}
|
1086fb6666135619c3ab5a4cfd98dc6251f692b5 | c5c850791e054f5e4bcc559abf9fb71c22b79e80 | /R/abs_stdapdC.R | 49f7d8114f1ca89a1e93f91d9821536dcb0f7e74 | [] | no_license | cran/generalCorr | 3412664373559d8f03d0b668bb6a5b6bdac40f2b | 6a26d66ddee3b518f34a64d25fdaa5e13a5a45a1 | refs/heads/master | 2023-08-31T09:59:03.135328 | 2023-08-16T16:24:36 | 2023-08-16T18:30:25 | 57,865,966 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 2,208 | r | abs_stdapdC.R | #' Absolute values of gradients (apd's) of kernel regressions of x on y when
#' both x and y are standardized and control variables are present.
#'
#' 1) standardize the data to force mean zero and variance unity, 2) kernel
#' regress x on y and a matrix of control variables,
#' with the option `gradients = TRUE' and finally 3) compute
#' the absolute values of gradients
#'
#' The first argument is assumed to be the dependent variable. If
#' \code{abs_stdapdC(x,y)} is used, you are regressing x on y (not the usual y
#' on x). The regressors can be a matrix with 2 or more columns. The missing values
#' are suitably ignored by the standardization.
#'
#' @param x {vector of data on the dependent variable}
#' @param y {data on the regressors which can be a matrix}
#' @param ctrl {Data matrix on the control variable(s) beyond causal path issues}
#' @importFrom stats sd
#' @return Absolute values of kernel regression gradients are returned after
#' standardizing the data on both sides so that the magnitudes of amorphous
#' partial derivatives (apd's) are comparable between regression of x on y on
#' the one hand and regression of y on x on the other.
## @note %% ~~further notes~~
#' @author Prof. H. D. Vinod, Economics Dept., Fordham University, NY
#' @seealso See \code{\link{abs_stdapd}}.
#'
#' @concept kernel regression gradients
#' @concept apd
#' @examples
#' \dontrun{
#' set.seed(330)
#' x=sample(20:50)
#' y=sample(20:50)
#' z=sample(20:50)
#' abs_stdapdC(x,y,ctrl=z)
#' }
#' @export
abs_stdapdC=
function (x, y, ctrl)
{
stdx = function(x) (x - mean(x, na.rm = TRUE))/sd(x, na.rm = TRUE)
stx = (x - mean(x, na.rm = TRUE))/sd(x, na.rm = TRUE)
p = NCOL(y)
q = NCOL(ctrl)#ctrl is a mtrix of control variables
if (p == 1)
sty = (y - mean(y, na.rm = TRUE))/sd(y, na.rm = TRUE)
if (p > 1)
sty = apply(y, 2, stdx)
if (q == 1)
stz = (ctrl - mean(ctrl, na.rm = TRUE))/sd(ctrl, na.rm = TRUE)
if (q > 1)
stz = apply(ctrl, 2, stdx)
kk1 = kern_ctrl(dep.y = as.vector(stx), reg.x = sty, ctrl=stz, gradients = TRUE)
agrad = abs(kk1$grad[,1])
return(agrad)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.