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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f36d73c9dbe8a8b1892b90ca838aa40d4fe7b658
|
bd0bb262fda22a09140f77b8eb6db5b5b951d895
|
/fig01b.R
|
5ad3d9497f3147ea337a8ae0a4642946968e5c25
|
[] |
no_license
|
erikbsolbu/ecy22
|
470ae9a26be9f5bf70e92475a484e1d95274c9ce
|
871f18869f7538841ab9da4a1f12cc749cdbfaff
|
refs/heads/main
| 2023-04-08T10:37:06.115137
| 2022-03-24T12:03:04
| 2022-03-24T12:03:04
| 456,653,719
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 8,162
|
r
|
fig01b.R
|
# Required packages
library(tidyverse)
# Create variables
var1 <- factor(rep(paste(rep(paste("X_", 1:2, sep = ""),
each = 5),
"(",
rep(paste("t_", 1:5, sep = ""),
2),
")", sep = ""),
each = 10),
levels = paste(rep(paste("X_", 1:2, sep = ""),
each = 5),
"(",
rep(paste("t_", 1:5, sep = ""),
2),
")", sep = ""))
var2 <- factor(rep(paste(rep(paste("X_", 1:2, sep = ""),
each = 5),
"(",
rep(paste("t_", 1:5, sep = ""),
2),
")", sep = ""),
10),
levels = paste(rep(paste("X_", 2:1, sep = ""),
each = 5),
"(",
rep(paste("t_", 5:1, sep = ""),
2),
")", sep = ""))
# Table indicating correlation due to species heterogeneity
tbl_heterogeneity <- tibble(value = c(rep(c(1, NA), each = 5),
rep(c(1, NA), each = 5),
rep(c(1, NA), each = 5),
rep(c(1, NA), each = 5),
rep(c(1, NA), each = 5),
rep(c(NA, 1), each = 5),
rep(c(NA, 1), each = 5),
rep(c(NA, 1), each = 5),
rep(c(NA, 1), each = 5),
rep(c(NA, 1), each = 5)),
var1 = var1,
var2 = var2) %>%
add_column(case = "(e) - Heterogeneity")
p_heterogeneity <- tbl_heterogeneity %>%
ggplot(aes(x = var1, y = var2)) +
geom_tile(aes(fill = value), color = "black") +
scale_fill_gradient(low = "#8dd3c7",
high = "#8dd3c7",
na.value = "#8dd3c700") +
labs(x = "Species i, time t", y = "Species i, time t") +
guides(fill = "none") +
scale_y_discrete(labels = paste(rep(2:1, each = 5), rep(5:1, 2), sep = ",")) +
scale_x_discrete(labels = paste(rep(1:2, each = 5), rep(1:5, 2), sep = ",")) +
theme_bw() +
theme(axis.line = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
plot.margin = margin(t = 1, r = 1, b = 1, l = 1, unit = "pt")) +
facet_wrap(~ case)
# Table indicating correlation due to common environmental noise
tbl_common <- tibble(value = c(rep(c(1, 0.8, 0.6, 0.4, 0.2), 2),
rep(c(0.8, 1, 0.8, 0.6, 0.4), 2),
rep(c(0.6, 0.8, 1, 0.8, 0.6), 2),
rep(c(0.4, 0.6, 0.8, 1, 0.8), 2),
rep(c(0.2, 0.4, 0.6, 0.8, 1), 2),
rep(c(1, 0.8, 0.6, 0.4, 0.2), 2),
rep(c(0.8, 1, 0.8, 0.6, 0.4), 2),
rep(c(0.6, 0.8, 1, 0.8, 0.6), 2),
rep(c(0.4, 0.6, 0.8, 1, 0.8), 2),
rep(c(0.2, 0.4, 0.6, 0.8, 1), 2)),
var1 = var1,
var2 = var2) %>%
add_column(case = "(f) - Common")
p_common <- tbl_common %>%
ggplot(aes(x = var1, y = var2)) +
geom_tile(aes(fill = value), color = "black") +
scale_fill_gradient(low = "#ffffb330",
high = "#ffffb3",
na.value = "#ffffb300") +
labs(x = "Species i, time t", y = "") +
guides(fill = "none") +
scale_x_discrete(labels = paste(rep(1:2, each = 5), rep(1:5, 2), sep = ",")) +
theme_bw() +
theme(axis.line = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.y = element_blank(),
panel.border = element_blank(),
plot.margin = margin(t = 1, r = 1, b = 1, l = 1, unit = "pt")) +
facet_wrap(~ case)
# Table indicating correlation due to species specific environmental noise
tbl_environmental <- tibble(value = c(c(1, 0.8, 0.6, 0.4, 0.2), rep(NA, 5),
c(0.8, 1, 0.8, 0.6, 0.4), rep(NA, 5),
c(0.6, 0.8, 1, 0.8, 0.6), rep(NA, 5),
c(0.4, 0.6, 0.8, 1, 0.8), rep(NA, 5),
c(0.2, 0.4, 0.6, 0.8, 1), rep(NA, 5),
rep(NA, 5), c(1, 0.8, 0.6, 0.4, 0.2),
rep(NA, 5), c(0.8, 1, 0.8, 0.6, 0.4),
rep(NA, 5), c(0.6, 0.8, 1, 0.8, 0.6),
rep(NA, 5), c(0.4, 0.6, 0.8, 1, 0.8),
rep(NA, 5), c(0.2, 0.4, 0.6, 0.8, 1)),
var1 = var1,
var2 = var2) %>%
add_column(case = "(g) - Environmental")
p_species <- tbl_environmental %>%
ggplot(aes(x = var1, y = var2)) +
geom_tile(aes(fill = value), color = "black") +
scale_fill_gradient(low = "#bebada30",
high = "#bebada",
na.value = "#bebada00") +
labs(x = "Species i, time t", y = "") +
guides(fill = "none") +
scale_x_discrete(labels = paste(rep(1:2, each = 5), rep(1:5, 2), sep = ",")) +
theme_bw() +
theme(axis.line = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.y = element_blank(),
panel.border = element_blank(), #) +
plot.margin = margin(t = 1, r = 1, b = 1, l = 1, unit = "pt")) +
facet_wrap(~ case)
# Table indicating correlation due to observation noise
tbl_observation <- tibble(value = c(1, rep(NA, 9),
NA, 1, rep(NA, 8),
NA, NA, 1, rep(NA, 7),
rep(NA, 3), 1, rep(NA, 6),
rep(NA, 4), 1, rep(NA, 5),
rep(NA, 5), 1, rep(NA, 4),
rep(NA, 6), 1, rep(NA, 3),
rep(NA, 7), 1, rep(NA, 2),
rep(NA, 8), 1, rep(NA, 1),
rep(NA, 9), 1),
var1 = var1,
var2 = var2) %>%
add_column(case = "(h) - Observation")
p_observation <- tbl_observation %>%
ggplot(aes(x = var1, y = var2)) +
geom_tile(aes(fill = value), color = "black") +
scale_fill_gradient(low = "#fb8072",
high = "#fb8072",
na.value = "#fb807200") +
labs(x = "Species i, time t", y = "") +
guides(fill = "none") +
scale_x_discrete(labels = paste(rep(1:2, each = 5), rep(1:5, 2), sep = ",")) +
theme_bw() +
theme(axis.line = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.y = element_blank(),
panel.border = element_blank(),
plot.margin = margin(t = 1, r = 1, b = 1, l = 1, unit = "pt")) +
facet_wrap(~ case)
# Clean up
rm(list = c("var1", "var2", "tbl_heterogeneity", "tbl_common", "tbl_environmental", "tbl_observation"))
|
35c07fe6b1e2bc72f1a6861b5a887c0435fcf04f
|
6168dfdfd024f7d5bb03b1faea633f0e0690e093
|
/swc-r/tran.R
|
82ccd957bca0e98975b45c045a6ccef18ccfe1aa
|
[] |
no_license
|
star1327p/IMSM2015
|
01ebddc0b3d495369f5df9f7c801366371e0dbaa
|
9abd35d414fae1c382549843ef068dc8843698fc
|
refs/heads/master
| 2021-10-29T13:20:09.443478
| 2021-10-10T07:55:10
| 2021-10-10T07:55:10
| 39,018,937
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,433
|
r
|
tran.R
|
speeds <- read.table('car-speeds.csv', sep =",", header = TRUE)
speeds_UT <- subset(speeds, State == 'Utah')
moments <- function(vec){
mm <- mean(vec)
ll <- sd(vec)
n <- length(vec)
ret <- data.frame(mean = mm, sd = ll, vec_length = n)
return(ret)
}
tapply(speeds_UT$Speed, speeds_UT$Color, moments)
tapply(speeds_UT$Speed, speeds_UT$Color, mean)
tapply(speeds_UT$Speed, speeds_UT$Color, sd)
moments(speeds_UT$Speed)
ddply(speeds, c('Color', 'State'), function(df){moments(df$Speed)})
ddply(speeds_UT, c('Color'), function(df){moments(df$Speed)})
ddply(speeds, c('Color'), function(df){moments(df$Speed)})
ddply(speeds, .(Color), function(df){moments(df$Speed)})
library(lattice)
summary(speeds)
histogram(~Speed|State*Color, speeds)
# library(latticeExtra)
# useOuterStrips(
# histogram(~Speed|State*Color, speeds)
# )
# useOuterStrips(
# densityplot(~Speed|State*Color, speeds)
# )
#ldply to make a data.frame with 10 draws of rnorm each for mean = 1:10
#then use bwplot to plot results
#this is the end of the means vector and the length
tot <- 10
#starting point of means vector
start <- 1
#creating a vector with 1, 2, 3,...,10
means <- start:tot
#creating a data.frame with the draws
my_data <- ldply(
means, function(x){
data.frame(mean = x, draws = rnorm(tot, mean = x))
}
)
#t_my_data <- t(my_data)
bwplot(~draws|factor(mean), my_data)
bwplot(draws~factor(mean), my_data)
|
eefc734e426a4c126d78dfb616692e20d40b6d6d
|
6fd75a5fff8a0da2c0f5fa95567b14fe77dc58a5
|
/man/chisq_test2.Rd
|
c6acfa180adf46bf117104ba77e6b09004b990d8
|
[] |
no_license
|
zhangmanustc/StatComp18024
|
47a30f2dbf0c5cfcad9f130b2c9e4a1e433d04f7
|
873a7f6ca3dfafec8430e402261802d5dbc22c8d
|
refs/heads/master
| 2020-04-15T20:05:31.419177
| 2019-01-18T12:35:16
| 2019-01-18T12:35:16
| 164,978,725
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 570
|
rd
|
chisq_test2.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/chisq_test2.R
\name{chisq_test2}
\alias{chisq_test2}
\title{Make a faster version of chisq.test()}
\usage{
chisq_test2(x, y)
}
\arguments{
\item{x}{vector x}
\item{y}{vector y}
}
\value{
compute the chi-square test statistic to test the independence of observations in two vectors.
}
\description{
Make a faster version of chisq.test() when the input is two numeric vectors with no missing values.
}
\examples{
\dontrun{
chisq_test2(seq(1, 4,0.5), seq(2, 5,0.5))
}
}
|
9142790d1dfbf89e23cff68e4f7693e9ab0d87e9
|
d7eb7c0c62a7236b3fc25db9a6dd9d289c937775
|
/1-data/scripts/cesm_maps_ttests.R
|
38969a4eada6fd6f4039054274c3f8f6eae3f351
|
[] |
no_license
|
kvcalvin/iesm-45v85
|
f455554127193ded9026ad91f91cc602dfbe2142
|
a69537e8ae96ee3704e3bd8bb019ac6f2ade51cc
|
refs/heads/master
| 2020-05-29T17:17:57.254766
| 2020-03-31T16:46:11
| 2020-03-31T16:46:11
| 189,271,084
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,413
|
r
|
cesm_maps_ttests.R
|
source( "header.R" )
print( "SET PATHS" )
case1_ref_path <- "/pic/projects/iESM/rcp85_results/diagnostics/b.e11.BRCP85C5BPRP.f09_g16.iESM_uncoupled.001_2006-2090"
case1_impacts_path <- "/pic/projects/iESM/rcp85_results/diagnostics/b.e11.BRCP85C5BPRP.f09_g16.iESM_coupled.001_2006-2088"
case2_ref_path <- "/pic/projects/iESM/rcp45_results/"
case2_impacts_path <- "/pic/projects/iESM/rcp45_results/"
plot_dir <- "~/rslts/iESM"
print( "SET VARIABLES & YEARS" )
variables <- c( "TSA" )
years_to_avg_case1 <- seq( 65, 84, by=1 )
years_to_avg_case2 <- seq( 66, 85, by=1 )
print( "LOADING FILES" )
# iESM CASE 1 Reference
case1r_name <- "b.e11.BRCP85C5BPRP.f09_g16.iESM_uncoupled.001"
case1r_plotname <- "Uncoupled85"
case1r_syear <- 2006
case1r_eyear <- 2090
case1r_fn <- paste( case1r_name, "_", case1r_syear, "-", case1r_eyear, "_ANN_ALL.nc", sep="" )
setwd( case1_ref_path )
case1r_climo <- nc_open( case1r_fn, write=FALSE, verbose=FALSE )
# iESM CASE 1 Impacts
case1i_name <- "b.e11.BRCP85C5BPRP.f09_g16.iESM_coupled.001"
case1i_plotname <- "Coupled85"
case1i_syear <- 2006
case1i_eyear <- 2088
case1i_fn <- paste( case1i_name, "_", case1i_syear, "-", case1i_eyear, "_ANN_ALL.nc", sep="" )
setwd( case1_impacts_path )
case1i_climo <- nc_open( case1i_fn, write=FALSE, verbose=FALSE )
# iESM CASE 2 Reference
case2r_name <- "b.e11.BRCP45C5BPRP.f09_g16.iESM_exp2.001"
case2r_plotname <- "Uncoupled45"
case2r_syear <- 2005
case2r_eyear <- 2094
case2r_fn <- paste( case2r_name, "_", case2r_syear, "-", case2r_eyear, "_ANN_ALL.nc", sep="" )
setwd( case2_ref_path )
case2r_climo <- nc_open( case2r_fn, write=FALSE, verbose=FALSE )
# iESM CASE 2 Impacts
case2i_name <- "b.e11.BRCP45C5BPRP.f09_g16.iESM_exp2.003"
case2i_plotname <- "Coupled45"
case2i_syear <- 2005
case2i_eyear <- 2094
case2i_fn <- paste( case2i_name, "_", case2i_syear, "-", case2i_eyear, "_ANN_ALL.nc", sep="" )
setwd( case2_impacts_path )
case2i_climo <- nc_open( case2i_fn, write=FALSE, verbose=FALSE )
print( "PROCESS iESM CASE 1 DATA" )
IESM_DF <- data.frame( SCENARIO = c( "DELETE" ),
VARIABLE = c( "DELETE" ),
X1 = c( 0 ),
X2 = c( 0 ),
X3 = c( 0 ),
value = c( 0 ))
for ( v in variables ){
TEMP <- ncvar_get( case1r_climo, varid=v )
TEMP_DF <- melt( TEMP )
TEMP_DF$SCENARIO <- case1r_plotname
TEMP_DF$VARIABLE <- v
TEMP_DF <- subset( TEMP_DF, X3 %in% years_to_avg_case1 )
IESM_DF <- rbind( IESM_DF, TEMP_DF )
TEMP <- ncvar_get( case1i_climo, varid=v )
TEMP_DF <- melt( TEMP )
TEMP_DF$SCENARIO <- case1i_plotname
TEMP_DF$VARIABLE <- v
TEMP_DF <- subset( TEMP_DF, X3 %in% years_to_avg_case1 )
IESM_DF <- rbind( IESM_DF, TEMP_DF )
TEMP <- ncvar_get( case2r_climo, varid=v )
TEMP_DF <- melt( TEMP )
TEMP_DF$SCENARIO <- case2r_plotname
TEMP_DF$VARIABLE <- v
TEMP_DF <- subset( TEMP_DF, X3 %in% years_to_avg_case2 )
IESM_DF <- rbind( IESM_DF, TEMP_DF )
TEMP <- ncvar_get( case2i_climo, varid=v )
TEMP_DF <- melt( TEMP )
TEMP_DF$SCENARIO <- case2i_plotname
TEMP_DF$VARIABLE <- v
TEMP_DF <- subset( TEMP_DF, X3 %in% years_to_avg_case2 )
IESM_DF <- rbind( IESM_DF, TEMP_DF )
}
print( "PERFORM PAIRED T-TEST, using year as pairing" )
IESM_DF <- subset(IESM_DF, SCENARIO != "DELETE")
IESM_DF.WIDE <- cast( IESM_DF, VARIABLE + X1 + X2 + X3 ~ SCENARIO, val.var=c( "value" ))
max_X1 <- max(IESM_DF.WIDE$X1)
max_X2 <- max(IESM_DF.WIDE$X2)
IESM_TTEST <- subset(IESM_DF.WIDE, X3 == 75)
IESM_TTEST <- IESM_TTEST[ names(IESM_TTEST) %in% c("VARIABLE", "X1", "X2")]
IESM_TTEST$RCP45 <- "NA"
IESM_TTEST$RCP85 <- "NA"
for( i in 1:max_X1 ) {
for( j in 1:max_X2 ) {
TEMP_DF <- subset(IESM_DF.WIDE, X1 == i & X2 == j)
TEMP_DF <- na.omit(TEMP_DF)
if( nrow(TEMP_DF) > 1 ) {
TEMP <- with(TEMP_DF, t.test(Coupled45, Uncoupled45, paired = TRUE))
IESM_TTEST$RCP45[IESM_TTEST$X1 == i & IESM_TTEST$X2 == j] <- as.numeric(TEMP$p.value)
TEMP <- with(TEMP_DF, t.test(Coupled85, Uncoupled85, paired = TRUE))
IESM_TTEST$RCP85[IESM_TTEST$X1 == i & IESM_TTEST$X2 == j] <- as.numeric(TEMP$p.value)
} else {
IESM_TTEST$RCP45[IESM_TTEST$X1 == i & IESM_TTEST$X2 == j] <- -1
IESM_TTEST$RCP85[IESM_TTEST$X1 == i & IESM_TTEST$X2 == j] <- -1
}
}
}
print( "SAVE DATA FOR LATER" )
setwd( plot_dir )
write.csv(IESM_TTEST, "iESM_ttest_20yr.csv")
|
c6831bae20d814cc9cec2181780ba68fc822f1c4
|
89d219d3dfa744543c6ba1c1b3a99e4dcabb1442
|
/R/trimean.R
|
ae69f54c2acbcbccacdcce3d3e7e0679ed9621bc
|
[] |
no_license
|
pteetor/tutils
|
e2eb5d2fba238cbfe37bf3c16b90df9fa76004bb
|
fe9b936d8981f5cb9b275850908ef08adeffef4e
|
refs/heads/master
| 2022-06-17T11:34:30.590173
| 2022-06-14T02:02:15
| 2022-06-14T02:02:15
| 77,761,145
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 386
|
r
|
trimean.R
|
#'
#' Trimean - robust location statistic
#'
#' The trimean is defined as (Q1 + 2*Q2 + Q3) / 4.
#'
#' @param x Vector of numeric values
#' @param na.rm If TRUE, remove NA values from x
#'
#' @return Trimean value
#'
#' @export
#'
trimean = function(x, na.rm=FALSE) {
q = quantile(x, probs=c(0.25, 0.50, 0.75),
na.rm=na.rm, names=FALSE)
(q[1] + 2*q[2] + q[3]) / 4
}
|
575465e3b342d60ba1e476446c981355264e2281
|
c76086b45c23c48b250515e0bb158c6ca84da6e4
|
/tests/testthat.R
|
cff8729e6397a35ddff1a90ad7603f61229a27da
|
[] |
no_license
|
Ironholds/hail
|
7b821830395b1a6cc1971d4acd29f39fa033bd4c
|
ad4d7922edd102ee662d4913362b6e7a14370014
|
refs/heads/master
| 2021-01-10T17:54:59.278987
| 2017-01-04T22:53:26
| 2017-01-04T22:53:26
| 48,045,952
| 2
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 52
|
r
|
testthat.R
|
library(testthat)
library(hail)
test_check("hail")
|
7fae00a1d5f55224ceb11e8b489f09f7066ac1fa
|
5e85f011e52d2c5b51d833100e9e38677d047f6e
|
/Functions/Useful WebBuilder functions.R
|
39788a6ec9103c6904e28b27b8d999debff3dcb2
|
[
"MIT"
] |
permissive
|
Jpomz/honestly-you-eat-this
|
26fce41c4f068ea31a5703999864c05ef878f156
|
fa1fe624d73494769bf402f998a87096fb2e145e
|
refs/heads/master
| 2021-06-16T00:55:20.503870
| 2019-05-21T19:35:03
| 2019-05-21T19:35:03
| 115,657,416
| 1
| 1
| null | 2018-02-07T05:29:39
| 2017-12-28T20:31:48
|
R
|
UTF-8
|
R
| false
| false
| 6,868
|
r
|
Useful WebBuilder functions.R
|
######################################################
# this script was copied exactly from the supplementary material of Gray et al 2015, Food Webs. http://dx.doi.org/10.1016/j.fooweb.2015.09.001.
# if using, please cite the original publication
# J Pomeranz 27 Nov 2018
# original script below this line
#####################################################
# Functions for synthesising food webs from a registry of
# known trophic links
#Gray et al. 2015
.StripWhitespace <- function(v)
{
# Returns v with leading and trailing whitespace removed
return (gsub('^\\s+|\\s+$', '', v, perl=TRUE))
}
.AddRegistryLinks <- function(synthesized, registry, res.col, con.col,
res.method, con.method, reference.cols,
debug)
{
stopifnot(res.col %in% colnames(synthesized))
stopifnot(res.col %in% colnames(registry))
stopifnot(con.col %in% colnames(synthesized))
stopifnot(con.col %in% colnames(registry))
if(any(!reference.cols %in% colnames(registry)))
{
missing <- setdiff(reference.cols, colnames(registry))
stop('Missing reference columns: ', paste(missing, collapse=','))
}
# Match on multiple columns by pasting
# http://www.r-bloggers.com/identifying-records-in-data-frame-a-that-are-not-contained-in-data-frame-b-%E2%80%93-a-comparison/
# Strip whitespace and convert to lowercase
a <- lapply(synthesized[,c(res.col,con.col)], .StripWhitespace)
a <- lapply(a, tolower)
a <- do.call('paste', a)
b <- lapply(registry[,c(res.col,con.col)], .StripWhitespace)
b <- lapply(b, tolower)
b <- do.call('paste', b)
Debug <- function(...) if(debug) cat(...)
Debug('Matching on resource', res.method, 'consumer', con.method, '\n')
# Match where both resource and consumer columns are non-empty and a link
# does not already exist
to.match <- ''!=synthesized[,res.col] & ''!=synthesized[,con.col] &
is.na(synthesized$N.records)
for(row in which(to.match))
{
N <- sum(a[row]==b)
if(N>0)
{
synthesized$res.method[row] <- res.method
synthesized$con.method[row] <- con.method
synthesized$N.records[row] <- N
for(col in reference.cols)
{
synthesized[,col] <- paste(sort(unique(registry[a[row]==b,col])), collapse=',')
}
}
}
return (synthesized)
}
.AllPossible <- function(nodes, exclude.cols=NULL)
{
# A data.frame of all possible links
resource <- consumer <- nodes[,setdiff(colnames(nodes), exclude.cols),drop=FALSE]
colnames(resource) <- paste0('res.', tolower(colnames(resource)))
colnames(resource)['res.node'==colnames(resource)] <- 'resource'
colnames(consumer) <- paste0('con.', tolower(colnames(consumer)))
colnames(consumer)['con.node'==colnames(consumer)] <- 'consumer'
synthesized <- data.frame(resource[rep(1:nrow(resource), each=nrow(resource)),,drop=FALSE],
consumer[rep(1:nrow(resource), times=nrow(resource)),,drop=FALSE])
return (synthesized)
}
.ARWorker <- function(synthesized, registry, methods, reference.cols, debug)
{
# Add links for each level in methods
for(outer in methods)
{
for(inner in methods[1:which(methods==outer)])
{
synthesized <- .AddRegistryLinks(synthesized, registry,
ifelse('exact'==outer, 'resource', paste0('res.', outer)),
ifelse('exact'==inner, 'consumer', paste0('con.', inner)),
outer, inner, reference.cols, debug)
if(inner!=outer)
{
synthesized <- .AddRegistryLinks(synthesized, registry,
ifelse('exact'==inner, 'resource', paste0('res.', inner)),
ifelse('exact'==outer, 'consumer', paste0('con.', outer)),
inner, outer, reference.cols, debug)
}
}
}
synthesized <- droplevels(synthesized[!is.na(synthesized$N.records),])
rownames(synthesized) <- NULL
return (synthesized)
}
WebBuilder <- function(nodes, registry,
methods=c('exact','genus','subfamily','family','order','class'),
reference.cols=c('linkevidence', 'source.id'), debug=FALSE)
{
# nodes - a data.frame containing columns 'node' (character - unique node
# names) and either 'minimum.method' the minumum method for that
# taxon or 'minimum.res.method' and 'minimum.con.method' - the
# minimum methods for that taxon as a resource and a consumer
# respectively. Values in 'minimum.method', 'minimum.res.method' and
# 'minimum.con.method' must be in the 'methods' argument.
# registry - a data.frame of known trophic interactions
# methods - character vector of methods, in order
# reference.cols - names of columns in registry that will be included in the
# returned data.frame
# Checks
stopifnot(0<nrow(nodes))
stopifnot(nrow(nodes)==length(unique(nodes$node)))
stopifnot(all(c('resource','consumer') %in% colnames(registry)))
error.msg <- paste('nodes should contain either "minimum.method" or',
'"minimum.res.method" and "minimum.con.method"')
if('minimum.method' %in% colnames(nodes))
{
if(any(c('minimum.res.method', 'minimum.con.method') %in% colnames(nodes)))
{
stop(error.msg)
}
# Use minimum.method for both ends of the links
nodes$minimum.res.method <- nodes$minimum.con.method <- nodes$minimum.method
}
else
{
if(!all(all(c('minimum.res.method', 'minimum.con.method') %in% colnames(nodes))))
{
stop(error.msg)
}
# Use the provided minimum.res.method and minimum.con.method
}
stopifnot(all(nodes$minimum.res.method %in% methods))
stopifnot(all(nodes$minimum.con.method %in% methods))
synthesized <- .AllPossible(nodes,
c('minimum.res.method','minimum.con.method','minimum.method'))
synthesized[,c('res.method','con.method')] <- ''
synthesized$N.records <- NA
synthesized[,reference.cols] <- ''
links <- .ARWorker(synthesized, registry, methods, reference.cols, debug)
# Set factor levels
# What client has specified
nodes$minimum.res.method <- factor(nodes$minimum.res.method, levels=methods)
nodes$minimum.con.method <- factor(nodes$minimum.con.method, levels=methods)
# What RegistryLinks found
links$res.method <- factor(links$res.method, levels=methods)
links$con.method <- factor(links$con.method, levels=methods)
links <- links[as.integer(links$res.method)<=as.integer(nodes$minimum.res.method)[match(links$resource, nodes$node)] &
as.integer(links$con.method)<=as.integer(nodes$minimum.con.method)[match(links$consumer, nodes$node)],]
return(droplevels(links))
}
|
9a08f39cf9582ead7071624e7e99286d13ef500c
|
689635789d25e30767a562933f39fcba1cebecf1
|
/Alpha Modelling/QuantStrat/trash/algo1.R
|
1a47efea0d5aa0c9a411f90dff5195328616e0b7
|
[] |
no_license
|
Bakeforfun/Quant
|
3bd41e6080d6e2eb5e70654432c4f2d9ebb5596c
|
f2874c66bfe18d7ec2e6f2701796fb59ff1a0ac8
|
refs/heads/master
| 2021-01-10T18:23:23.304878
| 2015-08-05T12:26:30
| 2015-08-05T12:26:30
| 40,109,179
| 5
| 0
| null | 2015-08-05T12:12:09
| 2015-08-03T06:43:12
|
R
|
UTF-8
|
R
| false
| false
| 269
|
r
|
algo1.R
|
# https://quantstrattrader.wordpress.com/2014/11/02/its-amazing-how-well-dumb-things-get-marketed/
# It's Amazing How Well Dumb Things [Get Marketed]
# Posted on November 2, 2014 by Ilya Kipnis
# Posted in Asset Allocation, ETFs, Portfolio Management, R, SeekingAlpha
|
62df83b4a53de8121cd69de05c19475fc5f1516b
|
f41df8c9eed5eaae611f9df1690d822b1c5798b0
|
/tests/testthat.R
|
c7ff8162829d25ab13ff4e3e425039879ac03d29
|
[
"CC0-1.0"
] |
permissive
|
jakoever/histmaps
|
a0870aac42156bed8934b840029d63a0afa18cec
|
b414574c7daf6a42c8706ee58ad13ac3a7612a93
|
refs/heads/master
| 2022-01-17T05:37:26.780466
| 2018-10-19T08:30:19
| 2018-10-19T08:30:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 60
|
r
|
testthat.R
|
library(testthat)
library(histmaps)
test_check("histmaps")
|
550164f84fd704e23fe39bf532e14a4239107ece
|
59584c1a407817efec7315d47af9c02a89e7fff4
|
/plot6.R
|
2d39ee4427b5f8a18845ff264f8d12cd3983a9de
|
[] |
no_license
|
cmukhtmu/Course4Week4
|
5f20c475cbadf0f297171f9d71524c40c728f707
|
b4fbad4c376009d45fcb51e9aa2cc053d793b8f2
|
refs/heads/master
| 2020-04-24T20:17:02.022867
| 2019-02-23T16:55:53
| 2019-02-23T16:55:53
| 172,238,375
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,584
|
r
|
plot6.R
|
library(data.table)
library(ggplot2)
library(gridExtra)
library(ggpubr)
plot6 <- function()
{
# downloading the zip file
if(!file.exists("./exdata_data_NEI_data.zip"))
{
print("Downloading zip file, please wait...")
download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2FNEI_data.zip", "./exdata_data_NEI_data.zip")
print("Zip file downloaded successfully!")
}
# extracting the zip file
if(!file.exists("./summarySCC_PM25.rds"))
{
print("Extracting zip file, please wait...")
unzip("./exdata_data_NEI_data.zip")
print("Zip file extracted successfully!")
}
if(file.exists("./summarySCC_PM25.rds") & file.exists("./Source_Classification_Code.rds"))
{
# reading the rds file in a data frame
print("Reading data from RDS files, please wait...")
NEI = readRDS("summarySCC_PM25.rds")
Classification_Code = readRDS("Source_Classification_Code.rds")
print("RDS files read successfully!")
# writing data frame into data table
print("Converting data frames into data tables for operations...")
DT = as.data.table(NEI)
Codes = as.data.table(Classification_Code)
print("Converted successfully!")
# getting the sum of emissions by year from motor vehicle sources changed in Baltimore City and LA
print("Calculating emissions sum by year from coal combustion-related sources ...")
vehicleCodes = Codes[tolower(Short.Name) %like% "vehicle", "SCC"]
baltimoreVehicleList = DT[fips=="24510" & SCC %in% vehicleCodes$SCC, list(total = sum(Emissions)), by=year]
laVehicleList = DT[fips=="06037" & SCC %in% vehicleCodes$SCC, list(total = sum(Emissions)), by=year]
print("Calculations completed.")
# plotting with year on X-axis and total emissions on Y-axis
print("Drawing plot...")
p1 = ggplot(baltimoreVehicleList, aes(year, total)) +
geom_point() +
ggtitle("Motor Vehicles in Baltimore") +
geom_smooth()
p2 = ggplot(laVehicleList, aes(year, total)) +
geom_point() +
ggtitle("Motor Vehicles in LA") +
geom_smooth()
ggarrange(p1, p2)
ggsave("plot6.png", width = 5, height = 5)
print("Plot 6 created successfully: plot6.png")
print("*** E N D O F P R O G R A M ***")
}
}
|
edaf0e69e0b195d45049f37d658f5210a9c89cee
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/BLCOP/examples/mvdistribution-class.Rd.R
|
2c28f303cd292fbd64bc33612f86e282e143d779
|
[] |
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
| 193
|
r
|
mvdistribution-class.Rd.R
|
library(BLCOP)
### Name: mvdistribution-class
### Title: Class "mvdistribution"
### Aliases: mvdistribution-class
### Keywords: classes
### ** Examples
showClass("mvdistribution")
|
95837032982f87a58b5bb20773514d638d72bab7
|
a4021a064ad356d5b261ae116eec8d96e74eefb9
|
/tests/testthat/test-iucn_getname.R
|
b1bc3a079f6ae06149539b33e295545ee7055cb9
|
[
"CC0-1.0"
] |
permissive
|
dlebauer/taxize_
|
dc6e809e2d3ba00a52b140310b5d0f416f24b9fd
|
9e831c964f40910dccc49e629922d240b987d033
|
refs/heads/master
| 2020-12-24T23:28:49.722694
| 2014-04-01T18:22:17
| 2014-04-01T18:22:17
| 9,173,897
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 387
|
r
|
test-iucn_getname.R
|
context("iucn_getname")
temp <- iucn_getname(name = "Cyanistes caeruleus", verbose=FALSE)
test_that("iucn_summary returns the correct value", {
expect_that(temp, equals("Parus caeruleus"))
})
test_that("iucn_getname returns the correct class", {
expect_that(temp, is_a("character"))
})
test_that("iucn_getname gets the right dimensions", {
expect_that(length(temp), equals(1))
})
|
22e2c82798538b508e41f9965e7abdfe0f31d6a4
|
9975d797c0cb2d44ffad2d7cbeab31159b56855f
|
/tmp/realignBwaParser.R
|
19c120b848189f9c36fee20b4dc270cdb0327dbf
|
[] |
no_license
|
msubirana/DNAseqPipeline
|
16654870ba0a0797f9ca82fdf63613c34af4ceef
|
1a102eec826507e3a5b520519ab267f4243f9307
|
refs/heads/main
| 2023-09-03T05:29:22.782578
| 2021-11-15T15:56:46
| 2021-11-15T15:56:46
| 335,334,218
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 423
|
r
|
realignBwaParser.R
|
#load package
devtools::load_all('/gpfs42/robbyfs/scratch/lab_lpasquali/msubirana/marc/repos/DNAseqPipeline')
#parse arguments
args <- base::commandArgs(trailingOnly = TRUE)
#define variables
bam <- args[1]
ref <- args[2]
out_dir <- args[3]
threads <- parallel::detectCores()
#realign BAMs using DNAseqPipeline::realignBwa
realignBwa(bam=bam,
ref=ref,
out_dir=out_dir,
threads=threads)
|
a81115269a546fbf308215a43b3378fba0ef5e3e
|
968617612e55205cb56fef91c826d59e46acd23f
|
/Data Science/Coursera/Data Science/Coursework/Assignment1/corr.R
|
6c95f0373097b5190184f1bbff3eb46013e212a9
|
[] |
no_license
|
B4PJS/Assignment1
|
b1e59a7cabb4a82def6eaf224dfce5031bfaf62f
|
2a48539e44e112baa4fc46cc0833505a637a1356
|
refs/heads/master
| 2016-09-01T08:38:58.944850
| 2016-02-08T21:04:49
| 2016-02-08T21:04:49
| 51,327,136
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 376
|
r
|
corr.R
|
corr <- function(directory,threshold = 0){
pols <- data.frame()
cors <- vector()
for(i in 1:332){
wkfile <- paste("./",directory,"/",sprintf("%03i",i),".csv",sep = "")
x<- read.csv(wkfile)
y<-x[!is.na(x[,2])&!is.na(x[,3]),]
if(length(y$sulfate)>threshold){
retval <- cor(x = y$sulfate, y = y$nitrate)
cors <- c(cors,retval)
}
}
cors
}
|
a556793f18df131ed19017c6098c675790d00379
|
331234b7eabbe4daf51ee8143c6dcbc768da0595
|
/King et al. - 2016 - Placoderm R functions/geoplot.epoch.rates.R
|
32f80422033f96f3b011092bc53e1e6517ca0a87
|
[] |
no_license
|
IanGBrennan/Convenient_Scripts
|
6e3959ad69e594b21a5b4b2ca3dd6b30d63170be
|
71f0e64af8c08754e9e3d85fe3fb4770a12ec2d4
|
refs/heads/master
| 2021-05-12T03:57:32.339140
| 2020-01-30T01:58:19
| 2020-01-30T01:58:19
| 117,630,023
| 2
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 816
|
r
|
geoplot.epoch.rates.R
|
geoplot.epoch.rates <- function(rate.sample, epochs, line.col="black", plot.mean=T, mean.col="red", plot.bounds=T, ...){
data.frame(binmin=epochs[2:length(epochs)], binmax=epochs[1:((length(epochs))-1)]) -> epochbounds
apply(data.frame(binmin=epochs[2:length(epochs)], binmax=epochs[1:length(epochs)-1]), 1, mean) -> midages
geoscalePlot(ages=(midages), data=rate.sample[1,], data.lim=c(min(rate.sample), max(rate.sample)), type="n", label="rate", ...)
if(plot.bounds == TRUE)
for(i in 1:length(midages)){
abline(v=epochbounds[1:length(midages),1][i], lty=3)
}
for(i in 1:nrow(rate.sample)){
lines(midages[1:length(midages)], rate.sample[i,1:length(midages)], col=line.col, lwd=0.05)
}
if(plot.mean == TRUE)
lines(midages[1:length(midages)], apply(rate.sample, 2, mean), col=mean.col, lwd=3)
}
|
779ce97c9ec40621223cda8575d3d001d16b70f5
|
c76918157a67d76509c46650e42eeef2714c455b
|
/R/profPlot.R
|
17088bf8eec050844504904f085298f2bfa1184f
|
[] |
no_license
|
butterflyology/ordiBreadth
|
55b8817ae0e4c8db365f7c6930d92c5b37990548
|
41d3a543b6c5eaae3f909cf66ed10a02e32032f2
|
refs/heads/master
| 2021-01-10T12:58:18.289553
| 2016-04-28T03:17:24
| 2016-04-28T03:17:24
| 53,803,191
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 547
|
r
|
profPlot.R
|
profPlot <- function(specialization, id, col = c("black", "red")){
#specialization output from ordi.breadthvX
cols <- rep(col[1], length(specialization$distances[[id]]))
cols[which(specialization$group.vectors[id, ] == TRUE)] <- col[2]
specdist <- specialization$distances[[id]]#[which(specialization$group.vectors[id, ] == "YES")]
cols <- cols[order(specdist)]
specdisto <- specdist[order(specdist)]
plot(1:length(cols), specdisto, col = cols, pch = 19, xlab = "", ylab = "distance", las = 1, main = specialization$species[id])
}
|
77a0010d72807494425c6616ec32e1bcad4c17d3
|
7e7ba3eea4e4cfce0f5de796ac8b14cf457258bd
|
/plot1.R
|
fba6fc1ffd02bfb4a31f589e51862c4b7a78788e
|
[] |
no_license
|
Keervar/ExData_Plotting1
|
cf1856fac1055019ca9b92b9564f5ccd82521059
|
0e111c003f11ce7397ca35523b71001e9465534b
|
refs/heads/master
| 2021-01-01T05:57:02.549536
| 2017-07-16T16:06:53
| 2017-07-16T16:06:53
| 97,316,352
| 0
| 0
| null | 2017-07-15T13:04:00
| 2017-07-15T13:04:00
| null |
UTF-8
|
R
| false
| false
| 420
|
r
|
plot1.R
|
df <- read.table("household_power_consumption.txt", na.strings = "?", header = TRUE, sep = ";")
df$Date <- as.Date(df$Date , format ="%d/%m/%Y")
df1 <- subset(df, df$Date == "2007-02-01"| df$Date=="2007-02-02")
hist(df1$Global_active_power,col = "red", xlab = "Global Active Power (kilowatts)", ylab = "Frequency",
main = "Global Active Power")
dev.copy(png, file = "plot1.png", height = 480, width = 480)
dev.off()
|
64891f85b8b9a1e8fee6e389c83aa833c92101e3
|
2882750a43ae5fa188ec0805953831010a205b1b
|
/R/bisexual_flag.R
|
e76b76e2a74125fe6d451d6e12e30d8119ae15a6
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
Shornone/rosemary
|
ab0a0039006e7c3d82a7eea639d21243c3572216
|
807386719d366dc98ab3a0dc76e4c43a3c6b9650
|
refs/heads/master
| 2020-12-01T12:11:17.149352
| 2020-03-31T13:02:11
| 2020-03-31T13:02:11
| 230,621,467
| 0
| 0
|
CC-BY-4.0
| 2020-03-31T13:02:12
| 2019-12-28T14:34:26
| null |
UTF-8
|
R
| false
| false
| 857
|
r
|
bisexual_flag.R
|
# URL: https://www.flickr.com/photos/stringrbelle/49258653886
#' @rdname rosemary
#' @export
bisexual_flag <- function(dir = NULL, ...) {
dir <- check_dir(dir)
file <- file.path(dir, "bisexual_flag.png")
nrow <- 100
ncol <- 150
jasmines::use_seed(43) %>%
jasmines::scene_rows(n = nrow, grain = ncol) %>%
dplyr::mutate(
x = x * 24,
y = (y * 16) + 4,
id = 1:(nrow*ncol)
) %>%
jasmines::unfold_tempest(
iterations = 50,
scale = .005
) %>%
dplyr::mutate(order = id) %>%
jasmines::style_ribbon(
alpha = c(.4, .01),
size = 1,
palette = jasmines::palette_manual(
"#0038a8", "#0038a8", "#9b4f96", "#d60270", "#d60270"
),
background = "white"
) %>%
jasmines::export_image(file)
cat("image written to:", file, "\n")
return(invisible(NULL))
}
|
bc0375f21712e9a49b354e55b710c22ee2f92997
|
a3ac16582493f7eb5011c5eab0093c4b5ec2a2f1
|
/Paper/JournalManuscript/subscripts/sanity-checks-figs.R
|
3b4f3dfae220d9d2a2bbe83e564e0cc8488e25d0
|
[] |
no_license
|
marisacasillas/NorthAmericanChildren-ADSvsCDS
|
ba38e98fc789589817e82fd0f5011270385932ab
|
a2a155a81f5c716923857d3d9584bbe193d54781
|
refs/heads/master
| 2018-09-20T07:09:46.461428
| 2018-07-10T22:11:14
| 2018-07-10T22:11:14
| 111,093,867
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 25,885
|
r
|
sanity-checks-figs.R
|
################################################################################
# BLOCK DUR SUMMARIES PRIOR TO EXCLUSIONS ####
blk.dur.plot <- ggplot(blockdata, aes(x=(blk_dur))) +
geom_histogram(binwidth = 0.5) +
xlab("block duration (min)") +
geom_vline(xintercept = (mean(blockdata$blk_dur) +
OL.thresh*(sd(blockdata$blk_dur))), color="red")
ggsave(plot = blk.dur.plot,
filename = "blockdurs-withoutliers.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
################################################################################
# TAG PREVALENCE WITH AGE ####
nrec.age <- IDS_demo_update %>%
group_by(AgeMonths) %>%
summarise(n_age = n())
all.tags <- xdscopy %>%
group_by(lena_id) %>%
summarise(tot_dur = sum(utt_dur)/60000,
n = n())
top.10.tags <- all.tags %>%
arrange(-tot_dur) %>%
slice(1:10) %>%
dplyr::select(lena_id)
xdscopy.s <- xdscopy %>%
semi_join(top.10.tags)
all.tags.age <- xdscopy %>%
group_by(AgeMonths, lena_id) %>%
summarise(tot_dur = sum(utt_dur)/60000,
n = n()) %>%
left_join(nrec.age) %>%
mutate(tot_dur_n = tot_dur/n_age,
n_n = n/n_age) %>%
arrange(tot_dur, AgeMonths)
all.tags.ordered.dur <- all.tags %>%
arrange(tot_dur)
all.tags.age.plot.dur <- ggplot(
all.tags.age, aes(x = AgeMonths, y = tot_dur_n, color = lena_id)) +
ylab("Avg. total duration (min)") + xlab("Child age (mo)") +
geom_point(size = 3) +
geom_smooth(size = 3, method = "lm", se = F) +
scale_x_continuous(limits=c(3,21),
breaks=seq(3,21,3)) +
basic.theme +
theme(axis.text.x =
element_text(size=26, angle=0, hjust=0.5))
ggsave(plot = all.tags.age.plot.dur,
filename = "tags-with-age_ALL_dur.png",
path = support.plot.path,
width = 30,
height = 20,
units = "cm",dpi = 72,
bg = "transparent"
)
all.tags.age.plot.n <- ggplot(
all.tags.age, aes(x = AgeMonths, y = n_n, color = lena_id)) +
ylab("Avg. # of clips") + xlab("Child age (mo)") +
geom_point(size = 3) +
geom_smooth(size = 3, method = "lm", se = F) +
scale_x_continuous(limits=c(3,21),
breaks=seq(3,21,3)) +
basic.theme +
theme(axis.text.x =
element_text(size=26, angle=0, hjust=0.5))
ggsave(plot = all.tags.age.plot.n,
filename = "tags-with-age_ALL_n.png",
path = support.plot.path,
width = 30,
height = 20,
units = "cm",dpi = 72,
bg = "transparent"
)
top.tags.age <- xdscopy.s %>%
group_by(AgeMonths, lena_id) %>%
summarise(tot_dur = sum(utt_dur)/60000,
n = n()) %>%
left_join(nrec.age) %>%
mutate(tot_dur_n = tot_dur/n_age,
n_n = n/n_age)
all.tags.age.plot.dur <- ggplot(
top.tags.age, aes(x = AgeMonths, y = tot_dur_n, color = lena_id)) +
ylab("Avg. total duration (min)") + xlab("Child age (mo)") +
geom_point(size = 3) +
geom_smooth(size = 3, method = "lm", se = F) +
scale_x_continuous(limits=c(3,21),
breaks=seq(3,21,3)) +
basic.theme +
theme(axis.text.x =
element_text(size=26, angle=0, hjust=0.5))
ggsave(plot = all.tags.age.plot.dur,
filename = "tags-with-age_TOP10_dur.png",
path = support.plot.path,
width = 30,
height = 20,
units = "cm",dpi = 72,
bg = "transparent"
)
all.tags.age.plot.n <- ggplot(
top.tags.age, aes(x = AgeMonths, y = n_n, color = lena_id)) +
ylab("Avg. # of clips") + xlab("Child age (mo)") +
geom_point(size = 3) +
geom_smooth(size = 3, method = "lm", se = F) +
scale_x_continuous(limits=c(3,21),
breaks=seq(3,21,3)) +
basic.theme +
theme(axis.text.x =
element_text(size=26, angle=0, hjust=0.5))
ggsave(plot = all.tags.age.plot.n,
filename = "tags-with-age_TOP10_n.png",
path = support.plot.path,
width = 30,
height = 20,
units = "cm",dpi = 72,
bg = "transparent"
)
################################################################################
# ADS AND CDS MinPH DISTRIBUTIONS ####
ads.minph.plot <- ggplot(adsratedata, aes(x=ads.minph)) +
geom_histogram(binwidth = 0.5)
ggsave(plot = ads.minph.plot,
filename = "ads-minutesperhour.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
cds.minph.plot <- ggplot(cdsratedata, aes(x=cds.minph)) +
geom_histogram(binwidth = 0.5)
ggsave(plot = cds.minph.plot,
filename = "cds-minutesperhour.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
################################################################################
# Proportion CDS ####
prp.cds.plot <- ggplot(propCDS, aes(x=prp.cds)) +
geom_histogram(binwidth = 0.01)
ggsave(plot = prp.cds.plot,
filename = "cds-proportion.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
################################################################################
# # CDS utterance length ####
# utt_dur.sec.plot <- ggplot(CDSutts, aes(x=mutt_len)) +
# geom_histogram(binwidth = 0.1)
# ggsave(plot = utt_dur.sec.plot,
# filename = "cds-uttlensec.png",
# path = support.plot.path,
# width = 20,
# height = 10,
# units = "cm",dpi = 72,
# bg = "transparent"
# )
################################################################################
# MODEL RESIDUALS ####
# ADS minutes per hour ----
# Model 1: one datapoint per child ####
ads.mph.best.resid <- residuals(ads.mph.best)
ads.mph.resid.plot <- qqplot.data(ads.mph.best.resid)
ads.mph.best.int.resids <- data.frame(resid = ads.mph.best.resid)
ads.mph.resid.dist.plot <- ggplot(ads.mph.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = ads.mph.resid.plot,
filename = "ads-minutesperhour-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = ads.mph.resid.dist.plot,
filename = "ads-minutesperhour-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# Model 2: two datapoints per child with exclusions ####
if (models == "logged/") {
ads.agd.mph.match.resid <- residuals(ads.agd.s.mph.match)
ads.agd.mph.match.resid.plot <- qqplot.data(ads.agd.mph.match.resid)
ads.agd.mph.match.int.resids <- data.frame(resid = ads.agd.mph.match.resid)
ads.agd.mph.match.resid.dist.plot <- ggplot(ads.agd.mph.match.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = ads.agd.mph.match.resid.plot,
filename = "ads-minutesperhour-agd-modelresids-MATCHED.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = ads.agd.mph.match.resid.dist.plot,
filename = "ads-minutesperhour-agd-modelresiddist-MATCHED.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
}
ads.agd.mph.best.resid <- residuals(ads.agd.s.mph.best)
ads.agd.mph.resid.plot <- qqplot.data(ads.agd.mph.best.resid)
ads.agd.mph.best.int.resids <- data.frame(resid = ads.agd.mph.best.resid)
ads.agd.mph.resid.dist.plot <- ggplot(ads.agd.mph.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = ads.agd.mph.resid.plot,
filename = "ads-minutesperhour-agd-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = ads.agd.mph.resid.dist.plot,
filename = "ads-minutesperhour-agd-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# Model 3: Female ADS MinPH ####
fad.mph.best.resid <- residuals(fad.mph.best)
fad.mph.resid.plot <- qqplot.data(fad.mph.best.resid)
fad.mph.best.int.resids <- data.frame(resid = fad.mph.best.resid)
fad.mph.resid.dist.plot <- ggplot(fad.mph.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = fad.mph.resid.plot,
filename = "ads-minutesperhour-FEM-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = fad.mph.resid.dist.plot,
filename = "ads-minutesperhour-FEM-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# Model 4: Male ADS MinPH ####
mad.mph.best.resid <- residuals(mad.mph.best)
mad.mph.resid.plot <- qqplot.data(mad.mph.best.resid)
mad.mph.best.int.resids <- data.frame(resid = mad.mph.best.resid)
mad.mph.resid.dist.plot <- ggplot(mad.mph.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = mad.mph.resid.plot,
filename = "ads-minutesperhour-MAL-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = mad.mph.resid.dist.plot,
filename = "ads-minutesperhour-MAL-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# CDS minutes per hour ----
# Model 1: one datapoint per child ####
cds.mph.best.resid <- residuals(cds.mph.best)
cds.mph.resid.plot <- qqplot.data(cds.mph.best.resid)
cds.mph.best.int.resids <- data.frame(resid = cds.mph.best.resid)
cds.mph.resid.dist.plot <- ggplot(cds.mph.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = cds.mph.resid.plot,
filename = "cds-minutesperhour-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = cds.mph.resid.dist.plot,
filename = "cds-minutesperhour-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# Model 2: two datapoints per child with exclusions ####
cds.agd.mph.best.resid <- residuals(cds.agd.s.mph.best)
cds.agd.mph.resid.plot <- qqplot.data(cds.agd.mph.best.resid)
cds.agd.mph.best.int.resids <- data.frame(resid = cds.agd.mph.best.resid)
cds.agd.mph.resid.dist.plot <- ggplot(cds.agd.mph.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = cds.agd.mph.resid.plot,
filename = "cds-minutesperhour-agd-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = cds.agd.mph.resid.dist.plot,
filename = "cds-minutesperhour-agd-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# Model 3: Female CDS MinPH ####
fcd.mph.best.resid <- residuals(fcd.mph.best)
fcd.mph.resid.plot <- qqplot.data(fcd.mph.best.resid)
fcd.mph.best.int.resids <- data.frame(resid = fcd.mph.best.resid)
fcd.mph.resid.dist.plot <- ggplot(fcd.mph.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = fad.mph.resid.plot,
filename = "cds-minutesperhour-FEM-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = fad.mph.resid.dist.plot,
filename = "cds-minutesperhour-FEM-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# Model 4: Male CDS MinPH ####
mcd.mph.best.resid <- residuals(mcd.mph.best)
mcd.mph.resid.plot <- qqplot.data(mcd.mph.best.resid)
mcd.mph.best.int.resids <- data.frame(resid = mcd.mph.best.resid)
mcd.mph.resid.dist.plot <- ggplot(mcd.mph.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = mcd.mph.resid.plot,
filename = "cds-minutesperhour-MAL-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = mcd.mph.resid.dist.plot,
filename = "cds-minutesperhour-MAL-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# CDS proportion ----
# Model 1: one datapoint per child ####
cds.prp.best.resid <- residuals(cds.prp.best)
cds.prp.resid.plot <- qqplot.data(cds.prp.best.resid)
cds.prp.best.int.resids <- data.frame(resid = cds.prp.best.resid)
cds.prp.resid.dist.plot <- ggplot(cds.prp.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.05) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = cds.prp.resid.plot,
filename = "cds-proportion-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = cds.prp.resid.dist.plot,
filename = "cds-proportion-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# Model 2: two datapoints per child with exclusions ####
cds.prp.agd.best.resid <- residuals(cds.prp.agd.best)
cds.prp.agd.resid.plot <- qqplot.data(cds.prp.agd.best.resid)
cds.prp.agd.best.int.resids <- data.frame(resid = cds.prp.agd.best.resid)
cds.prp.agd.resid.dist.plot <- ggplot(cds.prp.agd.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = cds.prp.agd.resid.plot,
filename = "cds-proportion-agd-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = cds.prp.agd.resid.dist.plot,
filename = "cds-proportion-agd-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# Model 3: Female CDS proportion ####
fcd.prp.best.resid <- residuals(fcd.prp.best)
fcd.prp.resid.plot <- qqplot.data(fcd.prp.best.resid)
fcd.prp.best.int.resids <- data.frame(resid = fcd.prp.best.resid)
fcd.prp.resid.dist.plot <- ggplot(fcd.prp.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = fcd.prp.resid.plot,
filename = "cds-proportion-FEM-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = fcd.prp.resid.dist.plot,
filename = "cds-proportion-FEM-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# Model 4: Male CDS proportion ####
mcd.prp.best.resid <- residuals(mcd.prp.best)
mcd.prp.resid.plot <- qqplot.data(mcd.prp.best.resid)
mcd.prp.best.int.resids <- data.frame(resid = mcd.prp.best.resid)
mcd.prp.resid.dist.plot <- ggplot(mcd.prp.best.int.resids, aes(x=resid)) +
geom_histogram(aes(y=..density..),
fill="white", color="black",
binwidth = 0.5) +
geom_density(color="firebrick3", lwd=2)
ggsave(plot = mcd.prp.resid.plot,
filename = "cds-proportion-MAL-modelresids.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
ggsave(plot = mcd.prp.resid.dist.plot,
filename = "cds-proportion-MAL-modelresiddist.png",
path = support.plot.path,
width = 20,
height = 10,
units = "cm",dpi = 72,
bg = "transparent"
)
# # CDS utterance length ----
# # Model 1: one datapoint per child ####
# cds.dur.best.best.resid <- residuals(cds.dur.best)
# cds.dur.best.resid.plot <- qqplot.data(cds.dur.best.best.resid)
# cds.dur.best.best.int.resids <- data.frame(resid = cds.dur.best.best.resid)
# cds.dur.best.resid.dist.plot <- ggplot(cds.dur.best.best.int.resids,
# aes(x=resid)) +
# geom_histogram(aes(y=..density..),
# fill="white",
# color="black",
# binwidth = 0.05) +
# geom_density(color="firebrick3", lwd=2)
# ggsave(plot = cds.dur.best.resid.plot,
# filename = "cds-uttdursec-modelresids.png",
# path = support.plot.path,
# width = 20,
# height = 10,
# units = "cm",dpi = 72,
# bg = "transparent"
# )
# ggsave(plot = cds.dur.best.resid.dist.plot,
# filename = "cds-uttdursec-modelresiddist.png",
# path = support.plot.path,
# width = 20,
# height = 10,
# units = "cm",dpi = 72,
# bg = "transparent"
# )
#
# # Model 2: two datapoints per child with exclusions ####
# cds.dur.agd.best.best.resid <- residuals(cds.dur.agd.best)
# cds.dur.agd.best.resid.plot <- qqplot.data(cds.dur.agd.best.best.resid)
# cds.dur.agd.best.best.int.resids <- data.frame(resid = cds.dur.agd.best.best.resid)
# cds.dur.agd.best.resid.dist.plot <- ggplot(cds.dur.agd.best.best.int.resids,
# aes(x=resid)) +
# geom_histogram(aes(y=..density..),
# fill="white",
# color="black",
# binwidth = 0.05) +
# geom_density(color="firebrick3", lwd=2)
# ggsave(plot = cds.dur.agd.best.resid.plot,
# filename = "cds-uttdursec-agd-modelresids.png",
# path = support.plot.path,
# width = 20,
# height = 10,
# units = "cm",dpi = 72,
# bg = "transparent"
# )
# ggsave(plot = cds.dur.agd.best.resid.dist.plot,
# filename = "cds-uttdursec-agd-modelresiddist.png",
# path = support.plot.path,
# width = 20,
# height = 10,
# units = "cm",dpi = 72,
# bg = "transparent"
# )
#
# # Model 3: Female CDS utterance length ####
# fcd.dur.best.best.resid <- residuals(fcd.dur.best)
# fcd.dur.best.resid.plot <- qqplot.data(fcd.dur.best.best.resid)
# fcd.dur.best.best.int.resids <- data.frame(resid = fcd.dur.best.best.resid)
# fcd.dur.best.resid.dist.plot <- ggplot(fcd.dur.best.best.int.resids,
# aes(x=resid)) +
# geom_histogram(aes(y=..density..),
# fill="white",
# color="black",
# binwidth = 0.05) +
# geom_density(color="firebrick3", lwd=2)
# ggsave(plot = fcd.dur.best.resid.plot,
# filename = "cds-uttdursec-FEM-modelresids.png",
# path = support.plot.path,
# width = 20,
# height = 10,
# units = "cm",dpi = 72,
# bg = "transparent"
# )
# ggsave(plot = fcd.dur.best.resid.dist.plot,
# filename = "cds-uttdursec-FEM-modelresiddist.png",
# path = support.plot.path,
# width = 20,
# height = 10,
# units = "cm",dpi = 72,
# bg = "transparent"
# )
#
# # Model 4: Male CDS utterance length ####
# mcd.dur.best.best.resid <- residuals(mcd.dur.best)
# mcd.dur.best.resid.plot <- qqplot.data(mcd.dur.best.best.resid)
# mcd.dur.best.best.int.resids <- data.frame(resid = mcd.dur.best.best.resid)
# mcd.dur.best.resid.dist.plot <- ggplot(mcd.dur.best.best.int.resids,
# aes(x=resid)) +
# geom_histogram(aes(y=..density..),
# fill="white",
# color="black",
# binwidth = 0.05) +
# geom_density(color="firebrick3", lwd=2)
# ggsave(plot = mcd.dur.best.resid.plot,
# filename = "cds-uttdursec-MAL-modelresids.png",
# path = support.plot.path,
# width = 20,
# height = 10,
# units = "cm",dpi = 72,
# bg = "transparent"
# )
# ggsave(plot = mcd.dur.best.resid.dist.plot,
# filename = "cds-uttdursec-MAL-modelresiddist.png",
# path = support.plot.path,
# width = 20,
# height = 10,
# units = "cm",dpi = 72,
# bg = "transparent"
# )
################################################################################
# PREVALENCE OF NO-XDS BLOCKS ####
no.ads.plot <- ggplot(no.ads.blks, aes(x=ads.utt.N)) +
geom_histogram(binwidth = 1) +
facet_grid(. ~ adu_gender_m) +
xlim(-1,80) + ylim(-1,1500) +
xlab("# ADS utterances in block")
no.cds.plot <- ggplot(no.cds.blks, aes(x=cds.utt.N)) +
geom_histogram(binwidth = 1) +
facet_grid(. ~ adu_gender_m) +
xlim(-1,80) + ylim(-1,1500) +
xlab("# CDS utterances in block")
ggsave(plot = multiplot(no.ads.plot, no.cds.plot, cols=1),
filename = "uttsperblock-FvM.png",
path = support.plot.path,
width = 20,
height = 15,
units = "cm",dpi = 72,
bg = "transparent"
)
no.ads.plot.all <- ggplot(no.ads.blks.all, aes(x=ads.utt.N)) +
geom_histogram(binwidth = 1) +
xlim(-1,80) + ylim(-1,1500) +
xlab("# ADS utterances in block")
no.cds.plot.all <- ggplot(no.cds.blks.all, aes(x=cds.utt.N)) +
geom_histogram(binwidth = 1) +
xlim(-1,80) + ylim(-1,1500) +
xlab("# CDS utterances in block")
ggsave(plot = multiplot(no.ads.plot.all, no.cds.plot.all, cols=1),
filename = "uttsperblock-overall.png",
path = support.plot.path,
width = 10,
height = 15,
units = "cm",dpi = 72,
bg = "transparent"
)
|
044d45a205d6c99882ec4a45d7c74531d9ff7352
|
bdb1db73498d4366556a34fd03bd105296396ad2
|
/R/data.R
|
90b7fdff3549fd2c894d94536b8a6376d16bf026
|
[] |
no_license
|
cran/diffusionMap
|
3b9b634f5dffdae28215003920e7d16694a41f06
|
0fb2aae0da72fa97de3479ac689952de61a09eb5
|
refs/heads/master
| 2020-06-08T18:23:38.788875
| 2019-09-10T21:50:18
| 2019-09-10T21:50:18
| 17,695,503
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 815
|
r
|
data.R
|
#' Annulus toy data set
#'
#' The annulus data frame has 1000 rows and 2 columns. 500 data points are
#' from the noisy annulus and 500 data points reside within the annulus.
#'
#' @format Data are in two dimensions.
#' @keywords data
#'
#' @docType data
"annulus"
#' Chainlink toy clustering data set
#'
#' The Chainlink data frame has 1000 rows and 3 columns. The data are of two
#' interlocking 3-dimensional rings. 500 data points are from one ring and 500
#' from the other ring.
#'
#' @format The data are in 3 dimensions, C1, C2, and C3.
#' @references Ultsch, A.: Clustering with SOM: U*C, In Proc. Workshop on
#' Self-Organizing Maps, Paris, France, (2005) , pp. 75-82
#' @source
#' <http://www.uni-marburg.de/fb12/datenbionik/data?language_sync=1>
#' @keywords data
#'
#' @docType data
"Chainlink"
|
eb2ab6218b7e0ef88cf958c32423413c1d891832
|
129c835434be005639193cfdaa2e9daf30f85da1
|
/man/gencooccur.Rd
|
fc2a0770bee1bef6ee6c8b529b77d2d7ae92a1a3
|
[] |
no_license
|
cran/cooccurNet
|
67aae6e4a003cb32fae98aafdc11bd101a5f3df9
|
e0d16e980b9b919c1656f0995b3fd68bb4b9fbdc
|
refs/heads/master
| 2020-09-26T08:08:19.805303
| 2017-01-27T09:38:24
| 2017-01-27T09:38:24
| 66,298,993
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 3,289
|
rd
|
gencooccur.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cooccurrence.R
\name{gencooccur}
\alias{gencooccur}
\title{gencooccur}
\usage{
gencooccur(data = list(), cooccurFilter = NULL,
networkFile = "cooccurNetwork", module = FALSE,
moduleFile = "cooccurNetworkModule", property = FALSE,
propertyFile = "cooccurNetworkProperty", siteCo = FALSE,
siteCoFile = "siteCooccurr", sampleTimes = 100, debug = FALSE,
parallel = FALSE)
}
\arguments{
\item{data}{list, returns from the function "pprocess()"}
\item{cooccurFilter}{numeric, a number in the range of 0~1. It determines whether two columns are perfect co-occurrence. In default, for the data type of protein, it is set to be 0.9, while for the other data types, it is set to be 1.}
\item{networkFile}{character, 'cooccurNetwork' be default. It is a file name with full path for storing the co-occurrence network for each row.}
\item{module}{logic, FALSE by default, to check whether the modules in each network of the networkFile would be calculated.}
\item{moduleFile}{character, 'cooccurNetworkModule' by default. It is a file name with full path for storing the modules for co-occurrence network.}
\item{property}{logic, FALSE by default, to check whether the properties for each network of the networkFile, including the network diameter, connectivity, ConnectionEffcient and so on, would be calculated.}
\item{propertyFile}{character, 'cooccurNetworkProperty' by default. It is a file name with full path storing the properties for each network of the networkFile.}
\item{siteCo}{logic, FALSE by default, to check whether the residue co-occurence file would be calculated.}
\item{siteCoFile}{character, 'siteCooccurr' by default. It is a file name with full path for storing the RCOS between all pairs of columns, and the related p-values.}
\item{sampleTimes}{numeric, an integer of permutations in the simulation when calculating the p-values. It should be greater than 100.}
\item{debug}{logic, FALSE by default, indicates whether the debug message will be displayed or not.}
\item{parallel}{logic, FALSE by default. It only supports Unix/Mac (not Windows) system.}
}
\value{
list, all the output file paths are attributed in it. \cr The attribute "networkFile" stores the co-occurrence network for each row; \cr The attribute "moduleFile" is optional. When the module is set to be TRUE, it would be output. It stores the modules for co-occurrence network; \cr The attribute "propertyFile" is optional. When the property is set to be TRUE, it would be output. It stores the properties for co-occurrence network; \cr The attribute "siteCoFile" is optional. When the property is set to be TRUE, it would be output. It stores all the pairwise siteCos between columns.
}
\description{
Construct the co-occurrence network
}
\examples{
data = readseq(dataFile=getexample(dataType="protein"),dataType="protein")
data_process = pprocess(data=data)
#cooccurNetwork = gencooccur(data=data_process)
}
\references{
Du, X., Wang, Z., Wu, A., Song, L., Cao, Y., Hang, H., & Jiang, T. (2008). Networks of genomic co-occurrence capture characteristics of human influenza A (H3N2) evolution. Genome research, 18(1), 178-187. doi:10.1101/gr.6969007
}
|
7992a957b5e48eabc33b83ea330be9a668bae81a
|
e5f84c07e4b229502c67fff9ced2fa29420d5777
|
/R.old.code/zPoisProcAnalisis_FS.R
|
d01c9400ffa080cb3d8bc66ecc3475ced494a717
|
[] |
no_license
|
paurabassa/storm-generation
|
cd648f4ef868f312f48fb909b4aa4971a4760804
|
a7ace284d5be9dbf7830f1d984e5492c25042f0c
|
refs/heads/master
| 2021-01-22T17:22:51.416127
| 2015-04-20T18:28:37
| 2015-04-20T18:28:37
| 31,430,642
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 9,894
|
r
|
zPoisProcAnalisis_FS.R
|
##
##
## Analisis of interarrival time of storms via a non-homogenuous
## Poisson Process. Amended by Francesco to include modelling via
## GAM models
##
##
####################
# Part 1: Data fit #
####################
#set random seed
set.seed(1234)
# Read data
waves <- read.csv("./Clean.Data/waves-hourly.csv")
waves$Date <- as.POSIXct(strptime(waves$Date, "%Y-%m-%d %H:%M:%S","GMT"))
# Extract the point process of excedances (storms)
source("R.functions/ExtractPOTpp.R")
pots.storm <- ExtractPOTPointProcess(waves$hs,2.5)
storm.start <- as.POSIXct(waves$Date[pots.storm$p.exc])
storm.end <- as.POSIXct(waves$Date[pots.storm$p.exc + pots.storm$c.siz])
summary(difftime(storm.end,storm.start))
# Computation of the year fraction times and sanity test
source("R.functions/YearFraction.R")
ss.frac <- sapply(storm.start, yearfraction)
se.frac <- sapply(storm.end , yearfraction)
l <- length(ss.frac)
which(ss.frac[2:l]-se.frac[1:(l-1)]<0)
# histogram of diferences taking into acount the jump from one year to the next
faux<- function(x){ if(x<0){ y <-x+1}else{ y<-x}; y}
gaps <- sapply(ss.frac[2:l]-se.frac[1:(l-1)],faux)
hist(gaps,breaks=50)
nyears <- as.POSIXlt(tail(waves$Date,n=1))$year - as.POSIXlt(waves$Date[1])$year
# check if there is a correlation between storm duration (c.siz) and the
# inter arrival times
cor(sapply(ss.frac[2:l]-se.frac[1:(l-1)],faux),pots.storm$c.siz[1:(l-1)],method="k")
plot(sapply(ss.frac[2:l]-se.frac[1:(l-1)],faux),pots.storm$c.siz[1:(l-1)])
plot(rank(sapply(ss.frac[2:l]-se.frac[1:(l-1)],faux),ties.method="r")/l,rank(pots.storm$c.siz[1:(l-1)],ties.method="r")/l)
cor(sapply(ss.frac[2:l]-se.frac[1:(l-1)],faux),ss.frac[2:l],method="k")
plot(rank(sapply(ss.frac[2:l]-se.frac[1:(l-1)],faux),ties.method="r")/l,rank(ss.frac[2:l],ties.method="r")/l)
plot(sort(gaps/mean(gaps)),1-ppoints(l-1,0),log="y")
lines(sort(gaps/mean(gaps)), exp(-sort(gaps/mean(gaps))))
lines(sort(gaps/mean(gaps)), 1-pweibull(sort(gaps/mean(gaps)),.55))
# maximum likelihood fits of the gaps to a pp.distribution with intensity
# function lambda_i, i=1,2,3. For lambda_3 it is necessary to estimate 3
# parameters first, and then add the other 2.
source("R.functions/funcs_PPA.R")
fit.lam1 <- mle(ll.lam1,list(theta=1))
thet.lam1 <- coef(fit.lam1)[[1]]
fit.lam2 <- mle( llike.lam2, start = list(theta1 = 1, theta2=0.4, theta3=0.4))
thet.lam2 <- coef(fit.lam2)
fit.lam3.aux <- mle( llike.lam3.aux, method="L-BFGS-B", lower=c(0.01,0.01,0),
start = list(theta1 = 0, theta2=1, theta3=0.))
thet.lam3.aux <- coef(fit.lam3.aux)
fit.lam3 <- mle( llike.lam3, method="L-BFGS-B", lower=c(0,0.01,0,-Inf,0),
start = list(theta1 = thet.lam3.aux[[1]], theta2=thet.lam3.aux[[2]],
theta3 = thet.lam3.aux[[3]], theta4 = 0, theta5=1))
thet.lam3 <- coef(fit.lam3)
############################
# Part 2: Diagnostic Plots #
############################
# Densities of the 3 fitted distributions vs empirical histogram
x <- seq(0,1,0.001)
y1 <- sapply(x,function(x) { lambda1(x,thet.lam1)})
area <- sum(y1)/length(y1)
y1 <- y1/area
y2 <- sapply(x,function(x) { lambda2(x,thet.lam2)})
area <- sum(y2)/length(y2)
y2 <- y2/area
y3 <- sapply(x,function(x) { lambda3(x,thet.lam3)})
area <- sum(y3)/length(y3)
y3 <- y3/area
hist(se.frac, prob = T)
lines(x, y1, lty=1)
lines(x, y2, lty=2)
lines(x, y3, lty=3)
# quantile-quantile plots of the empirical inter arrival times vs
# fitted Poission Process
op <- par(mfrow=c(1,3))
#lambda1
x.lam1 <- vector("numeric")
for (i in 1:(l-1)) x.lam1[i]<- p.pp.cond(gaps[i],lambda1, thet.lam1, se.frac[i])
qqplot(qunif(ppoints(500)), x.lam1)
lines(seq(-0.1,1.1,0.0001),seq(-.1,1.1,0.0001))
# lambda2
x.lam2 <- vector("numeric")
for (i in 1:(l-1)) x.lam2[i]<- p.pp.cond(gaps[i],lambda2, thet.lam2, se.frac[i])
qqplot(qunif(ppoints(500)), x.lam2)
lines(seq(-0.1,1.1,0.0001),seq(-.1,1.1,0.0001))
# lambda3
x.lam3 <- vector("numeric")
for (i in 1:(l-1)) x.lam3[i]<- p.pp.cond(gaps[i],lambda3, thet.lam3, se.frac[i])
qqplot(qunif(ppoints(500)), x.lam3)
lines(seq(-0.1,1.1,0.0001),seq(-.1,1.1,0.0001))
par(op)
######################## GAM modelling########################################
######################## GAM modelling########################################
######################## GAM modelling########################################
######################## GAM modelling########################################
######################## GAM modelling########################################
######################## GAM modelling########################################
library(gamlss)
tt <- ss.frac[1:(l-1)]
fit.1 <- gamlss(gaps ~ sin(2*pi*tt) +cos(2*pi*tt) +sin(4*pi*tt) +cos(4*pi*tt) +sin(8*pi*tt) +cos(8*pi*tt)
, sigma.formula = ~ sin(2*pi*tt) +cos(2*pi*tt) +sin(4*pi*tt) + cos(4*pi*tt) +sin(8*pi*tt) +cos(8*pi*tt)
, family="BE")
centiles(fit.1,tt ,ylim=c(0,1))
wp(fit.1)
plot(fit.1)
######################## GAM modelling########################################
######################## GAM modelling########################################
######################## GAM modelling########################################
######################## GAM modelling########################################
######################## GAM modelling########################################
######################## GAM modelling########################################
# probability-probability plots of the empirical inter arrival times vs
# fitted models
op <- par(mfrow=c(2,2),mar=c(4,4,1,1))
# lambda2
x.lam1 <- vector("numeric")
for (i in 1:(l-1)) x.lam1[i]<- p.pp.cond(gaps[i],lambda1, thet.lam1, se.frac[i])
qqplot(ppoints(500), x.lam1)
abline(0,1)
# lambda2
x.lam2 <- vector("numeric")
for (i in 1:(l-1)) x.lam2[i]<- p.pp.cond(gaps[i],lambda2, thet.lam2, se.frac[i])
qqplot(ppoints(500), x.lam2)
abline(0,1)
# lambda3
x.lam3 <- vector("numeric")
for (i in 1:(l-1)) x.lam3[i]<- p.pp.cond(gaps[i],lambda3, thet.lam3, se.frac[i])
qqplot(ppoints(500), x.lam3)
abline(0,1)
# GAM
para <- predictAll(fit.1)
p.BE <- pBE(gaps,para$mu, para$sigma)
qqplot(ppoints(500), p.BE)
abline(0,1)
par(op)
#############################
# Part 3: Generate a sample via BETA GAM
#############################
# Given a set of indexed storms from 1:nst we generate a new resample of
# storms, which is represented by
# storm start
# storm index
# storm duration
# storms generation
n.str <- as.POSIXct("20150101 00:00",format ="%Y%m%d %H:%M") #next strom time
i <- 1
future <- as.POSIXct("20650101 00:00",format ="%Y%m%d %H:%M")
n.st <- vector()
n.sind <- vector()
n.gap <- vector()
while(n.str < future){
n.st[i] <- as.POSIXct(n.str, origin="1970-01-01 00:00.00 UTC")
yf <- yearfraction(date=n.str) #year fraction
n.para <- predictAll(fit.1, newdata=data.frame(tt=yf),data=data.frame(gaps,tt))
n.gap.aux<- qBE(runif(1), n.para$mu, n.para$sigma) #gap in year units
n.gap[i] <- as.integer(n.gap.aux*365*24) #gap in seconds truncated at hours
n.sind[i]<- sample(1:l,size=1) #storm index
n.dur <- pots.storm$c.siz[n.sind[i]] #storm duration in seconds
n.str <- as.POSIXct(n.st[i] + 3600*(n.gap[i] + n.dur), origin="1970-01-01 00:00.00 UTC")
i <- i+1
}
# save new set of stroms into a data set
new.storms <- data.frame(s.times= as.POSIXct(n.st,
origin="1970-01-01 00:00.00 UTC"),
s.index= n.sind, s.dur= pots.storm$c.siz[n.sind],
s.gap=n.gap)
# qqplot of generated data vs original set of storms
qqplot(new.storms$s.gap, as.integer(365*24*gaps))
lines(seq(-10,10000,0.1), seq(-10,10000,0.1))
# Check that the average number of storms x year is similar in
# the original and the simulated data:
length(pots.storm[[1]])/nyears
length(new.storms[[1]])/50
##
## Write the resample of future storms with its corresponding predicted tide.
##
p.clim <- read.csv("./Clean.Data/clim-hourly.csv") # past climate
p.clim$Date <- as.POSIXct(strptime(p.clim$Date, "%Y-%m-%d %H:%M:%S","GMT"))
f.tide <- read.csv("./Clean.Data/future-tides.csv") # future tide
f.tide$Date <- as.POSIXct(strptime(f.tide$Date, "%Y-%m-%d %H:%M:%S", "GMT"))
storm.climate <- data.frame(Date = as.POSIXct(vector(mode="numeric"),
origin= '1970-01-01 00:00.00 UTC'),
hs = vector(mode="numeric"), fp = vector(mode="numeric"),
tm = vector(mode="numeric"), dir = vector(mode="numeric"),
U10 = vector(mode="numeric"), V10 = vector(mode="numeric"),
a.tide=vector(mode="numeric"), res= vector(mode="numeric"))
i.aux<-1
for(i in 1:length(new.storms$s.times)){
print(paste(i," out of ",length(new.storms$s.times),sep=""))
for(j in 1:pots.storm$c.siz[new.storms$s.ind[i]]){
i.past <- pots.storm$p.exc[new.storms$s.ind[i]] + j-1
date.fut <- as.POSIXct(new.storms$s.times[i] + 3600*(j-1),
origin="1970-01-01 00:00.00 UTC")
# index.fut.tide <- which(f.tide$Date == date.fut
tide.fut <- f.tide[which(f.tide$Date == date.fut),]$Level
storm.climate[i.aux,"Date"] = date.fut
storm.climate[i.aux, c("hs", "fp", "tm", "dir", "U10", "V10", "res")] =
p.clim[i.past, c("hs", "fp", "tm", "dir", "U10", "V10", "res")]
storm.climate[i.aux, "a.tide"] = tide.fut
i.aux <- i.aux + 1
}
}
write.csv(storm.climate, "New.Data/storms-Pois-2.csv",row.names=F)
|
eb36f339be41c4a2a3e76e11a70965feb34645ba
|
5d84ca384c45b6280004fced1e2e11a1d43e8ff9
|
/scripts/MarinhoCatunda_etal_2021_Figure1a.c_soil_perharvest.R
|
44a5c5aa0f3fc4ac7c60a67443fa1efd470abdc7
|
[] |
no_license
|
kjfuller06/PACE
|
90cb0d55dd28a4264756a594ca5faf821a117e06
|
158e57be90abeb99d93c42648a126abf4cef9d49
|
refs/heads/master
| 2022-04-26T21:01:34.076401
| 2022-04-22T21:55:41
| 2022-04-22T21:55:41
| 192,671,350
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 7,299
|
r
|
MarinhoCatunda_etal_2021_Figure1a.c_soil_perharvest.R
|
Baug = as.POSIXct("2019-08-20 08:00:00")
Boct = as.POSIXct("2019-09-30 08:00:00")
Faug_13 = as.POSIXct("2019-08-20 08:00:00")
Faug_46 = as.POSIXct("2019-08-21 08:00:00")
Foct = as.POSIXct("2019-10-08 08:00:00")
Fnov = as.POSIXct("2019-11-18 08:00:00")
Laug = as.POSIXct("2019-08-16 08:00:00")
Loct = as.POSIXct("2019-10-02 08:00:00")
Lnov = as.POSIXct("2019-11-15 08:00:00")
Raug = as.POSIXct("2019-08-13 08:00:00")
Roct_14 = as.POSIXct("2019-09-30 08:00:00")
Roct_56 = as.POSIXct("2019-10-02 08:00:00")
#start date
sD<-as.Date("2019-06-01")
#end date
eD<-as.Date("2019-11-30")
#Irrigation####
Irrig<- (downloadTOA5("PACE_AUTO_ALL_IRRIG_R_", startDate=sD, endDate=eD, keepFiles=FALSE))[,c(1,4:6)]
#Rename columns
names(Irrig)<-c("DateTime","Code","Treatment","Irrigation")
Irrig$Shelter = substr(Irrig$Code,1 ,2)
Irrig$Plot = paste0("P", substr(Irrig$Code, 4, 4))
plots = read.csv("PACE_treatment_species_reference.csv")
plots$Shelter = substr(plots$Subplot.ID, 1, 2)
plots$Plot = substr(plots$Subplot.ID, 3, 4)
Irrig = left_join(Irrig, plots)
# assign harvest month of interest for summary stats
Irrig$month = NA
Irrig$month[Irrig$Species == "Bis" & Irrig$DateTime <= Baug] = "Aug"
Irrig$month[Irrig$Species == "Bis" & Irrig$DateTime > Baug & Irrig$DateTime <= Boct] = "Oct"
Irrig$month[Irrig$Species == "Fes" & Irrig$Shelter %in% c("S1", "S2", "S3") & Irrig$DateTime <= Faug_13] = "Aug"
Irrig$month[Irrig$Species == "Fes" & Irrig$Shelter %in% c("S4", "S5", "S6") & Irrig$DateTime <= Faug_46] = "Aug"
Irrig$month[Irrig$Species == "Fes" & Irrig$Shelter %in% c("S1", "S2", "S3") & Irrig$DateTime > Faug_13 & Irrig$DateTime <= Foct] = "Oct"
Irrig$month[Irrig$Species == "Fes" & Irrig$Shelter %in% c("S4", "S5", "S6") & Irrig$DateTime > Faug_46 & Irrig$DateTime <= Foct] = "Oct"
Irrig$month[Irrig$Species == "Fes" & Irrig$DateTime > Foct & Irrig$DateTime <= Fnov] = "Nov"
Irrig$month[Irrig$Species == "Luc" & Irrig$DateTime <= Laug] = "Aug"
Irrig$month[Irrig$Species == "Luc" & Irrig$DateTime > Laug & Irrig$DateTime <= Loct] = "Oct"
Irrig$month[Irrig$Species == "Luc" & Irrig$DateTime > Loct & Irrig$DateTime <= Lnov] = "Nov"
Irrig$month[Irrig$Species == "Rye" & Irrig$DateTime <= Raug] = "Aug"
Irrig$month[Irrig$Species == "Rye" & Irrig$Shelter %in% c("S1", "S2", "S3", "S4") & Irrig$DateTime > Raug & Irrig$DateTime <= Roct_14] = "Oct"
Irrig$month[Irrig$Species == "Rye" & Irrig$Shelter %in% c("S5", "S6") & Irrig$DateTime > Raug & Irrig$DateTime <= Roct_56] = "Oct"
#force Treatment to be a factor
Irrig$Treatment<-as.factor(Irrig$Treatment)
levels(Irrig$Treatment)<-c("Control","Drought","Control","Drought")
Irrig<-aggregate(data=Irrig,Irrigation~month+Treatment+Plot+Subplot.ID,FUN=sum)
Irrig<-aggregate(data=Irrig,Irrigation~month+Treatment,FUN=mean)
Irrig$month = factor(Irrig$month, levels = c("Aug", "Oct", "Nov"))
Irrig = Irrig[order(Irrig$month, Irrig$Treatment),]
# plot
tiff(file = paste("Figure1a_Irrig_",sD,"_",eD,".tiff",sep=""), width =1100, height = 900, units = "px", res = 200)
ggplot(data=Irrig, aes(x=month, y=Irrigation, fill=Treatment)) +
geom_bar(stat="identity", width=0.75, color="black", position=position_dodge())+
theme_classic() +
scale_fill_manual(values=c('black','white')) +
labs(x="Month", y = "Irrigation (mm)")
dev.off()
#Soil Moisture####
#download data from HIEv and only keep soil moisture variables of interest
for(i in c(1:6)){
s<-(downloadTOA5(paste("PACE_AUTO_S",i,"_BLWGRND_R_",sep=""), startDate=sD, endDate=eD, keepFiles=FALSE))[,c(1,3:26)]
assign(paste("s",i,sep=""),s)
}
#convert to long form, add "shelter" variable
s1<-reshape2::melt(s1,id.vars="DateTime")
s1$Shelter<-1
s2<-reshape2::melt(s2,id.vars="DateTime")
s2$Shelter<-2
s3<-reshape2::melt(s3,id.vars="DateTime")
s3$Shelter<-3
s4<-reshape2::melt(s4,id.vars="DateTime")
s4$Shelter<-4
s5<-reshape2::melt(s5,id.vars="DateTime")
s5$Shelter<-5
s6<-reshape2::melt(s6,id.vars="DateTime")
s6$Shelter<-6
#combine into one DF
soil<-rbind(s1,s2,s3,s4,s5,s6)
names(soil)<-c("DateTime","SensorCode","value","Shelter")
sensors<-read.csv("soilsensors.csv")
soil<-merge(soil,sensors,by=c("Shelter","SensorCode"))
soil = soil %>%
filter(Position != "Lower" & SensorType == "TDR")
soil$water<-as.factor(substr(soil$Treatment, 4, 6))
soil$code = paste0("S", soil$Shelter, "P", soil$Plot)
soil = soil %>%
dplyr::select(-SensorCode,
-SensorType,
-Treatment,
-Position)
soil = soil[order(soil$DateTime, soil$Shelter, soil$water),]
soil<-aggregate(data=soil,value~Shelter+DateTime+Sp+water,FUN=mean)
soil = soil %>%
pivot_wider(names_from = water, values_from = value) %>%
as.data.frame()
soil$comp = soil$Drt - soil$Con
#change class of variables
soil$Sp<-as.factor(soil$Sp)
soil$Shelter<-as.factor(soil$Shelter)
# assign harvest month of interest for summary stats
soil$month = NA
soil$month[soil$Sp == "BIS" & soil$DateTime <= Baug] = "Aug"
soil$month[soil$Sp == "BIS" & soil$DateTime > Baug & soil$DateTime <= Boct] = "Oct"
soil$month[soil$Sp == "FES" & soil$Shelter %in% c("1", "2", "3") & soil$DateTime <= Faug_13] = "Aug"
soil$month[soil$Sp == "FES" & soil$Shelter %in% c("4", "5", "6") & soil$DateTime <= Faug_46] = "Aug"
soil$month[soil$Sp == "FES" & soil$Shelter %in% c("1", "2", "3") & soil$DateTime > Faug_13 & soil$DateTime <= Foct] = "Oct"
soil$month[soil$Sp == "FES" & soil$Shelter %in% c("4", "5", "6") & soil$DateTime > Faug_46 & soil$DateTime <= Foct] = "Oct"
soil$month[soil$Sp == "FES" & soil$DateTime > Foct & soil$DateTime <= Fnov] = "Nov"
soil$month[soil$Sp == "LUC" & soil$DateTime <= Laug] = "Aug"
soil$month[soil$Sp == "LUC" & soil$DateTime > Laug & soil$DateTime <= Loct] = "Oct"
soil$month[soil$Sp == "LUC" & soil$DateTime > Loct & soil$DateTime <= Lnov] = "Nov"
soil$month[soil$Sp == "RYE" & soil$DateTime <= Raug] = "Aug"
soil$month[soil$Sp == "RYE" & soil$Shelter %in% c("1", "2", "3", "4") & soil$DateTime > Raug & soil$DateTime <= Roct_14] = "Oct"
soil$month[soil$Sp == "RYE" & soil$Shelter %in% c("5", "6") & soil$DateTime > Raug & soil$DateTime <= Roct_56] = "Oct"
soil$month = factor(soil$month, levels = c("Aug", "Oct", "Nov"))
soil = soil[order(soil$DateTime),]
#remove NAs
soil<-na.omit(soil)
#Summarize data
backup1<-soil
soil$comp = soil$comp*100
soil$Con = soil$Con*100
soil$Drt = soil$Drt*100
soil<-aggregate(data=soil,comp~Sp+month,FUN=function(x) c(avg=mean(x),stder=sd(x)/sqrt(length(x))),simplify=TRUE,drop=TRUE)
#spit the aggregate function outputs into a DF and reassign so they are variables in the dataframe
##otherwise the output is a list within soil
val<-data.frame(soil[["comp"]])
soil$value<-val$avg
soil$stder<-val$stder
soil = soil[order(soil$month),]
# plot
tiff(file = paste("Figure1c_soilVWC_",sD,"_",eD,".tiff",sep=""), width =1100, height = 900, units = "px", res = 200)
ggplot(data=soil, aes(x=month, y=value, group = month, color=month)) +
ylim(c(-4.5, 2)) +
geom_point(size = .5, stroke = 0) +
geom_pointrange(aes(ymin=value-stder, ymax=value+stder)) +
scale_color_manual(values=c('deepskyblue','blue', "grey45")) +
facet_wrap(~Sp, strip.position = "bottom", nrow = 1) +
labs(x="Month", y = "Volumetric Water Content (%)") +
geom_hline(yintercept = 0) +
theme_classic() +
theme(legend.position = "none")
dev.off()
|
a511316d70719989653c4585f9879e090f8a1fd8
|
d9a3434bc86c670a563a09c248b2ba142842634d
|
/cachematrix.R
|
9dee097c2e84ea34c0fd16c7c547f0f72086399d
|
[] |
no_license
|
Aladroite/ProgrammingAssignment2
|
cc00f859c799e9969b7b3f7b463b3d1495409851
|
53bdc61bc2d51015d4e80e4d31aa81fa9450ec2b
|
refs/heads/master
| 2020-03-25T21:49:39.923635
| 2018-08-09T21:41:16
| 2018-08-09T21:41:16
| 144,191,333
| 0
| 0
| null | 2018-08-09T18:47:34
| 2018-08-09T18:47:33
| null |
UTF-8
|
R
| false
| false
| 1,224
|
r
|
cachematrix.R
|
## Put comments here that give an overall description of what your
## functions do: Alison Lewis, makeCacheMatrix and cacheSolve Assignments
## The makeCacheMatrix function: creates a special 'matrix' object
## that can cache its reverse. The special 'matrix' object is a list of
## functions that can: 1. Set the value of the matrix, 2. get the value of
## the matrix, 3. set the value of the inverse, 4. get the value of the inverse
makeCacheMatrix <- function(x = matrix()) {
i<-NULL
set<-function (y) {
x<<- y
i<<- NULL
}
get<- function () x
setinverse<- function(inverse) i <<-inverse
getinverse<- function() i
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
}
## The cacheSolve function: computes the inverse of the special matrix
## created above. However, it first checks the cache to see if
## the inverse has already been computed and stored. If the inverse has
## already been computed and cached, it simply retrieves this value.
## Otherwise it computes the inverse and stores this new value in the cache.
cacheSolve <- function(x, ...) {
i<-x$getinverse()
if(!is.null(i)){
message("getting cached data")
return (i)
}
data<- x$get()
i<- solve(data, ...)
x$setinverse(i)
i
}
|
0d742add927e9d5ad4f14112da0d8c95067b03a2
|
80c6b6739dab6bbfde951f8ff3fa1bb3b8768563
|
/pgmm.methods.R
|
d02c8a807ea6664a70ffe683fe03a85e2e0f6523
|
[] |
no_license
|
Eligijus112/bachelor
|
18d6a38502d4f92f2e596b6db4de9cd46cec2fbe
|
10433c7753a60abaa330f60c37512410b56594e7
|
refs/heads/master
| 2021-01-13T15:48:18.113949
| 2017-05-21T11:18:36
| 2017-05-21T11:18:36
| 79,720,111
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 7,134
|
r
|
pgmm.methods.R
|
coef.pgmm <- function(object,...){
model <- describe(object, "model")
if(model == "onestep") coefficients <- object$coefficients
else coefficients <- object$coefficients[[2]]
coefficients
}
summary.pgmm <- function(object, robust = TRUE, time.dummies = FALSE, ...){
# model <- describe(object, "model")
# effect <- describe(object, "effect")
# transformation <- describe(object, "transformation")
model <- object$args$model
effect <- object$args$effect
transformation <- object$args$transformation
if (robust){
vv <- vcovHC(object)
A <- object$A2
}
else{
vv <- vcov(object)
A <- object$A1
}
if (model == "onestep") K <- length(object$coefficients)
else K <- length(object$coefficients[[2]])
object$sargan <- sargan(object, "twosteps")
object$m1 <- mtest(object, 1, vv)
object$m2 <- mtest(object, 2, vv)
object$wald.coef <- wald(object, "coef", vv)
if (describe(object, "effect") == "twoways") object$wald.td <- wald(object,"time",vv)
Kt <- length(object$args$namest)
if (! time.dummies && effect == "twoways") rowsel <- -c((K - Kt + 1):K)
else rowsel <- 1:K
std.err <- sqrt(diag(vv))
b <- coef(object)
z <- b / std.err
p <- 2 * pnorm(abs(z), lower.tail = FALSE)
coefficients <- cbind(b, std.err, z, p)
colnames(coefficients) <- c("Estimate", "Std. Error", "z-value", "Pr(>|z|)")
object$coefficients <- coefficients[rowsel, , drop = FALSE]
class(object) <- "summary.pgmm"
object
}
mtest <- function(object, order = 1, vcov = NULL){
myvcov <- vcov
if (is.null(vcov)) vv <- vcov(object)
else if (is.function(vcov)) vv <- myvcov(object)
else vv <- myvcov
model <- describe(object, "model")
transformation <- describe(object, "transformation")
Kt <- length(object$args$namest)
if (transformation == "d"){
resid <- object$residuals
residl <- lapply(resid,
function(x) c(rep(0,order), x[1:(length(x)-order)])
)
}
else{
resid <- lapply(object$residuals,
function(x) c(x[-c(Kt:(2*Kt + 1))], rep(0, Kt)))
residl <- lapply(object$residuals,
function(x) c(rep(0, order), x[1:(Kt-order-1)], rep(0, Kt)))
}
X <- lapply(object$model, function(x) x[,-1])
W <- object$W
if (model == "onestep") A <- object$A1
else A <- object$A2
EVE <- Reduce("+",
mapply(function(x, y) t(y) %*% x %*% t(x) %*%y, resid, residl, SIMPLIFY = FALSE))
EX <- Reduce("+", mapply(crossprod, residl, X, SIMPLIFY = FALSE))
XZ <- Reduce("+", mapply(crossprod, W, X, SIMPLIFY = FALSE))
ZVE <- Reduce("+",
mapply(function(x,y,z) t(x)%*%y%*%t(y)%*%z, W, resid, residl, SIMPLIFY = FALSE))
denom <- EVE - 2 * EX %*% vcov(object) %*% t(XZ) %*% A %*% ZVE + EX %*% vv %*% t(EX)
num <- Reduce("+", mapply(crossprod, resid, residl, SIMPLIFY = FALSE))
stat <- num / sqrt(denom)
names(stat) <- "normal"
pval <- pnorm(abs(stat), lower.tail = FALSE)
mtest <- list(statistic = stat,
p.value = pval,
method = paste("Autocorrelation test of degree", order))
class(mtest) <- "htest"
mtest
}
wald <- function(object, param = c("coef", "time", "all"), vcov = NULL){
param <- match.arg(param)
myvcov <- vcov
if (is.null(vcov)) vv <- vcov(object)
else if (is.function(vcov)) vv <- myvcov(object)
else vv <- myvcov
model <- describe(object, "model")
effect <- describe(object, "effect")
if (param == "time" && effect == "individual") stop("no time-dummies in this model")
transformation <- describe(object, "transformation")
if (model == "onestep") coefficients <- object$coefficients
else coefficients <- object$coefficients[[2]]
Ktot <- length(coefficients)
Kt <- length(object$args$namest)
if (param == "time"){
start <- Ktot - Kt + ifelse(transformation == "ld", 2, 1)
end <- Ktot
}
if (param == "coef"){
start <- 1
if (effect == "twoways") end <- Ktot-Kt else end <- Ktot
}
if (param == "all"){
start <- 1
end <- Ktot
}
coef <- coefficients[start:end]
vv <- vv[start:end, start:end]
stat <- t(coef) %*% solve(vv) %*% coef
names(stat) <- "chisq"
parameter <- length(coef)
pval <- pchisq(stat, df = parameter, lower.tail = FALSE)
wald <- list(statistic = stat,
p.value = pval,
parameter = parameter,
method = "Wald test")
class(wald) <- "htest"
wald
}
print.summary.pgmm <- function(x, digits = max(3, getOption("digits") - 2),
width = getOption("width"),
...){
model <- describe(x, "model")
transformation <- describe(x, "transformation")
effect <- describe(x, "effect")
pdim <- attr(x,"pdim")
formula <- x$call$formula
cat(paste(effect.pgmm.list[effect]," ",sep=""))
cat(paste(model.pgmm.list[model],"\n",sep=""))
cat("\nCall:\n")
print(x$call)
cat("\n")
print(pdim)
ntot <- sum(unlist(x$residuals) != 0)
cat("\nNumber of Observations Used: ",ntot,"\n")
cat("\nResiduals\n")
print(summary(unlist(residuals(x))))
cat("\nCoefficients\n")
printCoefmat(x$coefficients,digits=digits)
cat("\nSargan Test: ",names(x$sargan$statistic),
"(",x$sargan$parameter,") = ",x$sargan$statistic,
" (p.value=",format.pval(x$sargan$p.value,digits=digits),")\n",sep="")
cat("Autocorrelation test (1): ",names(x$m1$statistic),
" = ",x$m1$statistic,
" (p.value=",format.pval(x$m1$p.value,digits=digits),")\n",sep="")
cat("Autocorrelation test (2): ",names(x$m2$statistic),
" = ",x$m2$statistic,
" (p.value=",format.pval(x$m2$p.value,digits=digits),")\n",sep="")
cat("Wald test for coefficients: ",names(x$wald.coef$statistic),
"(",x$wald.coef$parameter,") = ",x$wald.coef$statistic,
" (p.value=",format.pval(x$wald.coef$p.value,digits=digits),")\n",sep="")
if (describe(x, "effect") == "twoways"){
cat("Wald test for time dummies: ",names(x$wald.td$statistic),
"(",x$wald.td$parameter,") = ",x$wald.td$statistic,
" (p.value=",format.pval(x$wald.td$p.value,digits=digits),")\n",sep="")
}
invisible(x)
}
sargan <- function(object, weights = c("twosteps", "onestep")){
weights <- match.arg(weights)
model <- describe(object, "model")
transformation <- describe(object, "transformation")
if (model == "onestep") Ktot <- length(object$coefficient)
else Ktot <- length(object$coefficient[[2]])
N <- length(residuals(object))
z <- as.numeric(Reduce("+",
lapply(seq_len(N),
function(i) crossprod(object$W[[i]], residuals(object)[[i]]))))
p <- ncol(object$W[[1]])
if (weights == "onestep") A <- object$A1 else A <- object$A2
stat <- as.numeric(crossprod(z, t(crossprod(z, A))))
parameter <- p - Ktot
names(parameter) <- "df"
names(stat) <- "chisq"
method <- "Sargan test"
pval <- pchisq(stat, df = parameter, lower.tail = FALSE)
sargan <- list(statistic = stat,
p.value = pval,
parameter = parameter,
method = "Sargan Test")
class(sargan) <- "htest"
sargan
}
|
fd759daa5ba5a248224b814477028b0faa67df3f
|
da8baef13311f0a710b1c33d279caf8550be0665
|
/R/CounterBind.R
|
aff063e8d193b8ff118205cb607479a23cb5260a
|
[] |
no_license
|
colinpmillar/FishCounter
|
51c9e5abe846fd6b36822bef698cf8afc25f91e0
|
10e389a6a690d59a58f19ca18f8e8f7866a04c12
|
refs/heads/master
| 2021-01-21T08:43:51.879886
| 2015-04-02T20:29:16
| 2015-04-02T20:29:16
| 33,184,834
| 0
| 0
| null | 2015-03-31T12:44:32
| 2015-03-31T12:44:32
| null |
UTF-8
|
R
| false
| false
| 3,417
|
r
|
CounterBind.R
|
#' bind_counter_data
#' bind individual data files, clean up data, and return a master data file.
#' A function to bind and process Logie counter data
#' This function allows you to bind together mulitple counter data files, remove errors and produce a master datafile.
#' @param path_to_folder This is the file path for the folder that contains all data files for processing.
#' @param no_channels This is the number of counter channels that were operated.
#' @param site Name of the study river.
#' @param year Year of counter operation.
#' @param max_signal The maximum signal size.
#' @export
bind_counter_data <- function(path_to_folder, no_channels, site, year, max_signal) {
library(plyr)
library(dplyr)
if(missing(site)) {
site <- ""
}
if(missing(year)) {
year <- ""
}
counter.paths <- dir(path_to_folder, full.names = TRUE)
names(counter.paths) <- basename(counter.paths)
counter.data1 <- ldply(counter.paths,
read.table,
header=FALSE,
sep="",
fill=TRUE,
stringsAsFactors=FALSE)[, c(1:7)]
#stringsAsFactors=FALSE is important because conversion
#of numeric factors to numeric can be problematic.
colnames(counter.data1) <- c("file",
"date",
"time",
"X",
"channel",
"description",
"signal")
counter.data2 <- subset(counter.data1,
description=="U" | description=="D" | description=="E")
#This removes erronious data or unwanted counter status data
date.alt <- strptime(counter.data2$date, '%d/%m/%y')
counter.data2$jday <- date.alt$yday
counter.data3 <- subset(counter.data2, jday != "NA")
counter.data4 <- data.frame("file"=counter.data3$file,
"date.time"=as.character(as.POSIXlt(strptime(paste(counter.data3$date,
counter.data3$time, sep="-"),
format='%d/%m/%y-%H:%M:%S'))),
"date"=as.character(as.POSIXlt(strptime(counter.data3$date,
format="%d/%m/%y"))),
"time"=as.character(counter.data3$time),
"X"=as.numeric(counter.data3$X),
"channel"=as.numeric(counter.data3$channel),
"description"=counter.data3$description,
"signal"=as.numeric(counter.data3$signal))
counter.data5 <- subset(counter.data4, channel <= (no_channels))
# removes any errors in channel number
counter.data6 <- counter.data5[!duplicated(counter.data5[, c(2, 6)]), ]
# removes any duplicate data
counter.data7 <- subset(counter.data6, signal <= max_signal)
# gets rid of levels that have been subseted out.
counter.data <- droplevels(counter.data7)
# gets rid of levels that have been subseted out.
counter.data <- counter.data[order(counter.data$date.time), ]
# Now write a new text file with only the graphics data.
# The row names, column names and quotes must be removed.
write.csv(x=counter.data[, -2],
file=paste(path_to_folder,
site,
year,
".csv",
sep=""),
row.names=FALSE)
}
|
79af205049b6a6d36b281ff1fd7b45134cb8bc76
|
bc42c76a961ef56d4d08a714c0eaabb4366a36a1
|
/R/DepCPSPKenv.R
|
0ba7b35d1c2cd750652b4a060e928ad90713308f
|
[] |
no_license
|
cran/IndTestPP
|
593ab1dc0ddb6addd008e80aed948d88058a240c
|
a628d5be9c314513541656d6e2ea28dd9bc91cee
|
refs/heads/master
| 2021-06-28T21:12:36.085070
| 2020-08-28T18:00:03
| 2020-08-28T18:00:03
| 64,703,962
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 488
|
r
|
DepCPSPKenv.R
|
DepCPSPKenv <-
function(i,lambdaix, lambdaiy, lambdaixy,lambdax, lambday, r=NULL, T=NULL,typeEst, fixed.seed=NULL)
{
if (!is.null(fixed.seed)) fixed.seed2<-fixed.seed+i
auxpos<-DepNHCPSP(lambdaiM=cbind(lambdaix, lambdaiy, lambdaixy), d=2 ,dplot=FALSE,
fixed.seed=fixed.seed2)$posNH
Kaux<-NHKaux(lambdaC=lambdax, lambdaD=lambday,T=T, posC=auxpos$N1,
posD=auxpos$N2, typeC=rep(1,length(auxpos$N1)), typeD=rep(1,length(auxpos$N2)), r=r, typeEst=typeEst)
return(Kaux)
}
|
d4695debdcd2c182c86ee2ec67ffda640a5ab5d0
|
7a95abd73d1ab9826e7f2bd7762f31c98bd0274f
|
/meteor/inst/testfiles/E_Penman/AFL_E_Penman/E_Penman_valgrind_files/1615918467-test.R
|
fe6bd4d682300e03bf44566f5e02beb2f94bf90d
|
[] |
no_license
|
akhikolla/updatedatatype-list3
|
536d4e126d14ffb84bb655b8551ed5bc9b16d2c5
|
d1505cabc5bea8badb599bf1ed44efad5306636c
|
refs/heads/master
| 2023-03-25T09:44:15.112369
| 2021-03-20T15:57:10
| 2021-03-20T15:57:10
| 349,770,001
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,277
|
r
|
1615918467-test.R
|
testlist <- list(Rext = numeric(0), Rs = numeric(0), Z = numeric(0), alpha = numeric(0), atmp = numeric(0), relh = c(-1.84445564980858e-242, 5.97935653522269e-39, 1.0286791867366e-307, 5.93388628067419e+252, -6.10798253418121e-263, -3.96270958130688, 6.07090976184692e+178, 1.97234986880642e-128, -9.10063427226872e-250, 1.10395557934995e-307, 3.70340327340868e+302, 8.54009096134078e+185, -8.17783303367037e+21, 1.44639722950247e+23, 2.77360665336815e-305, 1.29293007517243e-177, 1.1988711311556e-153, 2.0143677787073e-314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), temp = c(1.06099789548264e-311, 1.60455557047237e+82, -4.51367941637774e-141, -56857994149.4251, 6.32034765431037e-192, 2.3873936536139e+54, -5.55769636213337e+44, -1.09437040829831e+302, 3.28946800994193e-155, -7.26700641004178e+230, -4.27739371871223e-150, -1.66374486455865e-233, 8.91482022514747e+250, 1.20249590583909e-169, -1.25434190571476e-51, 3.47174239177889e+24, 1.34880482498924e-271, 4.13249975462168e+21, 2.02482005430359e+66, 4.40046688773191e+192, 1.10879224935053e-90), u = numeric(0))
result <- do.call(meteor:::E_Penman,testlist)
str(result)
|
c2b89b279048f0c99a56ad2e105f21a43a86481d
|
f8766acedba45c6ab57de62edfd26a53338d976a
|
/Prewhitening.R
|
9de4c84467c3ff65ddf34f89dd6267cfb7362c59
|
[] |
no_license
|
jabranham/brazil
|
1521aedf46ea7633cbaa9bb442800897b4e57bb3
|
4d62221e319265cdc2a0f77f7f89970ecfc6250e
|
refs/heads/master
| 2021-01-15T10:19:04.560501
| 2016-06-14T14:09:38
| 2016-06-14T14:09:38
| 56,794,522
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 581
|
r
|
Prewhitening.R
|
#Prewhitening
library(forecast)
source("run-first.R")
preW.R <- auto.arima(ts(w.list$Proportion.Rousseff), D=0, seasonal=F, ic="bic")
res.R <- residuals(preW.R)
preW.N <- auto.arima(ts(w.list$Proportion.Neves), D=0, seasonal=F, ic="bic")
res.N <- residuals(preW.N)
preW.psb <- auto.arima(ts(w.list$Proportion.PSB), D=0, seasonal=F, ic="bic")
res.psb <- residuals(preW.psb)
preW.dk <- auto.arima(ts(w.list$Proportion.DK), D=0, seasonal=F, ic="bic")
res.dk <- residuals(preW.dk)
preW.O <- auto.arima(ts(w.list$Proportion.Other), D=0, seasonal=F, ic="bic")
res.O <- residuals(preW.O)
|
dc84266b1688a5ae2ade8ca62fef0ff5b9980f94
|
f7f5260f4a084a39bdb30149d1b39ff961bfd55f
|
/private/backend/get_product_sales_sum_by_day.R
|
124403f6620efc38791d2ccb6a7dd7280e3198d8
|
[] |
no_license
|
naroarnold/grocery
|
32764967496f041f7522421415f574b6e52d9a0d
|
feb6cafe9e498baa9ec7d813a2d3bd081ddf5b25
|
refs/heads/master
| 2021-01-15T13:52:25.480811
| 2015-12-02T17:27:20
| 2015-12-02T17:27:20
| 46,244,526
| 0
| 0
| null | 2015-11-16T01:25:51
| 2015-11-16T01:25:50
| null |
UTF-8
|
R
| false
| false
| 405
|
r
|
get_product_sales_sum_by_day.R
|
get_p_daily_sales_avg <- function(product_id,con)
{
#find overall sales of a given product
query <- paste("SELECT store_sales,day_of_month,month_of_year FROM sales_fact_dec_1998_p,time_by_day WHERE product_id = ",product_id,"AND sales_fact_dec_1998_p.time_id = time_by_day.time_id;")
data <- dbGetQuery(con,query)
#calculate the mean
result <- mean(data$store_sales)
return (result)
}
|
f980e47dfa3a49b9ac658d4a04f16090353ea461
|
a4aa93fe9fae6d6218d96188bda72ea793f222f3
|
/plumber.R
|
3ba49458b7cda12c693abe4eac2bff82e70c37dc
|
[] |
no_license
|
ratnexa/plumber-test
|
d4cf6829ba57ed1d72c94c5b59556da007a2143a
|
34eafa595d36c66501bdfd216ed05c530e6141da
|
refs/heads/master
| 2022-12-08T04:35:05.557154
| 2020-09-03T19:13:08
| 2020-09-03T19:13:08
| 292,612,564
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 900
|
r
|
plumber.R
|
library(caret)
library(httr)
library(magrittr)
library(plumber)
library(tidyverse)
# plumber.R
# Read model data.
# model.list <- readRDS(file = 'model_list.rds')
#* @param wt
#* @param qsec
#* @param am
#* @post /predict
# CalculatePrediction <- function(wt, qsec, am){
# wt %<>% as.numeric
# qsec %<>% as.numeric
# am %<>% as.numeric
#
# x.new <- tibble(wt = wt, qsec = qsec, am = am)
# y.pred <- model.list$GetNewPredictions(model = model.list$model.obj,
# transformer = model.list$scaler.obj,
# newdata = x.new)
#
# return(y.pred)
# }
#* @param a
#* @param b
#* @param c
#* @post /sum
sumSantiago <- function(a, b, c){
a %<>% as.numeric
b %<>% as.numeric
c %<>% as.numeric
#result <- a + b + c
result <- data.frame(a,b,c)
return(result)
}
#CalculatePrediction(1, 16.2, 23)
|
cc57fde2c86e26ffc97a0cab012a9cc2ac1337f8
|
13c6a1a108ffd9edc98bbbd0287c503b484db2f3
|
/man/qqANOVA.Rd
|
7a76906610a83d2828e91535a017199ff6b47f8e
|
[] |
no_license
|
cran/MPV
|
81f894f2ecca63c391037ea8dc6033dbc7b57d98
|
b757e5149d3b29c0a8f20cc4315acec17a27693b
|
refs/heads/master
| 2023-03-03T14:14:08.549709
| 2023-02-26T02:40:02
| 2023-02-26T02:40:02
| 17,680,727
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 783
|
rd
|
qqANOVA.Rd
|
\name{qqANOVA}
\alias{qqANOVA}
\title{
QQ Plot for Analysis of Variance
}
\description{ This function is used to display the weight of the
evidence against null main effects in data coming from a 1 factor
design, using a QQ plot. In practice this method is often called via
the function GANOVA.
}
\usage{
qqANOVA(x, y, plot.it = TRUE, xlab = deparse(substitute(x)),
ylab = deparse(substitute(y)), ...)
}
\arguments{
\item{x}{numeric vector of errors}
\item{y}{numeric vector of scaled responses}
\item{plot.it}{logical vector indicating whether to plot
or not}
\item{xlab}{character, x-axis label}
\item{ylab}{character, y-axis label}
\item{...}{any other arguments for the plot function}
}
\value{A QQ plot is drawn.}
\author{
W. John Braun
}
\keyword{graphics}
|
7e3116e2dff9a91758e8320071406ccfac5f6f94
|
17205acfbd00aeb7edf976966f251698c5ae2458
|
/GpOutput2D.Rcheck/00_pkg_src/GpOutput2D/man/Inverse2D.OrthoNormalBsplines2D.Rd
|
1fe579fe6bcd0bcf70cc439accae12191a93ca87
|
[] |
no_license
|
tranvivielodie/GpOutput2D
|
148be512b5ecd99fba7d105fa3171d8c86d531fd
|
9f779d33fb86f8bff8b3da3db4845c37b3045f75
|
refs/heads/main
| 2023-03-04T19:28:27.694988
| 2021-02-18T10:11:00
| 2021-02-18T10:11:00
| 316,458,801
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 828
|
rd
|
Inverse2D.OrthoNormalBsplines2D.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/OrthoNormalBsplines2D_utils.R
\name{Inverse2D.OrthoNormalBsplines2D}
\alias{Inverse2D.OrthoNormalBsplines2D}
\title{Inverse transform of control points of two-dimensional B-splines basis}
\usage{
\method{Inverse2D}{OrthoNormalBsplines2D}(object, coeff, ...)
}
\arguments{
\item{object}{an object of class \code{\link{OrthoNormalBsplines2D}}
with functions of the B-splines basis.}
\item{coeff}{matrix with control points on two-dimensional B-splines basis.}
\item{...}{other arguments.}
}
\value{
an array with two-dimensional approximated data.
}
\description{
Inverse transform of control points of two-dimensional B-splines basis
}
\seealso{
\code{\link{coef.OrthoNormalBsplines2D}} \code{\link{OrthoNormalBsplines2D}}
\code{\link{Inverse2D}}
}
|
8c40caaf703420657ad2e1365207a9ac78f36f68
|
7e78610eba99aab8b7f7abb7e8d2520c681aa0e5
|
/medidas_resumo.R
|
6eb7e1a03efca41a99b044e5ea333f91556fe14f
|
[] |
no_license
|
joaohmorais/garu-estatistica
|
69eed5db648c66e84f97aff0d40e61a5b85f6b2f
|
c125c6baffc625499f8087838de033980084608e
|
refs/heads/master
| 2020-05-25T20:09:30.926790
| 2019-07-25T21:26:39
| 2019-07-25T21:26:39
| 187,968,563
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 9,358
|
r
|
medidas_resumo.R
|
library(shinyjs)
medidas_resumo <- fluidPage(
title = "Medidas Resumo",
useShinyjs(),
withMathJax(),
fluidRow(
column(6,
h4(strong("Gerador de Elementos")),
p("Gere uma amostra de elementos (números) através dos parâmetros e do botão 'Gerar Elementos'. Depois
acompanhe como suas medidas resumo são calculadas."),
verbatimTextOutput("printElementos"),
fluidRow(
column(4,
sliderInput("slider_qtd_elementos", label = "Quantidade de Elementos (Tamanho da Amostra)", min = 4,
max = 40, value = 10)),
column(4,
sliderInput("slider_min_max_valor", label = "Valores entre:", min = 1, max = 50, value = c(1, 10))),
column(2,
actionButton("geraElementos", "Gerar Elementos"))
),
plotOutput("graficoElementos")
),
column(6,
fluidRow(
column(6,
wellPanel(htmlOutput("mediaTitle"),
actionLink("mediaMostrarMais", "Mostrar mais"),
hidden(actionLink("mediaMostrarMenos", "Mostrar menos")),
hidden(p("A média aritmética, medida mais familiar, é a soma dos valores das
observações dividido pela quantidade de observações.", id = "mediaTexto")),
hidden(uiOutput("mediaExplain")),
hidden(helpText(id="htMedia", "Exemplo com os elementos gerados:"),
verbatimTextOutput("exMedia"))
)),
column(6, wellPanel(htmlOutput("medianaTitle"),
actionLink("medianaMostrarMais", "Mostrar mais"),
hidden(actionLink("medianaMostrarMenos", "Mostrar menos")),
hidden(p("A mediana representa a observação que ocupa a metade da lista
de observações, quando essa está ordenada. Quando o conjunto
possui um número ímpar de observações, então a mediana é
simplesmente o valor central. Caso contrário, é feita a média
dos dois valores centrais.", id = "medianaTexto")),
hidden(uiOutput("medianaExplain")),
hidden(helpText(id="htMediana", "Exemplo com os elementos gerados:"),
verbatimTextOutput("exMediana"))
))
),
fluidRow(
column(6,
wellPanel(htmlOutput("modaTitle"),
actionLink("modaMostrarMais", "Mostrar mais"),
hidden(actionLink("modaMostrarMenos", "Mostrar menos")),
hidden(p("A moda é representada pela observação mais frequente do conjunto. Ou
seja, o valor que aparece mais vezes. Em alguns casos, pode-se ter mais
de uma moda.", id = "modaTexto")),
hidden(helpText(id="htModa", "Exemplo com os elementos gerados:"),
verbatimTextOutput("exModa"))
)),
column(6, wellPanel(htmlOutput("minimoTitle"),
actionLink("minimoMostrarMais", "Mostrar mais"),
hidden(actionLink("minimoMostrarMenos", "Mostrar menos")),
hidden(p("Observação de menor valor.", id = "minimoTexto")),
hidden(helpText(id="htMinimo", "Exemplo com os elementos gerados:"),
verbatimTextOutput("exMinimo"))
))
),
fluidRow(
column(6,
wellPanel(htmlOutput("maximoTitle"),
actionLink("maximoMostrarMais", "Mostrar mais"),
hidden(actionLink("maximoMostrarMenos", "Mostrar menos")),
hidden(p("Observação de maior valor.", id = "maximoTexto")),
hidden(helpText(id="htMaximo", "Exemplo com os elementos gerados:"),
verbatimTextOutput("exMaximo"))
)),
column(6, wellPanel(htmlOutput("varianciaTitle"),
actionLink("varianciaMostrarMais", "Mostrar mais"),
hidden(actionLink("varianciaMostrarMenos", "Mostrar menos")),
HTML("<p id='varianciaTexto' class='shinyjs-hide'>Em alguns casos, medidas como média, moda e mediana podem não nos trazer
informações suficientes sobre o conjunto de observações. Afinal,
as medidas anteriores são <strong>medidas de posição</strong>. É interessente
analisarmos <strong>medidas de dispersão</strong>, como a variância. Esta representa
o quão desviados os dados estão de sua média. Para isso, precisamos
calcular a distância de cada elemento da média, somar o quadrado dessas
distâncias e dividir pelo número de observações. </p>"),
hidden(uiOutput("varianciaExplain")),
hidden(helpText(id="htVariancia", "Exemplo com os elementos gerados:"),
verbatimTextOutput("exVariancia"))
))
),
fluidRow(
column(6,
wellPanel(htmlOutput("dpTitle"),
actionLink("dpMostrarMais", "Mostrar mais"),
hidden(actionLink("dpMostrarMenos", "Mostrar menos")),
hidden(p("O desvio padrão também é uma medida clássica de dispersão.
Em termos de cálculo, ele se dá pela raiz quadrada da variância do
conjunto. A vantagem que ele apresenta sobre a variância é a possibilidade
de uma interpretação direta, uma vez que ele está na mesma unidade que a variável
(kg, m, cm, etc.).", id = "dpTexto")),
hidden(uiOutput("dpExplain")),
hidden(helpText(id="htDp", "Exemplo com os elementos gerados:"),
verbatimTextOutput("exDp"))
)),
column(6, wellPanel(htmlOutput("epTitle"),
actionLink("epMostrarMais", "Mostrar mais"),
hidden(actionLink("epMostrarMenos", "Mostrar menos")),
hidden(p("Quando tratamos de população e amostras, o erro padrão é utilizado
como uma medida de variação entre a média da amostra e a média da
população. Ou seja, é uma medida que ajuda a calcular a confiabilidade
da amostra e da média amostral calculada. Para obtê-lo, basta dividir o
desvio padrão pela raiz quadrada do tamanho amostral.", id = "epTexto")),
hidden(uiOutput("epExplain")),
hidden(helpText(id="htEp", "Exemplo com os elementos gerados:"),
verbatimTextOutput("exEp"))
))
),
fluidRow(
column(6,
wellPanel(htmlOutput("quantilTitle"),
actionLink("quantilMostrarMais", "Mostrar mais"),
hidden(actionLink("quantilMostrarMenos", "Mostrar menos")),
hidden(p("Foi dito acima que a mediana é a medida que divide os valores do conjunto,
deixando metade deles abaixo e metade acima. Um quantil é uma generalização dessa
ideia, onde define-se uma proporção p, 0 < p < 1, cujo p-quantil divide o conjunto
deixando 100p% das observações abaixo dele.", id = "quantilTexto")),
hidden(uiOutput("quantilExplain")),
hidden(helpText(id="htQuantil", "Exemplo com os elementos gerados:"),
verbatimTextOutput("exQuantil"))
)),
column(6,
helpText("Fonte: Morettin, P. and Bussab, W. (2000). Estatística Básica (7a. ed.). Editora Saraiva."))
)
)
)
)
|
9a76d27265abc0b6c491e803b2eed412ab3a1553
|
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
|
/fuzzedpackages/tokenizers/tests/testthat/test-encoding.R
|
643f99dc21dcad08dc716691574744edc924d1b0
|
[] |
no_license
|
akhikolla/testpackages
|
62ccaeed866e2194652b65e7360987b3b20df7e7
|
01259c3543febc89955ea5b79f3a08d3afe57e95
|
refs/heads/master
| 2023-02-18T03:50:28.288006
| 2021-01-18T13:23:32
| 2021-01-18T13:23:32
| 329,981,898
| 7
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 667
|
r
|
test-encoding.R
|
context("Encodings")
test_that("Encodings work on Windows", {
input <- "César Moreira Nuñez"
reference <- c("césar", "moreira", "nuñez")
reference_enc <- c("UTF-8", "unknown", "UTF-8")
output_n1 <- tokenize_ngrams(input, n = 1, simplify = TRUE)
output_words <- tokenize_words(input, simplify = TRUE)
output_skip <- tokenize_skip_ngrams(input, n = 1, k = 0, simplify = TRUE)
expect_equal(output_n1, reference)
expect_equal(output_words, reference)
expect_equal(output_skip, reference)
expect_equal(Encoding(output_n1), reference_enc)
expect_equal(Encoding(output_words), reference_enc)
expect_equal(Encoding(output_skip), reference_enc)
})
|
957abeadf9f99e966723e088eed04948d60f0c10
|
fea71570dc6786eb56eb1b3faf0c282b908f96fc
|
/server.R
|
e3aaf82e185198292fd0738527b8fe37ec483d73
|
[] |
no_license
|
turgeonmaxime/tavi_demand
|
51c6b820362d79de909440a10cef6955e8af3624
|
a5a2512ba6e1238ab6b160e4b870312b9a7be3a5
|
refs/heads/master
| 2020-03-22T22:15:46.987367
| 2018-07-12T17:05:41
| 2018-07-12T17:05:41
| 140,742,552
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,570
|
r
|
server.R
|
# Define server logic required to draw a histogram
library(tidyverse)
n_years <- 25
baseline_pop <- 36065
server <- function(input, output) {
y_lim <- reactive({
if (input$sts > 45 &&
input$symp > 75 &&
input$savs > 5) c(0, 1500) else if (input$savs > 5) c(0, 1000) else c(0, 800)
})
dataset <- reactive({
rate <- switch(input$growth,
"Low" = 1.01,
"Medium" = 1.0125,
"High" = 1.015)
# create data
eligible_pop <- round(baseline_pop * (input$savs/100) *
(input$symp/100) * (input$sts/100))
y <- seq_len(n_years) + 2016L
x1 <- round(eligible_pop * (rate)^seq_len(n_years))
x2 <- c(cumsum(rep(25, n_years)))
x3 <- cumsum(c(seq(25, 50, by = 5),
rep(50, n_years - 6)))
x4 <- cumsum(c(seq(25, 150, by = 25),
rep(150, n_years - 6)))
# create dataframe
dataset <- bind_rows(
tibble::tibble(
Year = y,
CumCases = x2,
Target = x1
) %>% mutate(Method = "Current"),
tibble::tibble(
Year = y,
CumCases = x3,
Target = x1
) %>% mutate(Method = "5 incr."),
tibble::tibble(
Year = y,
CumCases = x4,
Target = x1
) %>% mutate(Method = "25 incr.")
) %>%
mutate(CumCases = pmin(CumCases, Target))
})
output$plot <- renderPlot({
# Plot graph
dataset() %>%
ggplot(aes(x = Year)) +
geom_line(aes(y = CumCases, colour = Method),
size = 1) +
geom_line(aes(y = Target), size = 1.5) +
theme_bw() + theme(legend.position = 'top',
text = element_text(size = 20)) +
geom_vline(xintercept = 2022L, linetype = 2) +
ylab("Cumulative TAVIs since 2016") +
scale_colour_manual(values = c("#898d8e", "#c80f2e",
"#026936")) +
coord_cartesian(ylim = y_lim())
})
output$table <- renderTable({
# Percentage caught up with demand by 2022
percent_cup <- dataset() %>%
filter(Year == 2022L) %>%
group_by(Method) %>%
transmute(Percent = CumCases/Target)
# When will we be caught up?
date_cup <- dataset() %>%
filter(CumCases == Target) %>%
group_by(Method) %>%
summarise(Year = min(Year, na.rm = TRUE))
full_join(date_cup, percent_cup,
by = 'Method') %>%
mutate(Year = as.integer(Year),
Percent = scales::percent(Percent))
})
}
|
edc9f80946790d811a4808c20e1e6fe63698ee8b
|
648c3c15a9d15da278c1d17c27d34e487353400c
|
/a_Archive/for Beisit.R
|
05ba8bb4439db215bf423d51ff7ca91c63d89b8d
|
[] |
no_license
|
OxfordEcosystemsLab/GEMcarbon.R
|
c50c485ef27664b8b2b0d5cd4364b082630e70f3
|
bddd26fcd3e9909bbb9ca730838541d48d3da5d0
|
refs/heads/master
| 2020-04-07T05:39:38.683573
| 2018-12-12T13:01:29
| 2018-12-12T13:01:29
| 18,173,751
| 5
| 6
| null | null | null | null |
UTF-8
|
R
| false
| false
| 37,465
|
r
|
for Beisit.R
|
> setwd("/Users/cecile/Dropbox/GEMcarbondb/db_csv/db_csv_2015/readyforupload_db/acj_pan_2015")
> census_ACJ01 <- read.table("ACJcensus_clean_date.csv", header=TRUE, sep=",", na.strings=c("NA", "NaN", ""), dec=".", strip.white=TRUE)
> head(census_ACJ01)
X.1 Tag.No Old.No T1 T2 X Y Family genus species Old.Tree.Notes D..2013.1 POM..2013.1 F1..2013.1 F2..2013.1 Height..2013.1 F5..2013.1
1 1 1 NA 1 NA NA NA Symplocaceae Symplocos quitensis <NA> 129 1300 a 1 8.0 4
2 2 2 NA 1 NA NA NA Cunoniaceae Weinmannia cochensis <NA> 234 1300 a 1 8.4 4
3 3 3 NA 1 2 NA NA Cunoniaceae Weinmannia cochensis <NA> 119 1300 a 1 7.0 4
4 4 4 NA 1 NA NA NA Cunoniaceae Weinmannia cochensis <NA> 134 1300 a 1 8.5 4
5 5 5 NA 1 NA NA NA Rosaceae Polylepis pauta <NA> 312 1300 a 1 9.0 4
6 6 6 NA 1 NA NA NA Cunoniaceae Weinmannia cochensis <NA> 128 1300 a 1 7.0 4
F3..2013.1 F4..2013.1 LI..2013.1 CI..2013.1 Census.Notes..2013.1 D..2014.2 POM..2014.2 F1 F2 Height..2014.2 F5 F3 F4 LI..2014.2 CI..2014.2 Tree.ID
1 0 0 0 1 NA 130 1300 a 1 NA NA 0 0 NA NA 1105383
2 0 0 0 1 NA 234 1300 ah 1 NA NA 0 0 NA NA 1105384
3 0 0 0 1 NA 112 1300 ah 1 NA NA 0 0 NA NA 1105385
4 0 0 0 1 NA 131 1300 c 1 NA NA 0 0 NA NA 1105386
5 0 0 0 1 NA 317 1300 c 1 NA NA 0 0 NA NA 1105387
6 0 0 0 1 NA 131 1300 c 1 NA NA 0 0 NA NA 1105388
D..2015.1 POM..2015.1 F1.1 F2.1 Height..2015.1 F5.1 F3.1 F4.1 LI..2015.1 CI..2015.1 Census.Notes Tree.ID.1 New.Tag.No wdensity height density tag
1 132 1300 m 1 7000 NA 0 0 2 3b <NA> 1105383 NA 0.5745640 7.50 0.5745640 1
2 268 1300 ah 1 7000 NA 0 0 0 3b <NA> 1105384 NA 0.6392357 7.70 0.6392357 2
3 115 1300 ah 1 7000 NA 0 0 0 3a <NA> 1105385 NA 0.6392357 7.00 0.6392357 3
4 130 1300 c 1 8000 NA 0 0 1 3a <NA> 1105386 NA 0.6392357 8.25 0.6392357 4
5 327 1300 c 1 10000 NA 0 0 0 3b <NA> 1105387 NA 0.6697630 9.50 0.6697630 5
6 131 1300 c 1 8000 NA 0 0 0 2a <NA> 1105388 NA 0.6392357 7.50 0.6392357 6
plot DBH.1 DBH.2 DBH.3 dbh_growth_yr recruits srink missing overgrown value_replaced
1 ACJ-01 12.9 13.0 13.2 0.08752998 ok ok ok ok NA
2 ACJ-01 23.4 23.4 26.8 0.00000000 ok ok ok ok NA
3 ACJ-01 11.9 11.2 11.5 -0.61270983 ok ok ok ok NA
4 ACJ-01 13.4 13.1 13.0 -0.26258993 ok ok ok ok NA
5 ACJ-01 31.2 31.7 32.7 0.43764988 ok ok ok ok NA
6 ACJ-01 12.8 13.1 13.1 0.26258993 ok ok ok ok NA
> data <- subset(census_ACJ01, plot=="ACJ-01")
> date_1 <- as.character("2013/01/22") # 22 de Enero 2013
> date_2 <- as.character("2014/03/15") # 15 de Marzo 2014
> date_3 <- as.character("2015/03/16") # 16 de Marzo 2015
> date_1 <- as.Date(format(strptime(date_1, format="%Y/%m/%d")))
> date_2 <- as.Date(format(strptime(date_2, format="%Y/%m/%d")))
> date_3 <- as.Date(format(strptime(date_3, format="%Y/%m/%d")))
> census_interval_1 <- as.numeric(difftime(date_2, date_1, units="days"))
> census_interval_yrs_1 <- census_interval_1/365
> census_interval_2 <- as.numeric(difftime(date_3, date_2, units="days"))
> census_interval_yrs_2 <- census_interval_2/365
> data$dbh_growth_yr <- (data$DBH.2 - data$DBH.1)/census_interval_yrs_1
> gr_sd <- sd(data$dbh_growth_yr, na.rm=T)
> plot1 <- ggplot(data=data, aes(x=DBH.1, y=dbh_growth_yr, na.rm=T)) +
+ geom_point() +
+ ylim(-10, 10) +
+ ggtitle(data$plot)
> plot1
Warning message:
Removed 7 rows containing missing values (geom_point).
> w = which(is.na(data$DBH.1) & !is.na(data$DBH.2))
> data$DBH.2[w] = 0/0
> data$recruits <- "ok"
> data$recruits[w] <- "recruit"
> w = which(is.na(data$DBH.1) & is.na(data$DBH.2) & !is.na(data$DBH.3))
> data$DBH.3[w] = 0/0
> data$recruits[w] <- "recruit"
> w = which(data$DBH.1 > data$DBH.2 + (data$DBH.1*0.1))
> data$DBH.2[w] = data$DBH.1[w]
> data$srink <- "ok"
> data$srink[w] <- "shrunk.dbh.2"
> w = which(data$DBH.2 > data$DBH.3 + (data$DBH.2*0.1))
> data$DBH.3[w] = data$DBH.2[w]
> data$srink[w] <- "shrunk.dbh.3"
> w = which(!is.na(data$DBH.1) & is.na(data$DBH.2) & !is.na(data$DBH.3))
> data$DBH.2[w] = (data$DBH.1[w] + data$DBH.3[w])/2 # mean rather than meadian flag this as 8 - see RAINFOR flags.
> data$missing <- "ok"
> data$missing[w] <- "missing"
> maxincrement_1 <- 5 * census_interval_yrs_1 #(3*gr_sd)
> maxincrement_2 <- 5 * census_interval_yrs_2 #(3*gr_sd)
> w = which((data$DBH.2 - data$DBH.1) >= maxincrement_1)
> data$overgrown <- "ok"
> data$overgrown[w] <- ">2cm growth per yr dbh.2"
> data$value_replaced <- NA
> data$value_replaced[w] <- data$DBH.2[w]
> data$DBH.2[w] = (data$DBH.1[w] + maxincrement_1)
> w = which((data$DBH.3 - data$DBH.2) >= maxincrement_2)
> data$overgrown[w] <- ">2cm growth per yr dbh.3"
> data$value_replaced[w] <- data$DBH.3[w]
> data$DBH.3[w] = (data$DBH.2[w] + maxincrement_2)
> n_occur <- data.frame(table(data$tag))
> n_occur[n_occur$Freq > 1,]
[1] Var1 Freq
<0 rows> (or 0-length row.names)
> data[data$tag %in% n_occur$Var1[n_occur$Freq > 1],]
[1] X.1 Tag.No Old.No T1 T2 X
[7] Y Family genus species Old.Tree.Notes D..2013.1
[13] POM..2013.1 F1..2013.1 F2..2013.1 Height..2013.1 F5..2013.1 F3..2013.1
[19] F4..2013.1 LI..2013.1 CI..2013.1 Census.Notes..2013.1 D..2014.2 POM..2014.2
[25] F1 F2 Height..2014.2 F5 F3 F4
[31] LI..2014.2 CI..2014.2 Tree.ID D..2015.1 POM..2015.1 F1.1
[37] F2.1 Height..2015.1 F5.1 F3.1 F4.1 LI..2015.1
[43] CI..2015.1 Census.Notes Tree.ID.1 New.Tag.No wdensity height
[49] density tag plot DBH.1 DBH.2 DBH.3
[55] dbh_growth_yr recruits srink missing overgrown value_replaced
<0 rows> (or 0-length row.names)
> data[is.na(data)] <- NA
> dataACJ01 <- data
> head(dataACJ01)
X.1 Tag.No Old.No T1 T2 X Y Family genus species Old.Tree.Notes D..2013.1 POM..2013.1 F1..2013.1 F2..2013.1
1 1 1 NA 1 NA NA NA Symplocaceae Symplocos quitensis <NA> 129 1300 a 1
2 2 2 NA 1 NA NA NA Cunoniaceae Weinmannia cochensis <NA> 234 1300 a 1
3 3 3 NA 1 2 NA NA Cunoniaceae Weinmannia cochensis <NA> 119 1300 a 1
4 4 4 NA 1 NA NA NA Cunoniaceae Weinmannia cochensis <NA> 134 1300 a 1
5 5 5 NA 1 NA NA NA Rosaceae Polylepis pauta <NA> 312 1300 a 1
6 6 6 NA 1 NA NA NA Cunoniaceae Weinmannia cochensis <NA> 128 1300 a 1
Height..2013.1 F5..2013.1 F3..2013.1 F4..2013.1 LI..2013.1 CI..2013.1 Census.Notes..2013.1 D..2014.2 POM..2014.2 F1 F2
1 8.0 4 0 0 0 1 NA 130 1300 a 1
2 8.4 4 0 0 0 1 NA 234 1300 ah 1
3 7.0 4 0 0 0 1 NA 112 1300 ah 1
4 8.5 4 0 0 0 1 NA 131 1300 c 1
5 9.0 4 0 0 0 1 NA 317 1300 c 1
6 7.0 4 0 0 0 1 NA 131 1300 c 1
Height..2014.2 F5 F3 F4 LI..2014.2 CI..2014.2 Tree.ID D..2015.1 POM..2015.1 F1.1 F2.1 Height..2015.1 F5.1 F3.1 F4.1 LI..2015.1
1 NA NA 0 0 NA NA 1105383 132 1300 m 1 7000 NA 0 0 2
2 NA NA 0 0 NA NA 1105384 268 1300 ah 1 7000 NA 0 0 0
3 NA NA 0 0 NA NA 1105385 115 1300 ah 1 7000 NA 0 0 0
4 NA NA 0 0 NA NA 1105386 130 1300 c 1 8000 NA 0 0 1
5 NA NA 0 0 NA NA 1105387 327 1300 c 1 10000 NA 0 0 0
6 NA NA 0 0 NA NA 1105388 131 1300 c 1 8000 NA 0 0 0
CI..2015.1 Census.Notes Tree.ID.1 New.Tag.No wdensity height density tag plot DBH.1 DBH.2 DBH.3 dbh_growth_yr recruits
1 3b <NA> 1105383 NA 0.5745640 7.50 0.5745640 1 ACJ-01 12.9 13.0 13.2 0.08752998 ok
2 3b <NA> 1105384 NA 0.6392357 7.70 0.6392357 2 ACJ-01 23.4 23.4 26.8 0.00000000 ok
3 3a <NA> 1105385 NA 0.6392357 7.00 0.6392357 3 ACJ-01 11.9 11.2 11.5 -0.61270983 ok
4 3a <NA> 1105386 NA 0.6392357 8.25 0.6392357 4 ACJ-01 13.4 13.1 13.0 -0.26258993 ok
5 3b <NA> 1105387 NA 0.6697630 9.50 0.6697630 5 ACJ-01 31.2 31.7 32.7 0.43764988 ok
6 2a <NA> 1105388 NA 0.6392357 7.50 0.6392357 6 ACJ-01 12.8 13.1 13.1 0.26258993 ok
srink missing overgrown value_replaced
1 ok ok ok NA
2 ok ok ok NA
3 ok ok ok NA
4 ok ok ok NA
5 ok ok ok NA
6 ok ok ok NA
> eltrcensus <- dataACJ01
> yearDAP1 <- c()
> monthDAP1 <- c()
> dayDAP1 <- c()
> for (ii in 1:(length(eltrcensus$plot))) { # length(eltrcensus$plot) is equivalent to nrow(eltrcensus)
+ yeartmp = NA
+ monthtmp = NA
+ daytmp = NA
+ # cat("At row",i,"=",eltrcensus$plot[i]) # this is to print the number of row and the value in that row
+ if (as.character(eltrcensus$plot[ii]) == "ACJ-01") {
+ yeartmp = 2013
+ monthtmp = 01
+ daytmp = 22
+ }
+ if (as.character(eltrcensus$plot[ii]) == "PAN-02") {
+ yeartmp = 2013
+ monthtmp = 04
+ daytmp = 12
+ }
+ if (as.character(eltrcensus$plot[ii]) == "PAN-03") {
+ yeartmp = 2013
+ monthtmp = 03
+ daytmp = 30
+ }
+ if (as.character(eltrcensus$plot[ii]) == "TRU-04") {
+ yeartmp = 2003
+ monthtmp = 07
+ daytmp = 14
+ }
+ yearDAP1 = c(yearDAP1,yeartmp)
+ monthDAP1 = c(monthDAP1,monthtmp)
+ dayDAP1 = c(dayDAP1,daytmp)
+ datesDAP1 = data.frame(yearDAP1, monthDAP1, dayDAP1)
+ datesDAP1 = data.frame(datesDAP1[1,], eltrcensus$plot, row.names = NULL) # Make sure this is the right number of rows.
+ colnames(datesDAP1) <- c("year", "month", "day", "plot")
+ }
>
> # 2nd census
> yearDAP2 <- NULL # same as yearDAP2 = c()
> monthDAP2 <- NULL
> dayDAP2 <- NULL
> for (ii in 1:(length(eltrcensus$plot))) { #length(eltrcensus$plot) is equivalent to nrow(eltrcensus)
+ yeartmp = NA
+ monthtmp = NA
+ daytmp = NA
+ # cat("At row",i,"=",eltrcensus$plot[i]) this is to print the number of row and the value in that row
+ if (as.character(eltrcensus$plot[ii]) == "ACJ-01") {
+ yeartmp = 2014
+ monthtmp = 03
+ daytmp = 15
+ }
+ if (as.character(eltrcensus$plot[ii]) == "PAN-02") {
+ yeartmp = 2015
+ monthtmp = 03
+ daytmp = 02
+ }
+ if (as.character(eltrcensus$plot[ii]) == "PAN-03") {
+ yeartmp = 2014
+ monthtmp = 03
+ daytmp = 02
+ }
+ if (as.character(eltrcensus$plot[ii]) == "TRU-04") {
+ yeartmp = 2007
+ monthtmp = 06
+ daytmp = 08
+ }
+ yearDAP2 = c(yearDAP2,yeartmp)
+ monthDAP2 = c(monthDAP2,monthtmp)
+ dayDAP2 = c(dayDAP2,daytmp)
+ datesDAP2 = data.frame(yearDAP2, monthDAP2, dayDAP2)
+ datesDAP2 = data.frame(datesDAP2[1,], eltrcensus$plot, row.names = NULL)
+ colnames(datesDAP2) <- c("year", "month", "day", "plot")
+ }
>
> # 3rd census
> yearDAP3 <- NULL # same as yearDAP2 = c()
> monthDAP3 <- NULL
> dayDAP3 <- NULL
> for (ii in 1:(length(eltrcensus$plot))) { #length(eltrcensus$plot) is equivalent to nrow(eltrcensus)
+ yeartmp = NA
+ monthtmp = NA
+ daytmp = NA
+ # cat("At row",i,"=",eltrcensus$plot[i]) this is to print the number of row and the value in that row
+ if (as.character(eltrcensus$plot[ii]) == "ACJ-01") {
+ yeartmp = 2015
+ monthtmp = 03
+ daytmp = 16
+ }
+ #if (as.character(eltrcensus$plot[ii]) == "PAN-02") {
+ # yeartmp = 2015
+ # monthtmp = 03
+ # daytmp = 02
+ #}
+ if (as.character(eltrcensus$plot[ii]) == "PAN-03") {
+ yeartmp = 2015
+ monthtmp = 03
+ daytmp = 04
+ }
+ if (as.character(eltrcensus$plot[ii]) == "TRU-04") {
+ yeartmp = 2011
+ monthtmp = 07
+ daytmp = 30
+ }
+ yearDAP3 = c(yearDAP3,yeartmp)
+ monthDAP3 = c(monthDAP3,monthtmp)
+ dayDAP3 = c(dayDAP3,daytmp)
+ datesDAP3 = data.frame(yearDAP3, monthDAP3, dayDAP3)
+ datesDAP3 = data.frame(datesDAP3[1,], eltrcensus$plot, row.names = NULL)
+ colnames(datesDAP3) <- c("year", "month", "day", "plot")
+ }
> eltrcen1 <- data.frame(plot_code=eltrcensus$plot, tree_tag=eltrcensus$tag, dbh=eltrcensus$DBH.1, height_m=eltrcensus$height, density=eltrcensus$density, datesDAP1)
> head(eltrcen1)
plot_code tree_tag dbh height_m density year month day plot
1 ACJ-01 1 12.9 7.50 0.5745640 2013 1 22 ACJ-01
2 ACJ-01 2 23.4 7.70 0.6392357 2013 1 22 ACJ-01
3 ACJ-01 3 11.9 7.00 0.6392357 2013 1 22 ACJ-01
4 ACJ-01 4 13.4 8.25 0.6392357 2013 1 22 ACJ-01
5 ACJ-01 5 31.2 9.50 0.6697630 2013 1 22 ACJ-01
6 ACJ-01 6 12.8 7.50 0.6392357 2013 1 22 ACJ-01
> eltrcen2 <- data.frame(plot_code=eltrcensus$plot, tree_tag=eltrcensus$tag, dbh=eltrcensus$DBH.2, height_m=eltrcensus$height, density=eltrcensus$density, datesDAP2)
> head(eltrcen2)
plot_code tree_tag dbh height_m density year month day plot
1 ACJ-01 1 13.0 7.50 0.5745640 2014 3 15 ACJ-01
2 ACJ-01 2 23.4 7.70 0.6392357 2014 3 15 ACJ-01
3 ACJ-01 3 11.2 7.00 0.6392357 2014 3 15 ACJ-01
4 ACJ-01 4 13.1 8.25 0.6392357 2014 3 15 ACJ-01
5 ACJ-01 5 31.7 9.50 0.6697630 2014 3 15 ACJ-01
6 ACJ-01 6 13.1 7.50 0.6392357 2014 3 15 ACJ-01
> eltrcen3 <- data.frame(plot_code=eltrcensus$plot, tree_tag=eltrcensus$tag, dbh=eltrcensus$DBH.3, height_m=eltrcensus$height, density=eltrcensus$density, datesDAP3)
> head(eltrcen3)
plot_code tree_tag dbh height_m density year month day plot
1 ACJ-01 1 13.2 7.50 0.5745640 2015 3 16 ACJ-01
2 ACJ-01 2 26.8 7.70 0.6392357 2015 3 16 ACJ-01
3 ACJ-01 3 11.5 7.00 0.6392357 2015 3 16 ACJ-01
4 ACJ-01 4 13.0 8.25 0.6392357 2015 3 16 ACJ-01
5 ACJ-01 5 32.7 9.50 0.6697630 2015 3 16 ACJ-01
6 ACJ-01 6 13.1 7.50 0.6392357 2015 3 16 ACJ-01
> census <- rbind(eltrcen1, eltrcen2)#, eltrcen3)
> census$height_m <- as.numeric(census$height_m)
> sapply(census, class)
plot_code tree_tag dbh height_m density year month day plot
"factor" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "factor"
> head(census)
plot_code tree_tag dbh height_m density year month day plot
1 ACJ-01 1 12.9 7.50 0.5745640 2013 1 22 ACJ-01
2 ACJ-01 2 23.4 7.70 0.6392357 2013 1 22 ACJ-01
3 ACJ-01 3 11.9 7.00 0.6392357 2013 1 22 ACJ-01
4 ACJ-01 4 13.4 8.25 0.6392357 2013 1 22 ACJ-01
5 ACJ-01 5 31.2 9.50 0.6697630 2013 1 22 ACJ-01
6 ACJ-01 6 12.8 7.50 0.6392357 2013 1 22 ACJ-01
> tail(census)
plot_code tree_tag dbh height_m density year month day plot
1721 ACJ-01 851 11.1 5.0 0.7332520 2014 3 15 ACJ-01
1722 ACJ-01 852 16.4 10.0 0.5400146 2014 3 15 ACJ-01
1723 ACJ-01 853 16.4 2.5 0.5745640 2014 3 15 ACJ-01
1724 ACJ-01 854 11.9 2.5 0.5745640 2014 3 15 ACJ-01
1725 ACJ-01 855 25.6 13.0 0.5400146 2014 3 15 ACJ-01
1726 ACJ-01 856 44.4 13.5 0.5400146 2014 3 15 ACJ-01
> sapply(census, class)
plot_code tree_tag dbh height_m density year month day plot
"factor" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "factor"
> setwd("/Users/cecile/GitHub/GEMcarbon.R")
> dir()
[1] "ACJ_carboncycle_2015.R" "Archive"
[3] "EGM_raw_to_flux_option1.R" "EGM_raw_to_flux_stem_2015.R"
[5] "GEM_carbon.R" "NPPacw_census_function_2015.R"
[7] "NPPacw_dendro_function_2015.R" "NPPacw_step1_reformatting_census_2015.R"
[9] "NPProot_2015.R" "SAFE_IngrowthCores_Rcode_toCecile_2.txt"
[11] "allometric_equations_2014.R" "coarsewoodNPP.R"
[13] "coarsewoodres.R" "datacleaning_census_2014.R"
[15] "example files" "flf_2015.R"
[17] "leafres.R" "script to create average daily climate.R"
[19] "smallTreeNPP_2015.R" "smallTreeNPP_v3.R"
[21] "soil_respiration_2015.R" "soilrespiration_auxfunctions.R"
[23] "stem_respiration_2015.R"
> Sys.setlocale('LC_ALL','C')
[1] "C/C/C/C/C/en_GB.UTF-8"
> source("NPPacw_census_function_2014.R")
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file 'NPPacw_census_function_2014.R': No such file or directory
> source("allometric_equations_2014.R")
> setwd("/Users/cecile/GitHub/GEMcarbon.R")
> dir()
[1] "ACJ_carboncycle_2015.R" "Archive"
[3] "EGM_raw_to_flux_option1.R" "EGM_raw_to_flux_stem_2015.R"
[5] "GEM_carbon.R" "NPPacw_census_function_2015.R"
[7] "NPPacw_dendro_function_2015.R" "NPPacw_step1_reformatting_census_2015.R"
[9] "NPProot_2015.R" "SAFE_IngrowthCores_Rcode_toCecile_2.txt"
[11] "allometric_equations_2014.R" "coarsewoodNPP.R"
[13] "coarsewoodres.R" "datacleaning_census_2014.R"
[15] "example files" "flf_2015.R"
[17] "leafres.R" "script to create average daily climate.R"
[19] "smallTreeNPP_2015.R" "smallTreeNPP_v3.R"
[21] "soil_respiration_2015.R" "soilrespiration_auxfunctions.R"
[23] "stem_respiration_2015.R"
> Sys.setlocale('LC_ALL','C')
[1] "C/C/C/C/C/en_GB.UTF-8"
> source("NPPacw_census_function_2015.R")
> source("allometric_equations_2014.R")
> acj_01A <- NPPacw_census(census, plotname="ACJ-01", allometric_option="Default", height_correction_option="Default", census1_year=2013, census2_year=2014)
[1] "moist equation is used for estimating AGB, model I.6 (see Chave et al., 2005)"
[1] "If you have height for more than 50 trees in your plot, estimate local diameter-height relationship. If not, choose height correction option 2."
> acj_01A
NPPacw_MgC_ha_yr NPPacw_MgC_ha_yr_se
1 2.482465 1.252718e-08
> acj_01B <- NPPacw_census(census, plotname="ACJ-01", allometric_option="Default", height_correction_option="Default", census1_year=2014, census2_year=2015)
[1] "moist equation is used for estimating AGB, model I.6 (see Chave et al., 2005)"
[1] "If you have height for more than 50 trees in your plot, estimate local diameter-height relationship. If not, choose height correction option 2."
> acj_01B
NPPacw_MgC_ha_yr NPPacw_MgC_ha_yr_se
1 0 NA
> setwd("/Users/cecile/Dropbox/GEMcarbondb/db_csv/db_csv_2015/readyforupload_db/acj_pan_2015")
> NPPdend_ACJ01 <- read.table("Dendrometer_ACJ_2013_2014.csv", header=TRUE, sep=",", na.strings=c("NA", "NaN", ""), dec=".", strip.white=TRUE)
> dendrometer <- NPPdend_ACJ01
> plotname = "ACJ-01" # TO DO: "ACJ" should be replaced by "ACJ-01" everywhere!
> allometric_option = "Default"
> height_correction_option = "Default"
> census_year = 2013
> plotit=T
> setwd("/Users/cecile/GitHub/GEMcarbon.R")
> dir()
[1] "ACJ_carboncycle_2015.R" "Archive"
[3] "EGM_raw_to_flux_option1.R" "EGM_raw_to_flux_stem_2015.R"
[5] "GEM_carbon.R" "NPPacw_census_function_2015.R"
[7] "NPPacw_dendro_function_2015.R" "NPPacw_step1_reformatting_census_2015.R"
[9] "NPProot_2015.R" "SAFE_IngrowthCores_Rcode_toCecile_2.txt"
[11] "allometric_equations_2014.R" "coarsewoodNPP.R"
[13] "coarsewoodres.R" "datacleaning_census_2014.R"
[15] "example files" "flf_2015.R"
[17] "leafres.R" "script to create average daily climate.R"
[19] "smallTreeNPP_2015.R" "smallTreeNPP_v3.R"
[21] "soil_respiration_2015.R" "soilrespiration_auxfunctions.R"
[23] "stem_respiration_2015.R"
> Sys.setlocale('LC_ALL','C')
[1] "C/C/C/C/C/en_GB.UTF-8"
> source("allometric_equations_2014.R")
> # load libraries
> library(sqldf)
> head(census)
plot_code tree_tag dbh height_m density year month day plot
1 ACJ-01 1 12.9 7.50 0.5745640 2013 1 22 ACJ-01
2 ACJ-01 2 23.4 7.70 0.6392357 2013 1 22 ACJ-01
3 ACJ-01 3 11.9 7.00 0.6392357 2013 1 22 ACJ-01
4 ACJ-01 4 13.4 8.25 0.6392357 2013 1 22 ACJ-01
5 ACJ-01 5 31.2 9.50 0.6697630 2013 1 22 ACJ-01
6 ACJ-01 6 12.8 7.50 0.6392357 2013 1 22 ACJ-01
> cen1 <- subset(census, plot_code==plotname)
> cen <- subset(cen1, year==census_year)
> dend1 <- subset(dendrometer, plot_code==plotname)
> cen$cenyear <- cen$year
> cen$cenmonth <- cen$month
> cen$cenday <- cen$day
> dend <- sqldf("SELECT dend1.*, cen.density, cen.height_m, cen.dbh, cen.cenyear, cen.cenmonth, cen.cenday FROM cen JOIN dend1 ON cen.tree_tag = dend1.tree_tag")
> head(dend) # check you have data in here. If not, make sure dend1 and cen are in the right formats, e.g. using sapply(cen, class).
plot_code sub_plot tree_tag year month day dend_pom_height_m dendrometer_reading_mm comments status_code_aintact_bmoved_cbroken
1 ACJ-01 1 6 2013 6 21 1.4 -1.8 <NA> NA
2 ACJ-01 1 6 2013 9 24 1.4 -1.54 <NA> NA
3 ACJ-01 1 6 2013 12 10 1.4 -2.1 <NA> NA
4 ACJ-01 1 6 2014 3 6 1.4 -1.6 <NA> NA
5 ACJ-01 1 10 2013 6 21 1.4 -0.7 <NA> NA
6 ACJ-01 1 10 2013 9 24 1.4 0 <NA> NA
mortality_aalive_ddead density height_m dbh cenyear cenmonth cenday
1 NA 0.6392357 7.5 12.8 2013 1 22
2 NA 0.6392357 7.5 12.8 2013 1 22
3 NA 0.6392357 7.5 12.8 2013 1 22
4 NA 0.6392357 7.5 12.8 2013 1 22
5 NA 0.5745640 9.5 17.0 2013 1 22
6 NA 0.5745640 9.5 17.0 2013 1 22
> if (allometric_option == 2 | allometric_option == "dry") {
+ allometrix <- 2
+ print("dry equation is used for estimating AGB, model I.3 (see Chave et al., 2005)")
+ } else if (allometric_option == 3 | allometric_option == "moist" | allometric_option == "Default" | allometric_option == 1) {
+ allometrix <- 3
+ print("moist equation is used for estimating AGB, model I.6 (see Chave et al., 2005)")
+ } else if (allometric_option == 4 | allometric_option == "wet") {
+ allometrix <- 4
+ print("wet equation is used for estimating AGB, model I.3 (see Chave et al., 2005)")
+ } else if (allometric_option == 5 | allometric_option == "Chave2014") {
+ allometrix <- 5
+ print("pantropical equation is used for estimating AGB, model (4) (see Chave et al., 2014)")
+ } else {
+ print("Please specify a valid allometric_option!")
+ return()
+ }
[1] "moist equation is used for estimating AGB, model I.6 (see Chave et al., 2005)"
> if (height_correction_option == 1 | height_correction_option == "Default" ) {
+ predheight <- 1
+ print("If you have height for more than 50 trees in your plot, estimate local diameter-height relationship. If not, choose height correction option 2.")
+ } else if (height_correction_option == 2) {
+ predheight <- 2
+ print("height correction estimated as described by Feldpauch et al. (2012). Please check Feldpauch regional parameters in the code. Default is Brazilian shield.")
+ } else {
+ print("Please specify a valid height_correction_option!")
+ return()
+ }
[1] "If you have height for more than 50 trees in your plot, estimate local diameter-height relationship. If not, choose height correction option 2."
> h.est=function(dbh, h){
+ l =lm(h~dbh)
+ coeffs = coefficients(l)
+ pred.h = coeffs[1] + coeffs[2]*dbh
+ }
> Bo = 0.6373
> B1 = 0.4647 # E.C. Amazonia
>
> So1 = 0.012 # E.C. Amazonia
> Abar = 20.4 # mean cenetered basal area m-2 ha-1
>
> n01 = 0.0034 # E.C. Amazonia
> Pvbar = 0.68 # mean centered precipitation coefficient of variation
>
> n02 = -0.0449 # E.C. Amazonia
> Sdbar = 5 # mean centered dry season length no months less than 100mm
>
> n03 = 0.0191 # E.C. Amazonia
> Tabar = 25.0 # mean centered annual averge temperature
>
>
> # Define height options
> if (predheight == 1) {
+ w <- which(is.na(cen$height_m))
+ h.pred <- h.est(cen$dbh, cen$height_m)
+ cen$height_m[w] <- h.pred[w]
+ } else if (predheight == 2) {
+ w <- which(is.na(cen$height_m))
+ cen$height_m[w] <- 10^(Bo + B1*log10(cen$dbh[w]/10) + Abar*So1 + n01*Pvbar + n02*Sdbar + n03*Tabar)
+ }
> # data cleaning
> dend$dendrometer_reading_mm[which(dend$dendrometer_reading_mm > 1000)] <- NaN
>
> # format dates
> dend$dbh_first_date <- as.Date(paste(dend$cenyear, dend$cenmonth, dend$cenday, sep="."), format="%Y.%m.%d")
> dend$date <- as.Date(paste(dend$year, dend$month, dend$day, sep="."), format="%Y.%m.%d")
> dend$dendrometer_reading_mm <- as.numeric(dend$dendrometer_reading_mm) # Ignore error message. NA introduced by coercion is ok.
Warning message:
NAs introduced by coercion
> dend$thisdbh_cm <- (dend$dbh*pi) + ((dend$dendrometer_reading_mm/10)/pi)
> # estimate biomass of each tree for each new thisdbh_mm
> #loop through each tree to estimate biomass (bm) and convert to above ground carbon (agC)
> for (ii in 1:length(dend$tree_tag)) {
+ thistree <- which(dend$tree_tag == dend$tree_tag[ii] & dend$year == dend$year[ii] & dend$month == dend$month[ii] & dend$day == dend$day[ii])
+ dbh_tree <- dend$thisdbh_cm[thistree]
+ den_tree <- dend$density[thistree]
+ h_tree <- dend$height_m[thistree]
+
+ # this uses allometric equations from allometricEquations.R
+ if (allometrix == 2) {
+ bm <- Chave2005_dry(diax=dbh_tree, density=den_tree, height=h_tree)
+ } else if (allometrix == 3) {
+ bm <- Chave2005_moist(diax=dbh_tree, density=den_tree, height=h_tree)
+ } else if (allometrix == 4) {
+ bm <- Chave2005_wet(diax=dbh_tree, density=den_tree, height=h_tree)
+ } else if (allometrix == 5) {
+ bm <- Chave2014(diax=dbh_tree, density=den_tree, height=h_tree)
+ }
+
+ ## TO DO ## error treatment remains to be done!
+
+ # Unit conversions
+
+ dend$agC[ii] <- (bm)*(1/(2.1097*1000)) # convert kg to Mg=1/1000=10 and convert to carbon = 47.8% (ADD REF!! Txx et al?)
+ dend$bm_kg[ii] <- (bm)
+ }
> dend$agCdiff <- ave(dend$agC, dend$plot_code, FUN = function(x) c(NA, diff(x)))
> first_run = T
> for (ii in 1:length(dend$tree_tag)) {
+ thistree <- which(dend$tree_tag == dend$tree_tag[ii])
+ agC <- dend$agC[thistree]
+ tag <- dend$tree_tag[thistree]
+ agCdiff <- dend$agCdiff[thistree]
+ year <- dend$year[thistree]
+ month <- dend$month[thistree]
+ plot_code <- dend$plot_code[thistree]
+ datediff <- rbind(0/0, data.frame(diff(as.matrix(dend$date[thistree])))) #datediff <- data.frame(0/0, difftime(tail(dend$date[thistree], -1), head(dend$date[thistree], -1), units="days"))
+ w <- cbind (plot_code, tag, year, month, agC, agCdiff, datediff)
+ if (first_run) {
+ npp_tree <- w
+ first_run = F
+ } else {
+ npp_tree <- rbind (npp_tree, w)
+ }
+ }
>
> colnames(npp_tree) <- c("plot_code", "tag", "year", "month", "agC", "agCdiff", "datediff")
> npp_tree$nppacw_tree_day <- npp_tree$agCdiff/npp_tree$datediff
> www <- sqldf("SELECT plot_code, year, month, AVG(nppacw_tree_day), STDEV(nppacw_tree_day) FROM npp_tree GROUP BY year, month")
> colnames (www) <- c("plot_code", "year", "month", "npp_avgtrees_day_dend", "npp_avgtrees_day_dend_sd")
> www$npp_avgtrees_day_dend <- as.numeric(www$npp_avgtrees_day_dend)
> www$npp_avgtrees_month_dend <- www$npp_avgtrees_day_dend*29.6
> www$npp_avgtrees_yr_dend <- www$npp_avgtrees_month_dend*12
> www$npp_avgtrees_month_dend_sd <- www$npp_avgtrees_day_dend_sd*29.6
> www$npp_avgtrees_yr_dend_sd <- www$npp_avgtrees_month_dend_sd*12
> nppacw_cen <- NPPacw_census(census, plotname="PAN-03", allometric_option="Default", height_correction_option="Default", census1_year=2013, census2_year=2014)
[1] "moist equation is used for estimating AGB, model I.6 (see Chave et al., 2005)"
[1] "If you have height for more than 50 trees in your plot, estimate local diameter-height relationship. If not, choose height correction option 2."
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
0 (non-NA) cases
Called from: lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...)
Browse[1]>
> xxx <- sqldf("SELECT plot_code, AVG(npp_avgtrees_yr_dend) from www")
> colnames(xxx) <- c("plot_code", "nppacw_dend")
> sf <- (xxx$nppacw_dend*length(unique(dend$tree_tag))) / nppacw_cen[,1]
Error: object 'nppacw_cen' not found
> www$nppacw_month <- (www$npp_avgtrees_month_dend*length(unique(dend$tree_tag)))/sf
Error: object 'sf' not found
> www$nppacw_month_sd <- (www$npp_avgtrees_month_dend_sd*length(unique(dend$tree_tag)))/sf # TO DO: so we want SE or SD???
Error: object 'sf' not found
> head(census)
plot_code tree_tag dbh height_m density year month day plot
1 ACJ-01 1 12.9 7.50 0.5745640 2013 1 22 ACJ-01
2 ACJ-01 2 23.4 7.70 0.6392357 2013 1 22 ACJ-01
3 ACJ-01 3 11.9 7.00 0.6392357 2013 1 22 ACJ-01
4 ACJ-01 4 13.4 8.25 0.6392357 2013 1 22 ACJ-01
5 ACJ-01 5 31.2 9.50 0.6697630 2013 1 22 ACJ-01
6 ACJ-01 6 12.8 7.50 0.6392357 2013 1 22 ACJ-01
> nppacw_cen <- NPPacw_census(census, plotname="ACJ-01", allometric_option="Default", height_correction_option="Default", census1_year=2013, census2_year=2014)
[1] "moist equation is used for estimating AGB, model I.6 (see Chave et al., 2005)"
[1] "If you have height for more than 50 trees in your plot, estimate local diameter-height relationship. If not, choose height correction option 2."
> xxx <- sqldf("SELECT plot_code, AVG(npp_avgtrees_yr_dend) from www")
> colnames(xxx) <- c("plot_code", "nppacw_dend")
> sf <- (xxx$nppacw_dend*length(unique(dend$tree_tag))) / nppacw_cen[,1]
> www$nppacw_month <- (www$npp_avgtrees_month_dend*length(unique(dend$tree_tag)))/sf
> www$nppacw_month_sd <- (www$npp_avgtrees_month_dend_sd*length(unique(dend$tree_tag)))/sf # TO DO: so we want SE or SD???
> yy <- data.frame((mean(www$nppacw_month, na.rm=T))*12,(mean(www$nppacw_month_sd, na.rm=T))*12)
> colnames(yy) <- c("nppacw_month", "nppacw_month_sd")
> yy
nppacw_month nppacw_month_sd
1 2.482465 9.023387
> nppacw_cen
NPPacw_MgC_ha_yr NPPacw_MgC_ha_yr_se
1 2.482465 1.252718e-08
> monthlynppacw <- data.frame(cbind(as.character(www$plot_code), www$year, www$month, www$nppacw_month, www$nppacw_month_sd))
> colnames(monthlynppacw) <- c("plot_code", "year", "month", "nppacw_MgC_month", "nppacw_MgC_month_sd")
> plot(www$month, www$nppacw_month)
> plotit=T
> plot <- ggplot(data=www, aes(x=month, y=nppacw_month, na.rm=T)) +
+ geom_point(colour='black', size=2) +
+ #geom_ribbon(data=www, aes(ymin=nppacw_month-nppacw_month_se , ymax=nppacw_month+nppacw_month_se), alpha=0.2) +
+ geom_errorbar(aes(ymin=nppacw_month-nppacw_month_sd, ymax=nppacw_month+nppacw_month_sd), width=.1) +
+ #scale_x_date(breaks = date_breaks("months"), labels = date_format("%b-%Y")) +
+ scale_colour_grey() +
+ theme(text = element_text(size=17), legend.title = element_text(colour = 'black', size = 17, hjust = 3, vjust = 7, face="plain")) +
+ xlab("month") + ylab(expression(paste("NPP ACW (MgC ", ha^-1, mo^-1, ")", sep=""))) +
+ theme_classic(base_size = 15, base_family = "") +
+ theme(legend.position="left") +
+ theme(panel.border = element_rect(fill = NA, colour = "black", size = 1))
>
> plot
Warning message:
Removed 1 rows containing missing values (geom_point).
> plot(www$month, www$nppacw_month)
>
|
8ff0d33d87b491acc8b9e43a5405db584bd767b6
|
2643a442e25b937a853f4576db73d7a23835b1c6
|
/R/define_variables.R
|
0350fa756208f843ae125307c50fce92b768450d
|
[
"MIT"
] |
permissive
|
mperezrocha83/ecocomDP
|
0e768bd754389dc617bbbd7c6dd383c254dbf2ed
|
e8165540722b0641471e7f4315e241848b847cd9
|
refs/heads/master
| 2020-09-04T17:59:12.234472
| 2019-10-14T23:01:23
| 2019-10-14T23:01:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,175
|
r
|
define_variables.R
|
#' Define categorical variables of ecocomDP tables
#'
#' @description
#' Get variable definitions and units from parent EML.
#'
#' @usage define_variables(data.path, parent.pkg.id)
#'
#' @param data.path
#' (character) Path to ecocomDP tables.
#' @param parent.pkg.id
#' (character) Parent data package ID from the EDI Data Repository (e.g.
#' knb-lter-cap.627.3).
#'
#' @return
#' (data frame) A data frame with columns:
#' \itemize{
#' \item{tableName} Table in which variable is found.
#' \item{attributeName} Field in which variable is found.
#' \item{code} Variable name.
#' \item{definition} Variable definition, if found, blank if otherwise.
#' \item{unit} Variable unit, if found, blank otherwise.
#' }
#'
#' @export
#'
define_variables <- function(data.path, parent.pkg.id){
message('Retrieving variable definitions and units')
# Define what a variable is
criteria <- read.table(
system.file('validation_criteria.txt', package = 'ecocomDP'),
header = T,
sep = "\t",
as.is = T,
na.strings = "NA"
)
L1_table_names <- criteria$table[is.na(criteria$column)]
file_names <- suppressMessages(
validate_table_names(
data.path = data.path,
criteria = criteria
)
)
# Load tables
data.list <- lapply(
file_names,
read_ecocomDP_table,
data.path = data.path
)
names(data.list) <- unlist(
lapply(
file_names,
is_table_rev,
L1_table_names
)
)
# Get variable names and create data.frame
cat_vars <- make_variable_mapping(
observation = data.list$observation$data,
observation_ancillary = data.list$observation_ancillary$data,
taxon_ancillary = data.list$taxon_ancillary$data,
location_ancillary = data.list$location_ancillary$data
)[ , c('variable_name', 'table_name')]
cat_vars$attributeName <- rep('variable_name', nrow(cat_vars))
cat_vars$definition <- NA_character_
cat_vars$unit <- NA_character_
cat_vars <- dplyr::select(
cat_vars,
table_name,
attributeName,
variable_name,
definition,
unit
)
colnames(cat_vars) <- c(
'tableName',
'attributeName',
'code',
'definition',
'unit'
)
# This work around turns vectors into data.frames, get_eml_attribute will
# otherwise break.
cat_vars[nrow(cat_vars)+1, ] <- NA_character_
# Get definitions and reshape output
var_metadata <- mapply(
EDIutils::get_eml_attribute,
attr.name = cat_vars$code,
MoreArgs = list(package.id = parent.pkg.id)
)
var_metadata <- as.data.frame(t(var_metadata), row.names = F)
# Combine into cat_vars object
cat_vars[ , c('definition', 'unit')] <- var_metadata[ , c('definition', 'unit')]
use_i <- stringr::str_detect(cat_vars$definition, 'Error in UseMethod')
use_i[is.na(use_i)] <- FALSE
cat_vars[use_i , c('definition', 'unit')] <- NA_character_
# Remove place holder added above
cat_vars <- cat_vars[1:(nrow(cat_vars)-1), ]
# Return --------------------------------------------------------------------
cat_vars
}
|
00ece5ff086a6937f19277402b1e958e356ed6b8
|
1b15d76ac488aaeadeb6b4e7cc4344dfff815266
|
/movie_boxoffie_forecast.R
|
44e9b63283d7802a65d55bb4eb59481aef3b6b8e
|
[] |
no_license
|
maujy/imdbR
|
29ff885b33ad0dc8d5e0c3834d8c559f0657cbf8
|
83842601372d9a89306e2d945b1a5d6a9b2ec0a1
|
refs/heads/master
| 2021-09-03T21:25:00.077177
| 2018-01-12T04:31:59
| 2018-01-12T04:31:59
| 115,768,638
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,199
|
r
|
movie_boxoffie_forecast.R
|
movie_title_list = read.csv("movie_title_list_v1.00.csv", header=TRUE)
str(movie_title_list)
View(movie_title_list)
movie_title_data.frame = movie_title_list[, c(-1, -2, -3, -4, -6, -10 )]
str(movie_title_data.frame)
View(movie_title_data.frame)
par(mfrow = c(1,2))
plot(main='Movie Box Office')
plot(movie_title_data.frame$worldGross, sub='original worldGross')
plot(log(movie_title_data.frame$worldGross+1), sub='log(worldGross+1)')
# plot(log(movie_title_data.frame$worldGross)+2.3026, sub='log(worldGross)+2.3026')
# plot(sqrt(movie_title_data.frame$worldGross), sub='sqrt(worldGross)')
# plot(1/movie_title_data.frame$worldGross, sub='1/worldGross**2')
par(mfrow = c(1,1))
summary(log(movie_title_data.frame$worldGross)+2.3026)
# colnames(movie_title_data.frame)
# [1] "worldGross" "originalTitle" "startYear" "runtimeMinutes" "directors"
# [6] "writers" "principalCast" "averageRating" "numVotes" "isSport"
# [11] "isMusical" "isFamily" "isMystery" "isHistory" "isCrime"
# [16] "isDrama" "isMusic" "isBiography" "isAdult" "isAdventure"
# [21] "isNews" "isX.N" "isFantasy" "isRomance" "isWar"
# [26] "isAction" "isHorror" "isThriller" "isAnimation" "isDocumentary"
# [31] "isWestern" "isSci.Fi" "isComedy" "isFilm.Noir" "summaries"
# [36] "synopsis" "filmRating" "firstRelaseDate" "firstReleaseCountry" "awards"
# [41] "productionCo"
# Linear regression
movie_title_list_simple = movie_title_data.frame[, c(1:8)]
write.csv(movie_title_list_simple, file="output/movie_title_list_simple.csv")
# data.frame = movie_title_data.frame[, c(1, 3:4, 10:34)]
data.frame = movie_title_data.frame[, c(1, 3:4, 12, 16, 20, 23, 26, 28, 29, 30, 32)]
str(data.frame)
View(data.frame)
na.fill
lmTrain = lm(formula = log(worldGross+1)~ ., data = data.frame)
summary(lmTrain)
New_data = data.frame(orginalTitle=)
|
a9bb7675ead13e5b54e23e2aee7a78c7e1783d28
|
33a08ca3c15a5fc678d78777b53d8868a7bc7897
|
/man/print.FSchr.Rd
|
81e56b3d668dcc27b3cb734adaab29542d110e1b
|
[] |
no_license
|
hjanime/DCS
|
09f10d37d549eae3837b1c15d65d319f8c45e8ea
|
33570353b7812fc0d1fb2744cc34d6e92375b90f
|
refs/heads/master
| 2020-03-23T02:44:05.383267
| 2018-07-15T01:18:57
| 2018-07-15T01:18:57
| 140,989,262
| 0
| 0
| null | 2018-07-15T01:17:32
| 2018-07-15T01:17:32
| null |
UTF-8
|
R
| false
| true
| 344
|
rd
|
print.FSchr.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ClassDefinitions.R
\name{print.FSchr}
\alias{print.FSchr}
\title{print.FSchr}
\usage{
\method{print}{FSchr}(x, ..., n = 6)
}
\arguments{
\item{x}{An \code{FSchr} object.}
\item{...}{Unused.}
\item{n}{Number of observations to print.}
}
\description{
print.FSchr
}
|
b07164b9ce85b93fe002be01f2767123b6501d81
|
35db3db7776101724d8ab20e4dfcf3f9e7b361a1
|
/ui.r
|
9cd57cc618db498a09a1561995563d54dd1cd660
|
[] |
no_license
|
mamonu/LDAShiny
|
dce38b1bad84021fbd150175645ad118ec2fa04d
|
045c23a39130656a247feec623f41240838fb092
|
refs/heads/master
| 2021-01-10T07:12:02.627342
| 2016-03-04T17:45:25
| 2016-03-04T17:45:25
| 53,063,030
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,280
|
r
|
ui.r
|
library(shiny)
library(formattable)
fluidPage(
# Application title
titlePanel("Interactive LDA"),
sidebarLayout(
# Sidebar with a slider and selection inputs
sidebarPanel(
fileInput('file1', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)
),
hr(),
sliderInput("clust",
"clusters:",
min = 1, max = 12, value = 3),
sliderInput("ialpha",
"alpha:",
min = 0.01, max = 0.05, value = 0.02),
sliderInput("ieta",
"eta:",
min = 0.01, max = 0.05, value = 0.02),
sliderInput("top",
"number of top words per topic:",
min = 2, max = 15, value = 5),
sliderInput("iter",
"Number of Iterations:",
min = 1, max = 5200, value = 800)
),
mainPanel(h4("LDA topics"),
formattableOutput ("LDA"),hr(),h4("Text"),
tableOutput('contents')
)
)
)
|
55b7ca941dc5a81a3281b7170c52a3fd762f7a7b
|
f40c36525935715889897ad377597a7cf0cc32ef
|
/Brachy4g24315DNA.R
|
87d24f89535d08ea8f02a6fce6baa2cb3fb1d8b6
|
[] |
no_license
|
KimNewell/2018-07-10_AyliffeProteinAlign
|
c80c5fa8e7fa20244fef3c43331c9e404d2f2c11
|
c5e343e5c72a4481a5b811bbbd27e71b86c27f8e
|
refs/heads/master
| 2020-03-22T16:57:06.394372
| 2018-07-17T13:02:40
| 2018-07-17T13:02:40
| 140,362,808
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,385
|
r
|
Brachy4g24315DNA.R
|
library(msa)
library(tools)
library(tidyverse)
library(dplyr)
Bradi4g24315DNASeq <- readDNAStringSet("C:/Users/new163/Desktop/2018-07-10_AyliffeProteinAlign/data/Bradi4g24315DNA.txt")
Bradi4g24315DNASeq
Bradi4g24315DNASeqAlign <- msa(Bradi4g24315DNASeq)
# To make a PDF file first have to make a 'tex' file then convert to 'pdf'
msaPrettyPrint(Bradi4g24315DNASeqAlign, output="tex", showNames="left", showLegend =FALSE,
showLogo="none", askForOverwrite=FALSE, verbose=FALSE, file='results/Brachy4g24315DNASeqAlign.tex')
texi2pdf('results/Brachy4g24315DNASeqAlign.tex', clean=TRUE)
#msaPrettyPrint(DNASeqAlign, output="tex", showNames="left",
# showLogo="none", askForOverwrite=FALSE, verbose=FALSE, file='results/DNASeqAlign.tex')
#texi2pdf('results/DNASeqAlign.tex', clean=TRUE)
# Change to matrix, transform, make a tibble
Bradi4g24315DNASeqAlign <- as.matrix(Bradi4g24315DNASeqAlign)
Bradi4g24315DNASeqAlign
Bradi4g24315DNASeqAlign_t <- t(Bradi4g24315DNASeqAlign)
Bradi4g24315DNASeqAlign_t
Bradi4g24315DNASeqAlign_t_t <- as_tibble(Bradi4g24315DNASeqAlign_t)
Bradi4g24315DNASeqAlign_t_t
#change row number to be a column and name it "position" using
# rownames_to_column()
Bradi4g24315DNASeqAlign_t_t <- rownames_to_column(Bradi4g24315DNASeqAlign_t_t, var="position")
head(Bradi4g24315DNASeqAlign_t_t, 20)
dfBradi4g24315DNA = apply(Bradi4g24315DNASeqAlign_t_t,1, function(x) length(unique(na.omit(x))))
dfBradi4g24315DNA
dfBradi4g24315DNACount <- cbind(Bradi4g24315DNASeqAlign_t_t, count = apply(Bradi4g24315DNASeqAlign_t_t, 1, function(x)length(unique(x))))
dfBradi4g24315DNACount
tail(dfBradi4g24315DNACount)
newdfBradi4g24315DNACount<- subset(dfBradi4g24315DNACount, count > 2)
newdfBradi4g24315DNACount
nrow(newdfBradi4g24315DNACount)
######
library(grid)
library(gridExtra)
df4 <- newdfBradi4g24315DNACount
df4
dim(df4)
maxrow = 102
npages = ceiling(nrow(df4)/maxrow)
pdf("results/Brachy4g24315DNAtabletemp.pdf", height = 50, width = 8.5)
idx = seq(1, maxrow)
grid.table(df4[idx,],rows = rownames(df4))
for(i in 2:npages){
grid.newpage();
if(i*maxrow <= nrow(df4)){
idx = seq(1+((i-1)*maxrow), i * maxrow)
}
else{
idx = seq(1+((i-1)*maxrow), nrow(df4))
}
grid.table(df4[idx, ],rows = NULL)
dev.off()
}
#dev.off()
|
c2e26229d94d17ff1c9e5db93fe34cab6e40f9d8
|
44a3fad6338a63ac5417b1e52e47420c0e013f45
|
/man/dExtDep.Rd
|
29d48f982fd64a695191497e442a462f632da120
|
[] |
no_license
|
cran/ExtremalDep
|
4faac60ce0040262a98410edc6488ddf939ad9bd
|
18238416ddb6567610c4457dc332316272dbd16e
|
refs/heads/master
| 2023-03-06T18:03:59.304908
| 2023-02-26T14:40:02
| 2023-02-26T14:40:02
| 236,595,530
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,844
|
rd
|
dExtDep.Rd
|
\name{dExtDep}
\alias{dExtDep}
\title{Parametric and non-parametric density of Extremal Dependence}
\description{This function calculates the density of parametric multivariate extreme distributions and corresponding angular density, or the non-parametric angular density represented through Bernstein polynomials.}
\usage{
dExtDep(x, method="Parametric", model, par, angular=TRUE, log=FALSE,
c=NULL, vectorial=TRUE, mixture=FALSE)
}
\arguments{
\item{x}{A vector or a matrix. The value at which the density is evaluated.}
\item{method}{A character string taking value \code{"Parametric"} or \code{"NonParametric"}}
\item{model}{A string with the name of the model: \code{"PB"} (Pairwise Beta), \code{"HR"} (Husler-Reiss), \code{"ET"} (Extremal-t), \code{"EST"} (Extremal Skew-t), \code{TD} (Tilted Dirichlet) or \code{AL} (Asymmetric Logistic) when evaluating the angular density. Restricted to \code{"HR"}, \code{"ET"} and \code{"EST"} for multivariate extreme value densities. Required when \code{method="Parametric"}.}
\item{par}{A vector representing the parameters of the (parametric or non-parametric) model.}
\item{angular}{A logical value specifying if the angular density is computed.}
\item{log}{A logical value specifying if the log density is computed.}
\item{c}{A real value in \eqn{[0,1]}{[0,1]}, providing the decision rule to allocate a data point to a subset of the simplex.
Only required for the parametric angular density of the Extremal-t, Extremal Skew-t and Asymmetric Logistic models.}
\item{vectorial}{A logical value; if \code{TRUE} a vector of \code{nrow(x)} densities is returned. If \code{FALSE} the likelihood
function is returned (product of densities or sum if \code{log=TRUE}. \code{TRUE} is the default.}
\item{mixture}{A logical value specifying if the Bernstein polynomial representation of distribution should be expressed as a mixture. If \code{mixture=TRUE} the density integrates to 1. Required when \code{method="NonParametric"}. }
}
\details{
Note that when \code{method="Parametric"} and \code{angular=FALSE}, the density is only available in 2 dimensions.
When \code{method="Parametric"} and \code{angular=TRUE}, the models \code{"AL"}, \code{"ET"} and \code{"EST"} are limited to 3 dimensions. This is because of the existence of mass on the subspaces on the simplex (and therefore the need to specify \code{c}).
For the parametric models, the appropriate length of the parameter vector can be obtained from the \code{dim_ExtDep} function and are summarized as follows.
When \code{model="HR"}, the parameter vector is of length \code{choose(dim,2)}.
When \code{model="PB"} or \code{model="Extremalt"}, the parameter vector is of length \code{choose(dim,2) + 1}.
When \code{model="EST"}, the parameter vector is of length \code{choose(dim,2) + dim + 1}.
When \code{model="TD"}, the parameter vector is of length \code{dim}.
When \code{model="AL"}, the parameter vector is of length \code{2^(dim-1)*(dim+2) - (2*dim+1)}.
}
\value{
If \code{x} is a matrix and \code{vectorial=TRUE}, a vector of length \code{nrow(x)}, otherwise a scalar.
}
\author{
Simone Padoan, \email{simone.padoan@unibocconi.it},
\url{https://faculty.unibocconi.it/simonepadoan/};
Boris Beranger, \email{borisberanger@gmail.com}
\url{https://www.borisberanger.com};
}
\references{
Beranger, B. and Padoan, S. A. (2015).
Extreme dependence models, chapater of the book \emph{Extreme Value Modeling and Risk Analysis: Methods and Applications},
\bold{Chapman Hall/CRC}.
Beranger, B., Padoan, S. A. and Sisson, S. A. (2017).
Models for extremal dependence derived from skew-symmetric families.
\emph{Scandinavian Journal of Statistics}, \bold{44}(1), 21-45.
Coles, S. G., and Tawn, J. A. (1991),
Modelling Extreme Multivariate Events,
\emph{Journal of the Royal Statistical Society, Series B (Methodological)}, \bold{53}, 377--392.
Cooley, D.,Davis, R. A., and Naveau, P. (2010).
The pairwise beta distribution: a flexible parametric multivariate model for extremes.
\emph{Journal of Multivariate Analysis}, \bold{101}, 2103--2117.
Engelke, S., Malinowski, A., Kabluchko, Z., and Schlather, M. (2015),
Estimation of Husler-Reiss distributions and Brown-Resnick processes,
\emph{Journal of the Royal Statistical Society, Series B (Methodological)}, \bold{77}, 239--265.
Husler, J. and Reiss, R.-D. (1989),
Maxima of normal random vectors: between independence and complete dependence,
\emph{Statistics and Probability Letters}, \bold{7}, 283--286.
Marcon, G., Padoan, S.A., Naveau, P., Muliere, P. and Segers, J. (2017)
Multivariate Nonparametric Estimation of the Pickands Dependence
Function using Bernstein Polynomials.
\emph{Journal of Statistical Planning and Inference}, \bold{183}, 1-17.
Nikoloulopoulos, A. K., Joe, H., and Li, H. (2009)
Extreme value properties of t copulas.
\emph{Extremes}, \bold{12}, 129--148.
Opitz, T. (2013)
Extremal t processes: Elliptical domain of attraction and a spectral representation.
\emph{Jounal of Multivariate Analysis}, \bold{122}, 409--413.
Tawn, J. A. (1990),
Modelling Multivariate Extreme Value Distributions,
\emph{Biometrika}, \bold{77}, 245--253.
}
\seealso{\code{\link{pExtDep}}, \code{\link{rExtDep}}, \code{\link{fExtDep}}, \code{\link{fExtDep.np}} }
\examples{
# Example of PB on the 4-dimensional simplex
dExtDep(x=rbind(c(0.1,0.3,0.3,0.3),c(0.1,0.2,0.3,0.4)), method="Parametric",
model="PB", par=c(2,2,2,1,0.5,3,4), log=FALSE)
# Example of EST in 2 dimensions
dExtDep(x=c(1.2,2.3), method="Parametric", model="EST", par=c(0.6,1,2,3), angular=FALSE, log=TRUE)
# Example of non-parametric angular density
par <- ExtremalDep:::rcoef(k=6, pm=list(p0=0.05, p1=0.1))
dExtDep(x=rbind(c(0.1,0.9),c(0.2,0.8)), method="NonParametric", par=par$beta)
}
\keyword{models}
|
accd701dc805fa94995540654978e26734d80ca0
|
29585dff702209dd446c0ab52ceea046c58e384e
|
/SPmlficmcm/R/Spmlficmcm.R
|
de7051530fdc3a5ce0e2118cba98e50767d2bff8
|
[] |
no_license
|
ingted/R-Examples
|
825440ce468ce608c4d73e2af4c0a0213b81c0fe
|
d0917dbaf698cb8bc0789db0c3ab07453016eab9
|
refs/heads/master
| 2020-04-14T12:29:22.336088
| 2016-07-21T14:01:14
| 2016-07-21T14:01:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,487
|
r
|
Spmlficmcm.R
|
Spmlficmcm <-
function(fl,N,gmname,gcname,DatfE,typ,start,p=NULL){
# ============================================================
# Etape 1 estimation des valeurs initiales
# Valeurs initiales des parametre du modele
# baterie des tests
yname = all.vars(fl)[1]
if(missing(N))
{
if (is.null(p))
{
print(p)
stop("Missing prevalence or N=c(N0,N1)")
}
else
{
if (p > 0.5) stop ("Disease prevalence needs to be <= 0.5")
if (p < 0) stop ("Negative disease prevalence")
clb<- model.frame(fl, data = DatfE)
# extraction de la variable reponse
outcb<-model.extract(clb,"response")
# nombre de cas
n1 = sum(outcb)
N1 = 5*n1
N0 = round(N1 * (1-p)/p)
N<-c(N0,N1)
#print (N)
}
}
#else
#{
# modele
clb1<- model.frame(fl, data = DatfE)
# extraction de la variable reponse
outcb1<-model.extract(clb1,"response")
# conditions
n1<-sum(outcb1)
n0<-length(outcb1)-n1
if(N[1]<n0 | N[2]<n1){print(N)
stop("The cases number or the controls in the study population is lower than cases or controls of study sample")
}else{
genom<-DatfE[gmname];genom1<-genom[is.na(genom)!=TRUE]
genoen<-DatfE[gcname];genoen1<-genoen[is.na(genoen)!=TRUE]
nagm<-genom[is.na(genom)==TRUE]
dat<-DatfE[is.na(DatfE[gcname])!=TRUE,]
gt1<-dat[gmname];
gt2<-dat[gcname];
teg1<-ifelse(gt1==0 & gt2==2,1,0)
teg2<-ifelse(gt1==2 & gt2==0,1,0)
tegk<-teg1+teg2
if(length(nagm)>0){print(gmname)
stop("missing mother genotype value")}
if(min(genom1)<0){print(gmname)
stop("mother's genotype is negative")}
if(max(genom1)>2){print(gmname)
stop("mother's genotype is greater than 2")}
if(min(genoen1)<0){print(gmname)
stop("child's genotype is negative")}
if(max(genoen1)>2){print(gmname)
stop("child's genotype is greater than 2")}
if(max(tegk)>0){print(gmname)
stop("mother and child genotypes are not compatible")
}else{
if(typ==1){
vIn<-Est.Inpar(fl,N,gmname,gcname,DatfE,1)
}else{
vIn<-Est.Inpar(fl,N,gmname,gcname,DatfE,2)
}
if(missing(start)){parms<-vIn$parms
}else{parms<-start}
p = length(parms)
beta.start=parms[1:(p-1)];
theta.start=parms[p]
# Valeurs initiales du systeme d quation non linaire
ma.u<-vIn$ma.u
vecma.u=c(ma.u[1,],ma.u[2,])
#=============================================================
# Etape 2 resolution du systeme d equation
RSeq<-Nlsysteq(fl,DatfE,N,gmname,gcname,yname,beta.start,theta.start)
SS<-nleqslv(vecma.u,RSeq)
vecma.u<-SS$x
#=============================================================
# Etape 3 ecriture de la vraisemblance profile
if(typ==1){
ftlh<-ft_likhoodCas1(fl,DatfE,N,gmname,gcname,yname,vecma.u)
}else{
ftlh<-ft_likhoodCasM(fl,DatfE,N,gmname,gcname,yname,vecma.u)
}
#=============================================================
# Etape 4 calcul des estimateurs
# calcul du gradient
if(typ==1){
fctgrad<-ft_gradientCas1(fl,DatfE,N,gmname,gcname,yname,vecma.u)
}
else{
fctgrad<-ft_gradientCasM(fl,DatfE,N,gmname,gcname,yname,vecma.u)
}
Grad<-fctgrad(parms)
#calcul de la hessian
delta <- 1e-5;
hess <- matrix(0, p, p);
for(gg in 1:p){
delta_ggamma <- parms;
delta_ggamma[gg]<- delta_ggamma[gg] + delta;
hess[, gg]<-(fctgrad(delta_ggamma) - Grad)/delta;
}
# estimateur des parametres
Parms.est=parms-solve(hess)%*%Grad
# calcul de la variance
Grad1<-fctgrad(Parms.est)
# Code de debuggage
# print(Grad1)
Hes1 <- matrix(0, p, p);
for(gg in 1:p){
delta_ggamma <- Parms.est;
delta_ggamma[gg] <- delta_ggamma[gg] + delta;
Hes1[, gg] <- (fctgrad(delta_ggamma) - Grad1)/delta;
}
matv<-(-1)*solve(Hes1)
var.par<-sqrt(diag(matv))
#=============================================================
# Etape 5 preparation des resultats
mats<-cbind(Parms.est,var.par)
nma<-c("Intercept",attr(terms.formula(fl),"term.labels"),"theta")
nac<-c("Estimate","Std.Error")
colnames(mats)<-nac
rownames(mats)<-nma
loglik<-ftlh(mats[,"Estimate"])
rr<-list(N=N,Uim=vecma.u,MatR=mats,Matv=matv,Lhft=ftlh,Value_loglikh=loglik)
return(rr)
}
}
#}
}
|
b46b06f061077df934018748c4a55a219c8b3fbc
|
73dcbcc208f33f1536c7fcf9a628b78363fec583
|
/man/kp_teamstats.Rd
|
b3bbdcc28f3bb50cd843c88d22c500b157ac6bfb
|
[
"MIT"
] |
permissive
|
sportsanalytics-world/hoopR
|
2a9ca3bd13ba02515900559dc801cbbdf4b5adde
|
4ddbfaf4e608dc6b2a543ea367c948891b651b0a
|
refs/heads/master
| 2023-04-19T19:20:20.433838
| 2021-05-21T10:23:42
| 2021-05-21T10:23:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 549
|
rd
|
kp_teamstats.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/kp_ratings_tables.R
\name{kp_teamstats}
\alias{kp_teamstats}
\title{Get Team Stats}
\usage{
kp_teamstats(min_year, max_year, defense = FALSE)
}
\arguments{
\item{min_year}{First year of data to pull}
\item{max_year}{Last year of data to pull}
\item{defense}{Choose whether to pull offense(default) with FALSE or defense with TRUE}
}
\description{
Get Team Stats
}
\examples{
\dontrun{
kp_teamstats(min_year = 2019, max_year = 2020, defense = FALSE)
}
}
\keyword{Team}
|
048020a7713eb90f6c1a6411f2dd0636902e6a8b
|
4f48793191dba5555eb5a4c92489e4e5b8e268d9
|
/movielens_project.R
|
3ded3eb33eedfc7fb76d24b73cdc58955c92b0e8
|
[] |
no_license
|
ZRNaum/movielens
|
a24eb2d7773f13acb8944c2f627a97ce7d868c0d
|
fbb839b7a23cbaa242dcd14ed330cc35b219449f
|
refs/heads/main
| 2023-05-08T17:38:53.048742
| 2021-05-28T15:45:56
| 2021-05-28T15:45:56
| 355,951,969
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,876
|
r
|
movielens_project.R
|
##########################################################
# Create edx set, validation set (final hold-out test set)
##########################################################
# Note: this process could take a couple of minutes
if(!require(tidyverse)) install.packages("tidyverse", repos = "http://cran.us.r-project.org")
if(!require(caret)) install.packages("caret", repos = "http://cran.us.r-project.org")
if(!require(data.table)) install.packages("data.table", repos = "http://cran.us.r-project.org")
if(!require(lubridate)) install.packages("lubridate", repos = "http://cran.us.r-project.org")
if(!require(recommenderlab)) install.packages("recommenderlab", repos = "http://cran.us.r-project.org")
library(tidyverse)
library(caret)
library(data.table)
library(lubridate)
library(recommenderlab)
# MovieLens 10M dataset:
# https://grouplens.org/datasets/movielens/10m/
# http://files.grouplens.org/datasets/movielens/ml-10m.zip
dl <- tempfile()
download.file("http://files.grouplens.org/datasets/movielens/ml-10m.zip", dl)
ratings <- fread(text = gsub("::", "\t", readLines(unzip(dl, "ml-10M100K/ratings.dat"))),
col.names = c("userId", "movieId", "rating", "timestamp"))
movies <- str_split_fixed(readLines(unzip(dl, "ml-10M100K/movies.dat")), "\\::", 3)
colnames(movies) <- c("movieId", "title", "genres")
# if using R 3.6 or earlier:
# movies <- as.data.frame(movies) %>% mutate(movieId = as.numeric(levels(movieId))[movieId],
# title = as.character(title),
# genres = as.character(genres))
# if using R 4.0 or later:
movies <- as.data.frame(movies) %>% mutate(movieId = as.numeric(movieId),
title = as.character(title),
genres = as.character(genres))
movielens <- left_join(ratings, movies, by = "movieId")
# Validation set will be 10% of MovieLens data
set.seed(1, sample.kind="Rounding") # if using R 3.5 or earlier, use `set.seed(1)`
test_index <- createDataPartition(y = movielens$rating, times = 1, p = 0.1, list = FALSE)
edx <- movielens[-test_index,]
temp <- movielens[test_index,]
# Make sure userId and movieId in validation set are also in edx set
validation <- temp %>%
semi_join(edx, by = "movieId") %>%
semi_join(edx, by = "userId")
# Add rows removed from validation set back into edx set
removed <- anti_join(temp, validation)
edx <- rbind(edx, removed)
rm(dl, ratings, movies, test_index, temp, movielens, removed)
### End of provided code ###
# Mutate edx and validation datasets to pull date from timestamp field
edx <- edx %>% mutate(timestamp = as_datetime(timestamp),
year = year(ymd_hms(timestamp)),
month = month(ymd_hms(timestamp)),
day = day(ymd_hms(timestamp)))
validation <- validation %>% mutate(timestamp = as_datetime(timestamp),
year = year(ymd_hms(timestamp)),
month = month(ymd_hms(timestamp)),
day = day(ymd_hms(timestamp)))
# Export datasets to .csv for use in report
write_csv(edx, "edx.csv")
write_csv(validation, "validation.csv")
# Generate train and test sets from edx dataset
set.seed(1, sample.kind="Rounding")
index <- createDataPartition(edx$rating, times = 1, p = 0.2, list = FALSE)
train_set <- edx[-index]
test_set <- edx[index]
test_set <- test_set %>%
semi_join(train_set, by = 'movieId') %>%
semi_join(train_set, by = 'userId')
# Compute average ratings for various predictors to determine variability
# UserId
train_set %>%
group_by(userId) %>%
filter(n()>=100) %>%
summarize(b_u = mean(rating)) %>%
ggplot(aes(b_u)) +
geom_histogram(bins = 30, color = "black")
# Genres
train_set %>%
group_by(genres) %>%
filter(n() >= 1000) %>%
summarize(b_g = mean(rating)) %>%
ggplot(aes(b_g)) +
geom_histogram(bins = 30, color = "black")
# Year
train_set %>%
group_by(year) %>%
filter(n() >= 5) %>%
summarize(b_y = mean(rating)) %>%
ggplot(aes(b_y)) +
geom_histogram(bins = 30, color = "black")
# Month
train_set %>%
group_by(month) %>%
summarize(b_m = mean(rating)) %>%
ggplot(aes(b_m)) +
geom_histogram(bins = 30, color = "black")
# Day
train_set %>%
group_by(day) %>%
summarize(b_d = mean(rating)) %>%
ggplot(aes(b_d)) +
geom_histogram(bins = 30, color = "black")
# Testing model to find the lambda that minimizes the RMSE
lambdas <- seq(0, 10, 0.25)
rmses <- sapply(lambdas, function(l) {
mu_hat <- mean(train_set$rating)
# Movie bias
b_i <- train_set %>%
group_by(movieId) %>%
summarize(b_i = sum(rating - mu_hat)/(n() + l))
# User bias
b_u <- train_set %>%
left_join(b_i, by = 'movieId') %>%
group_by(userId) %>%
summarize(b_u = sum(rating - mu_hat - b_i)/(n() + l))
# Genre bias
b_g <- train_set %>%
left_join(b_i, by = 'movieId') %>%
left_join(b_u, by = 'userId') %>%
group_by(genres) %>%
summarize(b_g = sum(rating - mu_hat - b_i - b_u)/(n() + l))
# Day bias
b_d <- train_set %>%
left_join(b_i, by = 'movieId') %>%
left_join(b_u, by = 'userId') %>%
left_join(b_g, by = 'genres') %>%
group_by(day) %>%
summarize(b_d = sum(rating - mu_hat - b_i - b_u - b_g)/(n() + l))
predicted_ratings <- test_set %>%
left_join(b_i, by = 'movieId') %>%
left_join(b_u, by = 'userId') %>%
left_join(b_g, by = 'genres') %>%
left_join(b_d, by = 'day') %>%
mutate(pred = mu_hat + b_i + b_u + b_g + b_d) %>%
pull(pred)
return(RMSE(test_set$rating, predicted_ratings))
})
# Best lambda value
lambda <- lambdas[which.min(rmses)]
# Final RMSE calculation using validation set
final_rmse <- sapply(lambda, function(l) {
mu_hat <- mean(edx$rating)
# Movie bias
b_i <- edx %>%
group_by(movieId) %>%
summarize(b_i = sum(rating - mu_hat)/(n() + l))
# User bias
b_u <- edx %>%
left_join(b_i, by = 'movieId') %>%
group_by(userId) %>%
summarize(b_u = sum(rating - mu_hat - b_i)/(n() + l))
# Genre bias
b_g <- edx %>%
left_join(b_i, by = 'movieId') %>%
left_join(b_u, by = 'userId') %>%
group_by(genres) %>%
summarize(b_g = sum(rating - mu_hat - b_i - b_u)/(n() + l))
# Day bias
b_d <- edx %>%
left_join(b_i, by = 'movieId') %>%
left_join(b_u, by = 'userId') %>%
left_join(b_g, by = 'genres') %>%
group_by(day) %>%
summarize(b_d = sum(rating - mu_hat - b_i - b_u - b_g)/(n() + l))
predicted_ratings <- validation %>%
left_join(b_i, by = 'movieId') %>%
left_join(b_u, by = 'userId') %>%
left_join(b_g, by = 'genres') %>%
left_join(b_d, by = 'day') %>%
mutate(pred = mu_hat + b_i + b_u + b_g + b_d) %>%
pull(pred)
return(RMSE(validation$rating, predicted_ratings))
})
|
20b2df456408f5f7975fe523e5753e7a2638dbf3
|
08ce90eef085080a6c7e2028cccce91e576d1b77
|
/plot3.R
|
2e3eeb6217cf39f0e5da4735b7c566d0162b6368
|
[] |
no_license
|
gustavolobo/ExData_Plotting1
|
16ef04e356a630b47959e9ad817617ed91f1fa23
|
c607ac18a0ec1ff5e7db2ec5a4ec9faa571da125
|
refs/heads/master
| 2021-01-22T20:36:04.483202
| 2014-09-06T01:45:53
| 2014-09-06T01:45:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 733
|
r
|
plot3.R
|
source("./loadData.R")
## Open PNG device and create 'plot3.png' in my working directory
png(file = "plot3.png")
data$Date <- as.Date(data$Date,format="%d/%m/%Y")
data$posix_date <- as.POSIXct(paste(data$Date, data$Time))
plot(
data$posix_date,
data$Sub_metering_1,
type = "l",
xaxt = "n",
xlab="",
ylab="Energy sub metering"
)
lines(data$posix_date, data$Sub_metering_2,type="l",col="red")
lines(data$posix_date, data$Sub_metering_3,type="l",col="blue")
legend("topright",
c("Sub_metering_1","Sub_metering_2", "Sub_metering_3"),
lty=c(1,1,1),
col=c("black", "blue","red")
) # gives the legend lines the correct color and width
axis.POSIXct(1, data$posix_date, format="%a")
dev.off() ## Close the PNG file device
|
872d03bbf047b43e9e5873bb77a5881bb00c272f
|
99e7f60f7cb80ff1f80b3dfd4937210a8552a95f
|
/analysis.R
|
c2f7071a8a38530dc525d2842b302050fe8dc657
|
[] |
no_license
|
YingzhiGou/GameOfGoals
|
3141755b7f700ad4726ceb94b6f2eec43f3b7bc0
|
406652f9348ff1717487ea31a4af81c950a6b51a
|
refs/heads/master
| 2020-09-21T23:19:54.626431
| 2019-12-05T12:22:36
| 2019-12-05T12:22:36
| 183,752,860
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 9,465
|
r
|
analysis.R
|
data.files <- list.files(path="output",
recursive=T,
pattern="*.csv"
,full.names=T)
data = lapply(data.files, read.csv)
library(data.table)
data <- rbindlist(data)
library(grid)
library(gridExtra)
library(ggplot2)
library(ggpubr)
library(Rmisc)
# rename mcts to MCTS
levels(data$Algorithm)[levels(data$Algorithm)=="mcts"] <- "MCTS"
# rename minimax to Minimax
levels(data$Algorithm)[levels(data$Algorithm)=="minimax"] <- "Minimax"
#remove NumConditionActionRules == 10 due to incomplete data
#data <- data[NumConditionActionRules!=10]
data$Time = round(data$Time/1000,4)
# The errorbars overlapped, so use position_dodge to move them horizontally
dodge <- position_dodge(0.05) # move them .05 to the left and right
# =============== LanguageSize~Time by Algorithm ===================
# create a group summary
data.language.group <- summarySE(data, measurevar="Time", groupvar=c("Algorithm", "LanguageSize"))
#plot
figure <- ggplot(data.language.group, aes(x=LanguageSize, y=Time, color=Algorithm)) + # data
geom_errorbar(aes(ymin=Time-se,ymax=Time+se), width=.1, position=dodge) + # errorbar
geom_line(position=dodge) + # line
#scale_y_continuous(trans="log10") + #log10 scale
geom_point(position=dodge, size=2, shape=21, fill="white") +
labs(x="Language Size", y="Time (second)")
show(figure)
ggsave("LanguageSize-Time.png", plot = figure, width=8, height=6, dpi=300)
tbl <- ggtexttable(format(data.language.group,digits=4,scientific = FALSE), rows=NULL, cols=c("Algorithm", "Language\nSize", "N", "Average\nTime (second)", "Standard\nDeviation", "Standard\nError", "Confidence\nInterval (95%)"))
show(tbl)
ggsave("LanguageSize-Time.table.png", plot=tbl)
# =============== NumConditionActionRules~Time by Algorithm ===========
# create a group summary
data.CARules.group <- summarySE(data, measurevar="Time", groupvar=c("Algorithm", "NumConditionActionRules"))
figure <- ggplot(data.CARules.group, aes(x=NumConditionActionRules, y=Time, color=Algorithm)) + # data
geom_errorbar(aes(ymin=Time-ci,ymax=Time+ci), width=.1, position=dodge) + # errorbar
geom_line(position=dodge) + # line
#scale_y_continuous(trans="log10") + #log10 scale
geom_point(position=dodge, size=2, shape=21, fill="white") +
labs(x="Number of Condition Action Rules", y="Time (second)")
show(figure)
ggsave("CARules-Time.png", plot = figure, width=8, height=6, dpi=300)
tbl <- ggtexttable(format(data.CARules.group,digits=4,scientific = FALSE), rows=NULL, cols=c("Algorithm", "Number of Condition-\nAction Rules", "N", "Average\nTime (second)", "Standard\nDeviation", "Standard\nError", "Confidence\nInterval (95%)"))
show(tbl)
ggsave("CARules-Time.table.png", plot=tbl)
# =============== SearchDepth~Time by Algorithm ===========
# create a group summary
data.SearchDepth.group <- summarySE(data, measurevar="Time", groupvar=c("Algorithm", "SearchDepth"))
figure <- ggplot(data.SearchDepth.group, aes(x=SearchDepth, y=Time, color=Algorithm)) + # data
geom_errorbar(aes(ymin=Time-ci,ymax=Time+ci), width=.1, position=dodge) + # errorbar
geom_line(position=dodge) + # line
# scale_y_continuous(trans="log10") + #log10 scale
geom_point(position=dodge, size=3, shape=21, fill="white") +
labs(x="Search Depth", y="Time (second)")
show(figure)
ggsave("SearchDepth-Time.png", plot = figure, width=8, height=6, dpi=300)
tbl <- ggtexttable(format(data.SearchDepth.group,digits=4,scientific = FALSE), rows=NULL, cols=c("Algorithm", "Search Depth", "N", "Average\nTime (second)", "Standard\nDeviation", "Standard\nError", "Confidence\nInterval (95%)"))
show(tbl)
ggsave("SearchDepth-Time.table.png", plot=tbl)
# ================ heatmap LanguageSize - NumConditionActionRules ============
data.LanguageSize.NumCondationActionRules.MCTS.group <- summarySE(data[data$Algorithm=="MCTS"], measurevar = "Time", groupvar=c("LanguageSize", "NumConditionActionRules"))
figure <- ggplot(data.LanguageSize.NumCondationActionRules.MCTS.group, aes(x=LanguageSize, y=NumConditionActionRules, fill=Time)) +
geom_raster() +
#scale_fill_gradient(low="#EEEEEE", high="#000000") +
labs(x="Language Size", y="Number of Condition-Action Rules", fill="Time (second)")
show(figure)
data.LanguageSize.NumCondationActionRules.Minimax.group <- summarySE(data[data$Algorithm=="Minimax"], measurevar = "Time", groupvar=c("LanguageSize", "NumConditionActionRules"))
figure <- ggplot(data.LanguageSize.NumCondationActionRules.Minimax.group, aes(x=LanguageSize, y=NumConditionActionRules, fill=Time)) +
geom_raster() +
#scale_fill_gradient(low="#EEEEEE", high="#000000") +
labs(x="Language Size", y="Number of Condition-Action Rules", fill="Time (second)")
show(figure)
# ================= heatmap LanguageSize - SearchDepth ============
data.LanguageSize.SearchDepth.MCTS.group <- summarySE(data[data$Algorithm=="MCTS"], measurevar = "Time", groupvar=c("LanguageSize", "SearchDepth"))
figure <- ggplot(data.LanguageSize.SearchDepth.MCTS.group, aes(x=LanguageSize, y=SearchDepth, fill=Time)) +
geom_raster() +
#scale_fill_gradient(low="#EEEEEE", high="#000000") +
labs(x="Language Size", y="Search Depth", fill="Time (second)")
show(figure)
data.LanguageSize.SearchDepth.Minimax.group <- summarySE(data[data$Algorithm=="Minimax"], measurevar = "Time", groupvar=c("LanguageSize", "SearchDepth"))
figure <- ggplot(data.LanguageSize.SearchDepth.Minimax.group, aes(x=LanguageSize, y=SearchDepth, fill=Time)) +
geom_raster() +
#scale_fill_gradient(low="#EEEEEE", high="#000000") +
labs(x="Language Size", y="Search Depth", fill="Time (second)")
show(figure)
# ================ heatmap SearchDepth - NumConditionActionRules ============
data.SearchDepth.NumCondationActionRules.MCTS.group <- summarySE(data[data$Algorithm=="MCTS"], measurevar = "Time", groupvar=c("SearchDepth", "NumConditionActionRules"))
figure <- ggplot(data.SearchDepth.NumCondationActionRules.MCTS.group, aes(x=SearchDepth, y=NumConditionActionRules, fill=Time)) +
geom_raster() +
#scale_fill_gradient(low="#EEEEEE", high="#000000") +
labs(x="Search Depth", y="Number of Condition-Action Rules", fill="Time (second)")
show(figure)
data.SearchDepth.NumCondationActionRules.Minimax.group <- summarySE(data[data$Algorithm=="Minimax"], measurevar = "Time", groupvar=c("SearchDepth", "NumConditionActionRules"))
figure <- ggplot(data.SearchDepth.NumCondationActionRules.Minimax.group, aes(x=SearchDepth, y=NumConditionActionRules, fill=Time)) +
geom_raster() +
#scale_fill_gradient(low="#EEEEEE", high="#000000") +
labs(x="Search Depth", y="Number of Condition-Action Rules", fill="Time (second)")
show(figure)
# ===========
library(latticeExtra)
mycolors.trans = c("#FF000046", "#00FF0046")
mycolors = c("#FF0000", "#00FF00")
data.LanguageSize.NumCondationActionRules.group <- summarySE(data, measurevar = "Time", groupvar=c("Algorithm", "LanguageSize", "NumConditionActionRules"))
figure <- wireframe(Time~LanguageSize*NumConditionActionRules, data.LanguageSize.NumCondationActionRules.group,
groups = Algorithm,
col.groups=mycolors.trans,
scales = list(arrows=FALSE, col="black",font=10),
xlab = list("Language Size",rot=30),
ylab = list("Number of Condition-Action Rules",rot=-40),
#auto.key=TRUE,
key=list(x = .7, y = .85,
text=list(c("MCTS","Minimax"),col=mycolors),
lines=list(lty=c(1),col=mycolors)),
par.settings = list(axis.line = list(col = "transparent")))
show(figure)
trellis.device(device="png", filename="LanguageSize-ConditionAction.png",width=1024,
height=768)
print(figure)
dev.off()
data.LanguageSize.SearchDepth.group <- summarySE(data, measurevar = "Time", groupvar=c("Algorithm", "LanguageSize", "SearchDepth"))
figure <- wireframe(Time~LanguageSize*SearchDepth, data.LanguageSize.SearchDepth.group,
groups = Algorithm,
col.groups=mycolors.trans,
scales = list(arrows=FALSE, col="black",font=10),
xlab = list("Language Size",rot=30),
ylab = list("Search Depth",rot=-40),
#auto.key=TRUE,
key=list(x = .7, y = .85,
text=list(c("MCTS","Minimax"),col=mycolors),
lines=list(lty=c(1),col=mycolors)),
par.settings = list(axis.line = list(col = "transparent")))
show(figure)
trellis.device(device="png", filename="LanguageSize-SearchDepth.png",width=1024,
height=768)
print(figure)
dev.off()
data.SearchDepth.NumCondationActionRules.group <- summarySE(data, measurevar = "Time", groupvar=c("Algorithm", "SearchDepth", "NumConditionActionRules"))
figure <- wireframe(Time~SearchDepth*NumConditionActionRules, data.SearchDepth.NumCondationActionRules.group,
groups = Algorithm,
col.groups=mycolors.trans,
scales = list(arrows=FALSE, col="black",font=10),
xlab = list("Search Depth",rot=30),
ylab = list("Number of Condition-Action Rules",rot=-40),
#auto.key=TRUE,
key=list(x = .7, y = .85,
text=list(c("MCTS","Minimax"),col=mycolors),
lines=list(lty=c(1),col=mycolors)),
par.settings = list(axis.line = list(col = "transparent")))
show(figure)
trellis.device(device="png", filename="SearchDepth-ConditionAction.png",width=1024,
height=768)
print(figure)
dev.off()
|
39e6d1467246ce0f001602cb79430179c2aa4053
|
d63cddc3eae16b16b0e67d671eacf23cb249af45
|
/R/load-maps.R
|
f808078cb26430980239db948549465063119a5a
|
[
"MIT"
] |
permissive
|
tjmckinley/arear
|
acfb63bd4b2a842600cd95768dfb67659bc39760
|
99523d47021dc88aa21c0b0aeb10395f2f5a3054
|
refs/heads/main
| 2023-06-04T22:34:30.671092
| 2021-06-30T13:45:15
| 2021-06-30T13:45:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 7,024
|
r
|
load-maps.R
|
#' Gets maps for which the metadata is known
#'
#' @param mapId - a name of a map
#' @param sources - a list of map sources - see arear::mapsources
#' @param codeType - defaults to mapId, the codeType of the map
#' @param wd - optional working directory
#'
#' @return a standard sf map
#' @export
#'
#' @examples
#' \dontrun{
#' map = getMap("NHSER20")
#' }
getMap = function(mapId, sources = arear::mapsources, codeType = mapId, wd = getOption("arear.cache.dir",default=tempdir())) {
if (!(mapId %in% names(sources))) stop("Unknown map: ",mapId)
loader = sources[[mapId]]
codeCol = as.symbol(loader$codeCol)
nameCol = tryCatch(as.symbol(loader$nameCol), error = function(e) NULL)
altCodeCol = tryCatch(as.symbol(loader$altCodeCol), error = function(e) NULL)
map = downloadMap(zipUrl = loader$url, mapName = loader$mapName, codeCol = !!codeCol, nameCol = !!nameCol, altCodeCol = !!altCodeCol, codeType=codeType, id=mapId, wd = wd)
return(map)
}
#' List the standard maps available to download
#'
#' @return a vector of map names
#' @export
listStandardMaps = function() {
names(arear::mapsources)
}
#' Download a map, unpack it, and rename columns
#'
#' to standard code, name, altCode and codeType columns
#'
#' @param zipUrl - the URL of the zipped shapefile
#' @param mapName - the layer name or map name - this is the "xyz" of a zip file containing "xyz.shp"
#' @param codeCol - the name of the column containing the id or code
#' @param nameCol - the name of the column containing the label (optional - defaults to the same as codeCol)
#' @param altCodeCol - an optional column name containing another code type
#' @param codeType - the "type" of the code - optional. defaults to NA
#' @param simplify - do you want to simplify the map
#' @param wd - an optional working directory (defaults to tempdir)
#' @param id - an optional id for the map - defaults to either the mapName or if not present the name of the zip file.
#'
#' @return a sf object containing the map
#' @export
#'
#' @examples
#' \dontrun{
#' downloadMap(
#' zipUrl="https://opendata.arcgis.com/datasets/87511f3ae00a40208741c685f827c1d3_0.zip?outSR=%7B%22latestWkid%22%3A27700%2C%22wkid%22%3A27700%7D",
#' mapName="NHS_England_Regions__April_2020__Boundaries_EN_BGC",
#' codeCol="nhser20cd",
#' nameCol="nhser20nm"
#' )
#' }
downloadMap = function(zipUrl, mapName=NULL, codeCol="code", nameCol="name", altCodeCol=NULL, codeType=NA_character_, simplify=FALSE, wd = tempdir(), id=NULL) {
codeCol = rlang::ensym(codeCol)
nameCol = tryCatch(rlang::ensym(nameCol), error = function(e) NULL)
altCodeCol = tryCatch(rlang::ensym(altCodeCol), error = function(e) NULL)
pattern = paste0(ifelse(is.null(mapName),"",mapName),"\\.shp$")
if(is.null(id)) {
if(!is.null(mapName)) {
id = fs::path_sanitize(mapName)
} else {
id = zipUrl %>% fs::path_file() %>% fs::path_ext_remove()
}
}
.cached({
onsZip = paste0(wd,"/",id,".zip")
unzipDir = paste0(wd,"/",id)
if(!file.exists(onsZip)) {
status = download.file(zipUrl, destfile = onsZip)
if (status != 0) stop("Problem downloading map: ",zipUrl)
}
suppressWarnings(dir.create(unzipDir,recursive = TRUE))
paths = unzip(onsZip, exdir=unzipDir, junkpaths = TRUE)
if(length(paths) < 1) stop("Could not extract files from shapefile zip: ",onsZip)
mapFile = paste0(unzipDir,"/",list.files(unzipDir,recursive = TRUE,pattern = pattern))
if(length(mapFile)!=1) stop("More than one matching map has been found: ",mapFile)
map = sf::st_read(mapFile) %>% sf::st_transform(crs=4326)
map = standardiseMap(map, !!codeCol, !!nameCol, !!altCodeCol, codeType)
if(simplify) map = suppressWarnings(map %>% rmapshaper::ms_simplify(keep=0.1))
map %>% dplyr::ungroup() %>% sf::st_as_sf()
}, name=id, hash=list(zipUrl,mapName,codeCol,nameCol,altCodeCol,codeType,simplify))
}
#' Standardise maps to a minimal set of attributes with consistent naming with code, name and codeType columns and an optional altCode column
#'
#' @param sf - a non standard map
#' @param codeCol - a column name containing the unique code or id for the map
#' @param nameCol - the name column
#' @param altCodeCol - an alternative code column
#' @param codeType - a fixed vlue for the codeType
#'
#' @return a standardised map
#' @export
standardiseMap = function(sf, codeCol, nameCol, altCodeCol, codeType) {
codeCol = rlang::ensym(codeCol)
nameCol = tryCatch(rlang::ensym(nameCol), error = function(e) NULL)
altCodeCol = tryCatch(rlang::ensym(altCodeCol), error = function(e) NULL)
sf = sf %>% dplyr::mutate(tmp_code = as.character(!!codeCol))
#TODO: catch missing columns and throw helpful error
if(!as.character(codeCol) %in% colnames(sf)) stop("the codeCol column is not present in sf should be one of: ",paste(colnames(sf),collapse = ","))
if(!identical(nameCol,NULL)) {
if(!as.character(nameCol) %in% colnames(sf)) stop("the nameCol column is not present in sf should be one of: ",paste(colnames(sf),collapse = ","))
sf = sf %>% dplyr::mutate(tmp_name = as.character(!!nameCol))
sf = sf %>% dplyr::select(-!!nameCol)
} else {
sf = sf %>% dplyr::mutate(tmp_name = as.character(!!codeCol))
}
sf = sf %>% dplyr::select(-!!codeCol) %>% dplyr::rename(code = tmp_code,name = tmp_name)
if(!identical(altCodeCol,NULL)) {
if(!as.character(altCodeCol) %in% colnames(sf)) stop("the altCodeCol column is not present in sf should be one of: ",paste(colnames(sf),collapse = ","))
sf = sf %>% dplyr::rename(altCode = !!altCodeCol) %>% dplyr::mutate(altCode = as.character(altCode))
} else {
sf = sf %>% dplyr::mutate(altCode = as.character(NA))
}
sf = sf %>% dplyr::mutate(codeType = codeType) %>% dplyr::select(codeType, code, name, altCode)
sf$area = sf %>% sf::st_area() %>% as.numeric()
return(sf %>% sf::st_zm())
}
#' save a shapefile to disk in the current working directory
#'
#' @param shape - the sf shape
#' @param mapId - a mapId - will become the zip filename, and the filename of the zipped .shp file
#' @param dir - the directory (defaults to current working directory)
#' @param overwrite - the save function will not write over existing files unless this is set to true
#'
#' @return a the filename of the zipped shapefile
#' @export
saveShapefile = function(shape, mapId, dir=getwd(), overwrite=FALSE) {
if (!dir %>% stringr::str_ends("/")) dir = paste0(dir,"/")
zipDir = paste0(dir,mapId)
if (dir.exists(zipDir) & !overwrite & length(list.files(zipDir))>0) stop("Directory ",zipDir," exists and is not empty. use overwrite=TRUE to force update")
if (dir.exists(zipDir)) unlink(zipDir, recursive=TRUE)
dir.create(zipDir, recursive = TRUE)
suppressWarnings(sf::st_write(shape, paste0(zipDir,"/",mapId, ".shp"), driver="ESRI Shapefile"))
wd = getwd()
setwd(dir) # the parent directory
zip(zipfile = paste0(zipDir,".zip"),files=mapId) #zip the directory
setwd(wd)
unlink(zipDir, recursive=TRUE)
return(paste0(zipDir,".zip"))
}
|
b976bd8c15f3cc853e55cbd997b22adcfa4b88b2
|
9ea74e7e088c6351ac4d29522529c0e79b51dcc4
|
/man/parse.formula.Rd
|
d10366391ec7284baa59d72de5bd2400ced84a84
|
[] |
no_license
|
imbs-hl/ranger
|
0ccd500db3cd97e5fda5d3b150517c71ed55ade6
|
5a04d9355a1a96315973d88492160bc00a91e399
|
refs/heads/master
| 2023-08-17T01:09:34.455853
| 2023-08-16T09:26:19
| 2023-08-16T09:26:19
| 41,377,351
| 739
| 245
| null | 2023-09-12T20:10:46
| 2015-08-25T17:18:39
|
C++
|
UTF-8
|
R
| false
| true
| 732
|
rd
|
parse.formula.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/formula.R
\name{parse.formula}
\alias{parse.formula}
\title{Parse formula}
\usage{
parse.formula(formula, data, env = parent.frame())
}
\arguments{
\item{formula}{Object of class \code{formula} or \code{character} describing the model to fit.}
\item{data}{Training data of class \code{data.frame}.}
\item{env}{The environment in which the left hand side of \code{formula} is evaluated.}
}
\value{
Dataset including selected columns and interactions.
}
\description{
Parse formula and return dataset containing selected columns.
Interactions are supported for numerical columns only.
An interaction column is the product of all interacting columns.
}
|
f6f10fa9cfac3d46246a2a22a5544fd76097d73a
|
f26781b86f2dea0394809d1951bad4550d82ba3c
|
/module/_module_summaryTab.R
|
a9a30f7dbab3105826631a5dd5f2ea3c4d96b302
|
[] |
no_license
|
fyang72/handbook
|
0ac0d616f033747347bce3fe72219223a2553ab8
|
89abb7b557b83d9b651821780b92410623aaa9a2
|
refs/heads/master
| 2022-09-30T10:36:14.303860
| 2019-12-16T19:32:13
| 2019-12-16T19:32:13
| 171,066,670
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 13,808
|
r
|
_module_summaryTab.R
|
################################################################################
################################################################################
# summaryTab
################################################################################
################################################################################
summaryTabUI <- function(id, label="") {
# Create a namespace function using the provided id
ns <- NS(id)
fluidRow(
column(4,
fluidRow(
box(width=12, title="Load data and filter", collapsible = TRUE, collapsed = FALSE, solidHeader = TRUE, status = "primary" ,
column(6,
# data and filter
uiOutput(ns("data_selector")),
uiOutput(ns("test_selector")),
tags$hr(style="border-color: black;"),
uiOutput(ns("dose_group_selector"))
),
column(6,
# x-variable, y-variable, and group_by
uiOutput(ns("summarise_by_selector")),
uiOutput(ns("valueCol_selector")),
tags$hr(style="border-color: black;")
)) # box
) # end of fluidRow
), # end of left column
column(8,
fluidRow(
box(width=12, title="Derived data", collapsible = TRUE, collapsed = FALSE, solidHeader = TRUE, status = "primary" ,
column(width=4, #status = "primary", #class = 'rightAlign', #background ="aqua",
textInput(ns("tab_name"), value="Tab-", label=NULL,
placeholder = "Enter data name here:")),
column(width=4, #align="left", offset = 0,
actionButton(ns("addToCart"), label="Add to cart", style=actionButton.style)),
column(width=4, #status = "primary", #class = 'rightAlign', #background ="aqua",
checkboxInput(ns("spreadOut"), label ="?Spreadout", value=FALSE)),
uiOutput(ns('summaryTab_container')))
)
)
)
}
# If a module needs to use a reactive expression, take the reactive expression as a
# function parameter. If a module wants to return reactive expressions to the calling app,
# then return a list of reactive expressions from the function.
#
#If a module needs to access an input that isn?t part of the module, the containing app
#should pass the input value wrapped in a reactive expression (i.e. reactive(...)):
# Module server function
################################################################################
################################################################################
# summaryTab
################################################################################
################################################################################
summaryTab <- function(input, output, session, DATA, TABLE_ALL) {
ns <- session$ns
EPS = 1E-3
values <- reactiveValues()
print("in summaryTab::::::")
#-----------------------------------------
# data_selector
#-----------------------------------------
output$data_selector <- renderUI({
if (is.null(DATA$mDATA)) {return(NULL)}
data.lst = c("NULL", unique(names(DATA$mDATA)))
selectizeInput(ns("data_name"),
label = "select which dataset:" ,
choices = data.lst, #unique(inputData()%>%pull(TEST)),
multiple = FALSE,
selected = data.lst[1]) #unique(inputData()%>%pull(TEST))[1])
})
#-----------------------------------------
# test_selector
#-----------------------------------------
output$test_selector <- renderUI({
data = inputData()
if (is.null(data)) {return(NULL)}
test.lst = c("", unique(data$TEST))
selectizeInput(ns("test"),
label = "select which test variable:" ,
choices = test.lst,
multiple = FALSE,
selected = test.lst[1])
})
#-----------------------------------------
# summarise_by_selector
#-----------------------------------------
output$summarise_by_selector <- renderUI({
data = inputData()
TEST_VARS = "TEST"
STUDYID_VARS = "STUDYID"
ARMA_VARS = "ARMA"
NTIM_VARS = ifelse(NTIM_VARS(data)!="", NTIM_VARS(data),
ifelse(TIME_VARS(data)!="", TIME_VARS(data), ""))
selectizeInput(ns("summarise_by"), label ="Summarise by", #h5()
choices = c(colnames(data)),
multiple = TRUE,
selected = c(STUDYID_VARS, ARMA_VARS, NTIM_VARS, TEST_VARS))
})
#-----------------------------------------
# valueCol_selector
#-----------------------------------------
output$valueCol_selector <- renderUI({
data = inputData()
DVOR = DVOR_VARS(data)
selectizeInput(ns("valueCol"),
label = "select valueCol:" ,
choices = colnames(data),
multiple = FALSE,
selected = ifelse(DVOR!="NULL", DVOR, colnames(data)[1]))
})
#-----------------------------------------
# group_by_selector
#-----------------------------------------
output$group_by_selector <- renderUI({
data = errbarTabb()
selectizeInput(ns("group_by"), label ="Group by", #h5()
choices = c(colnames(data)),
multiple = TRUE,
selected = c("ARMA"))
})
#-----------------------------------------
# dose_group_selector
#-----------------------------------------
output$dose_group_selector <- renderUI({
data = inputData()
if(is.null(data)) {return(NULL)}
if(is.null(data$ARMA)) {return(NULL)}
checkboxGroupInput(ns("dose_group"), label="Filter by dose groups",
choices = unique(as.character(data$ARMA)),
selected= unique(as.character(data$ARMA)) )})
#-----------------------------------------
# tab_title_selector
#-----------------------------------------
#value = "Figure title: Mean (+SE) Log-scaled Concentrations of xxxxx in Serum vs. Nominal Sampling Day
#Following a Single IV Dose of xxxx (Study xxxx-HV-1219"))),
output$tab_title_selector <- renderUI({
data = inputData()
patient.name = "Healthy Volunteers"
dosing.name = paste0("a Single Subcutaneous or Intravenous Dose(s)")
drug.name = substr(data$STUDYID, 1, 5)
study.name = unique(data$STUDYID)
tab.title = paste("Summary of", input$test, "by", paste(input$summarise_by, collapse=", "),
"in Study", study.name, sep=" ")
#tab.title = "tabure title: Mean (+SE) Log-scaled Concentrations of xxxxx in Serum vs. Nominal Sampling Day Following a Single IV Dose of xxxx (Study xxxx-HV-1219"
textAreaInput(ns("tab_title"), label = NULL, width='1040px', value = tab.title)})
#-----------------------------------------
# tab_footnote_selector
#-----------------------------------------
#"Note: Concentrations below the lower limit of quantification (LLOQ) are set to zero.", sep="") }
#footnote = paste("QW = Once a week; Q2W = Once every two weeks; Q4W = Once every four weeks; SC = Subcutaneous; IV = Intravenous. Note: Concentrations below the lower limit of quantification (LLOQ, horizontal dotted line = ", LLOQ, " mg/L) are imputed as LLOQ/2 = ", round(LLOQ/2, digits=3), " mg/L.", sep="")
output$tab_footnote_selector <- renderUI({
textAreaInput(ns("tab_footnote"), label = NULL, width='1040px',
value = "Note: QW = Once a week; Q2W = Once every two weeks; Q4W = Once every four weeks; SC = Subcutaneous; IV = Intravenous. Concentrations below the lower limit of quantification (LLOQ) are set to zero. ")})
#*****************************************
# inputData
#*****************************************
# select which dataset(s)
inputData <- reactive({
if (is.null(input$data_name)) {return(NULL)}
if (input$data_name=="NULL") {return(NULL)}
data = DATA$mDATA[[input$data_name]]
if (is.null(data)) {return(NULL)}
if (is.null(data$TEST)) {data$TEST= "xxxx"}
data
})
#*****************************************
# errbarTabb
#*****************************************
# select which dataset(s)
errbarTabb <- reactive({
data = inputData()
validate(need(data, message=FALSE),
need(input$dose_group, message=FALSE),
need(input$test, message=FALSE),
need(input$valueCol, message=FALSE)
)
data <- data %>% filter(ARMA %in% input$dose_group)
if (is.null(data)) {return(NULL)}
if (is.null(input$test)) {return(NULL)}
#data = errbarTab8(data, input, session, EPS = 1e-3) %>% select_( "ARMA", "NTIM", "N", "Mean_SD", "Mean_SE", "Median_Range")
if(!is.null(data$ARMA) & !is.null(input$dose_group)) {data = data %>% filter(ARMA %in% input$dose_group) }
data = data %>% filter(TEST %in% input$test)
validate(need(input$summarise_by, message="missing summarise_by"),
need(input$valueCol, message="missing valueCol"),
need("USUBJID" %in% colnames(data), message= "missing USUBJID in colnames(data)")
)
pkSummary = data %>% calc_stats(id="USUBJID", group_by=input$summarise_by, value=input$valueCol) %>%
select(one_of(input$summarise_by), N, Mean, SD, Mean_SD) # calculate the statistics
pkSummary
# print(head(data)%>% as.data.frame())
# print(colnames(data))
#
# col.lst = c("STUDYID", "ARMA", "NTIM", "N", "Mean_SD", "Mean_SE", "Median_Range")
# col.lst = intersect(col.lst, colnames(data))
# print(col.lst)
#
# data %>% select_(col.lst)
#print(head(data) %>% as.data.frame())
})
#
# ## use renderUI to display table
#https://rstudio.github.io/DT/
output$summaryTab_container <- renderUI({
pkSummary <- errbarTabb()
if (input$spreadOut==1) {pkSummary <- pkSummary %>% select(-Mean, -SD) %>% spread(key=TEST, value=Mean_SD) }
output$summaryTab <- DT::renderDataTable(
DT::datatable(data = pkSummary,
options = list(pageLength = 10, lengthChange = FALSE, width="100%", scrollX = TRUE)
#filter = 'top', # bottom',
#caption = htmltools::tags$caption(
# style = 'caption-side: bottom; text-align: center;',
# 'Table 2: ', htmltools::em('This is a simple caption for the table.')
# )
)
)
#rownames = FALSE,
# width="100%",
#autoWidth = FALSE
# aLengthMenu = c(5, 30, 50), iDisplayLength = 6, bSortClasses = TRUE,
# bAutoWidth = FALSE,
# aoColumn = list(list(sWidth = "150px", sWidth = "30px",
# sWidth = "30px", sWidth = "30px"))
#columnDefs = list(list(width = '200px', targets = "_all"))
DT::dataTableOutput(ns("summaryTab"))
})
#add figure to log when action button is pressed
observeEvent(input$addToCart, {
#req(input$addToCart, TABLE_ALL, input$tab_name)
if(is.null(input$addToCart)) {return()}
if(input$addToCart == 0) return()
cat(file=stderr(), "##############Step: tab add2Cart #################", "\n")
#CurrentLog <- TABLE_ALL$mTABLES #####################
CurrentLog_mTABLES <- isolate(TABLE_ALL$mTABLES)
newTab <- errbarTabb()
#newTab <- (isolate(newTab))
col.lst = c("STUDYID", "ARMA", "NTIM", "N", "Mean_SD", "Median_Range")
col.lst = intersect(col.lst, colnames(newTab))
newTab <- newTab %>% ungroup()
#if (!is.null(newTab$NTIM)) {newTab <- newTab %>% select(STUDYID, ARMA, TEST, NTIM, N, Mean_SD, Median_Range) }
#if (is.null(newTab$NTIM)) {newTab <- newTab %>% select(STUDYID, ARMA, TEST, N, Mean_SD, Median_Range) }
tab_name <- isolate(input$tab_name)
#names(newTab) = tab_name
CurrentLog_mTITLES <- isolate(TABLE_ALL$mTITLES)
newTitle <- (input$tab_title)
names(newTitle) = tab_name
CurrentLog_mFOOTNOTES <- isolate(TABLE_ALL$mFOOTNOTES)
newFootnote <- (input$tab_footnote)
names(newFootnote) = tab_name
if (!tab_name %in% names(CurrentLog_mTABLES)) {
#TABLE_ALL$mTITLES <- c(CurrentLog_mTITLES,newTitle)
#TABLE_ALL$mTABLES <- c(CurrentLog_mTABLES,newTab)
#TABLE_ALL$mFOOTNOTES <- c(CurrentLog_mFOOTNOTES,newFootnote)
TABLE_ALL$mTITLES[[tab_name]] <- newTitle
TABLE_ALL$mTABLES[[tab_name]] <- newTab
TABLE_ALL$mFOOTNOTES[[tab_name]] <- newFootnote
TABLE_ALL$NumOfTab <- isolate(TABLE_ALL$NumOfTab) + 1
}else{
TABLE_ALL$mTITLES[[tab_name]] <- newTitle
TABLE_ALL$mTABLES[[tab_name]] <- newTab
TABLE_ALL$mFOOTNOTES[[tab_name]] <- newFootnote
cat(file=stderr(), "##############Warning: tab_name exist, override will occur! #################", "\n")
#validate(
# need(!tab_name %in% names(CurrentLog_mTABLES), "tab_name already exist, override will occur! ")
#)
}
})
# Return the reactive that yields the data frame
return(TABLE_ALL)
}
|
5a92036064f50da1a54ad2b67fdfba786407cc63
|
bccaf9ca75d67fef6bec733e784c582149a32ed1
|
/plagiat/R/jpdf2imp.f.R
|
fca845e05a18272d9d9c6d2a06aafc6b4d269928
|
[] |
no_license
|
brooksambrose/pack-dev
|
9cd89c134bcc80711d67db33c789d916ebcafac2
|
af1308111a36753bff9dc00aa3739ac88094f967
|
refs/heads/master
| 2023-05-10T17:22:37.820713
| 2023-05-01T18:42:08
| 2023-05-01T18:42:08
| 43,087,209
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,398
|
r
|
jpdf2imp.f.R
|
#' JSTOR PDF to imp
#'
#' @param jpdf Vector of full paths to every pdf you with to import.
#' @param ocr
#' @param depth
#' @param ncores
#' @param logdir
#'
#' @import data.table stringr pdftools stringdist igraph progress
#'
#' @return
#' @export
#'
#' @examples
jpdf2imp.f<-function(jpdf,ocr=F,depth=5,ncores,logdir){
# parallel always seems slower
if(missing(ncores)) ncores<-c(1,parallel::detectCores()/2 %>% ceiling) %>% max
ncores<-1
# import
jimp<-function(x) {
x<-pdf_text(x) %>% as.list
# find last cover page, usually only one except in long titles
w<-grep('collaborating with JSTOR to digitize preserve and extend access' %>% strsplit(' ') %>% unlist %>% paste(collapse='[\n, ]+'),x)[1]
if(is.na(w)) w<-0
if(w>1){
x[w]<-x[1:w] %>% unlist %>% paste(collapse='\n')
x[0:(w-1)]<-NULL
x[[1]] %<>% sub('This content downloaded from[^\n]+','',.) %>% sub('All use subject to[^\n]+','',.)
}
x<-strsplit(unlist(x),'\n')
attr(x,'ncp')<-w
x
}
cat('Importing text from',length(jpdf),'pdfs:\n')
imp<-pbapply::pblapply(jpdf,cl=ncores,jimp)
# separate cover page
cp<-lapply(imp,function(x) x[[1]])
for(i in 1:length(imp)) imp[[i]][1]<-NULL
ncp<-sapply(imp,attr,'ncp')
# ocr
oc<-lapply(imp,sapply,length) %>% sapply(function(x) any((1:3)%in%x)) %>% which
if(length(oc)){
cat('\n',length(oc),' undigitized documents detected.',sep='')
if(!missing(logdir)) writeLines(jpdf[oc],paste(logdir,'log_badocr.txt',sep=.Platform$file.sep))
if(!ocr) {
cat(' Removing from corpus:',basename(jpdf[oc]),sep='\n')
dropped<-jpdf[oc]
jpdf<-jpdf[-oc]
cp<-cp[-oc]
imp<-imp[-oc]
} else {
ol<-sapply(jpdf[oc],function(x) suppressMessages(pdftools::pdf_info(x))$pages,simplify = F,USE.NAMES = T)
ol<-mapply(seq,to=ol,from=ncp[oc]+1,USE.NAMES = T,SIMPLIFY = F)
ol<-mapply(function(d,p) list(d=d,p=p)
,d=rep(names(ol),sapply(ol,length))
,p=unlist(ol)
,SIMPLIFY = F,USE.NAMES = F)
cat(' Performing optical character recognition on',length(ol),'pages:\n')
tocr<-function(y) {
x<-pdftools::pdf_convert(
pdf = y$d
,dpi=300
,pages=y$p
,filenames = tempfile(pattern = sub('.pdf',sprintf('_%03d_',y$p),basename(y$d)),fileext = '.png')
,verbose = F
)
invisible(tesseract::ocr(x)) %>% gsub('\n\n+','\n ',.) %>% strsplit('\n') %>% `[[`(1)
}
imp[oc]<-pbapply::pblapply(ol,cl=ncores,tocr) %>% split(sapply(ol,`[[`,'d'))
}
}
# metadata key if cover page
if(sum(ncp)) {
met<-data.table(
title=sapply(cp,function(x) {
b<-grep('^Author',x)
if(!length(b)) b<-grep('^Source',x)
x[1:(b-1)] %>% paste(collapse=' ') %>% sub(' +',' ',.)
})
,author=lapply(cp,function(x) {
b<-grep('^Author',x)
e<-grep('^Source',x)
if((!length(b))|(!length(e))) return('')
x[b:(e-1)] %>% paste(collapse=' ') %>% sub('^[^:]+: ','',.) %>% str_split(',|( and )') %>% unlist %>%
sub('^ *','',.) %>% sub(' *$','',.) %>% sub(' +',' ',.) %>% `[`(.!='')
})
,source=lapply(cp,function(x) {
b<-grep('^Source',x)
e<-grep('^Published',x)
x[b:(e-1)] %>% paste(collapse=' ') %>% sub('^[^:]+: ','',.) %>% str_split('[,)(]') %>% unlist %>%
sub('^ *','',.) %>% sub(' *$','',.) %>% sub(' +',' ',.) %>% `[`(.!='')
})
,url=sapply(cp,function(x) {
b<-grep('^Stable',x)
x[b] %>% sub('^[^:]+: ','',.) %>% sub('^ *','',.) %>% sub(' *$','',.)
})
,accessed=sapply(cp,function(x) {
b<-grep('^Accessed',x)
x[b] %>% sub('^[^:]+: ','',.) %>% sub('^ *','',.) %>% sub(' *$','',.)
})
)
met[,doc:=jpdf]
met[,`:=`(
journal=sapply(source,`[`,1)
,year=sapply(source,function(x) grep('^[0-9]{4}$',x,value = T) %>% tail(1))
)]
met[,ncp:=ncp]
setcolorder(met,c('doc','journal','year','title','author','source','url','accessed','ncp'))
}
# header detection, accurate solution is too slow
clusth<-function(y) {
y<-gsub(' +',' ',y)
m<-1-stringdistmatrix(y,y,method = 'jw',p = .1)
n<-graph_from_adjacency_matrix(m,'undirected',weighted=T)
if(is_connected(n)) {c<-cluster_spinglass(n) %>% communities}else{c<-cluster_walktrap(n) %>% communities}
r<-data.table(c=c)
r[,s:=sapply(c,function(x) E(induced_subgraph(n,x))$weight%>% mean)]
r<-r[sapply(c,length)>1]
r
}
h<-lapply(imp,function(x) {
d<-c(depth,sapply(x,length)) %>% min
sapply(x,function(y) {head(y,d)}) %>% t %>% data.table %>% setnames(paste0('h',1:ncol(.)))})
f<-lapply(imp,function(x) {
d<-c(depth,sapply(x,length)) %>% min
sapply(x,function(y) {tail(y,d)}) %>% t %>% data.table %>% setnames(paste0('f',1:ncol(.)))})
# headers not removed from single page articles, need to revisit at volume level rather than paper level
il<-sapply(imp,length)==1
cat('\nHeader detection:\n')
hc<-pbapply::pblapply(h[!il],cl=ncores,function(x) lapply(x,clusth))
cat('\nFooter detection:\n')
fc<-pbapply::pblapply(f[!il],cl=ncores,function(x) lapply(x,clusth))
ix<-(1:length(imp))[!il]
for(i in ix){
l<-sapply(imp[[i]],length)
hdrop<-sapply(hc[[which(ix==i)]],function(x) x[,mean(s)>.9&.N<5]) %>% which
for(j in 1:length(l)) {
fdrop<-tail(1:l[j],depth)[sapply(fc[[which(ix==i)]],function(x) x[,mean(s)>.9&.N<5]) %>% which]
imp[[i]][[j]]<-imp[[i]][[j]][-c(hdrop,fdrop) %>% na.omit]
}
}
# paragraph detection
cat('\nParagraph detection:\n')
par<-function(i,cn=c('doc','pag','lin','par','txt')) {
x<-imp[[i]]
pag<-1:length(x) %>% rep(sapply(x,length))
lin<-sapply(x,length) %>% `[`(!!.) %>% lapply(seq) %>% unlist
txt<-x %>% unlist
if(length(pag)!=length(lin)|length(lin)!=length(txt)|length(pag)!=length(txt)) browser()
x<-data.table(
pag
,lin
,txt
)
x[,es:=grepl('[.!?\'\",]$',txt)]
x[,bp:=grepl(' {3,6}',txt)]
x[,par:=c(T,es[-.N]&bp[-1]) %>% cumsum]
x[,doc:=jpdf[i]]
x[,setdiff(names(x),cn):=NULL]
setcolorder(x,cn)
x
}
imp<-pbapply::pblapply(1:length(imp),cl=ncores,par)
imp<-rbindlist(imp) %>% setkey(doc)
if(sum(ncp)) {
setkey(met,doc)
imp<-list(imp=imp,met=met)
} else {
imp<-list(imp=imp)
}
imp
}
|
99af36cf7586d53009a742a6035e061a77936c27
|
1cb8211da96b773389dec14a5bee30a8cc98f9df
|
/R/connectivity_score-methods.R
|
e3edca33a0f2fe7a760501f0b246779b922a6353
|
[] |
no_license
|
albert-ying/gCMAP_mod
|
2843b38ad18447c7984684ee76cf11976388781b
|
99b600ced1dba9a0fd1c388a1081b8ca14101e1a
|
refs/heads/master
| 2023-02-15T05:26:22.017484
| 2021-01-05T02:04:09
| 2021-01-05T02:04:09
| 326,838,682
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,956
|
r
|
connectivity_score-methods.R
|
setMethod(
"connectivity_score",
signature(experiment = "eSet", query = "CMAPCollection"),
function(experiment, query, element = "z", keep.scores = FALSE) {
if (!(element %in% assayDataElementNames(experiment))) {
stop("Requested element name not found in data.")
}
if (any(signed(query) == FALSE)) {
stop("CMAPCollection contains unsigned GeneSets, which lack the information
about up-/down-regulated categories required to compute the connectivity score.")
}
## rank data matrix in descending order
data.matrix <- as(assayDataElement(experiment, element), "matrix")
## subset objects to shared genes
matched.features <- match(featureNames(experiment), featureNames(query))
matched.sets <- query[na.omit(matched.features), ]
## extract scores for each gene set
sets.up <- mclapply(
seq(ncol(matched.sets)),
function(x) which(members(matched.sets)[, x] == 1)
)
sets.down <- mclapply(
seq(ncol(matched.sets)),
function(x) which(members(matched.sets)[, x] == -1)
)
## transform experiment to (reverse) ranks
rank.matrix <- apply(data.matrix, 2, function(x) {
length(x) - rank(x) + 1
})
## calculate connectivity score
raw.score <- apply(rank.matrix, 2, function(r) {
sapply(seq_along(sets.up), function(n) {
.s(r[sets.up[[n]]], r[sets.down[[n]]], length(r))
})
})
raw.score <- matrix(raw.score, ncol = ncol(experiment))
## scale score across all profiles
score <- apply(raw.score, 1, .S)
score <- matrix(score, ncol = ncol(experiment))
## store raw per-gene expression scores
if (keep.scores == TRUE) {
gene.scores <- featureScores(experiment, query, element = element)
} else {
gene.scores <- NA
}
## store results
results <- mclapply(seq(ncol(experiment)), function(x) { ## x = data column
if (!all(is.na(gene.scores))) {
geneScores <- I(gene.scores[[x]])
} else {
geneScores <- NA
}
res <- CMAPResults(
data = data.frame(
set = sampleNames(query),
trend = ifelse(score[, x] >= 0, "up", "down"),
effect = score[, x],
nSet = Matrix::colSums(abs(members(query))),
nFound = Matrix::colSums(abs(members(matched.sets))),
geneScores = geneScores,
pData(query)
),
docs = " \n Scores were calculated and scaled according to Lamb, J. et al. (2006)."
)
varMetadata(res)$labelDescription <-
c(
"SetName",
"Direction",
"Scaled connectivity score",
"Number of genes annotated in the query set",
"Number of genes set members found in the dataset",
"Per-gene raw scores",
colnames(pData(query))
)
res
})
names(results) <- sampleNames(experiment)
## return single CMAPResults of list of CMAPResults objects
if (length(results) == 1) {
return(results[[1]])
} else {
return(results)
}
}
)
setMethod(
"connectivity_score",
signature(experiment = "matrix", query = "CMAPCollection"),
function(experiment, query, ...) {
connectivity_score(ExpressionSet(experiment), query, element = "exprs")
}
)
setMethod(
"connectivity_score",
signature(experiment = "matrix", query = "SignedGeneSet"),
function(experiment, query, ...) {
connectivity_score(ExpressionSet(experiment), as(query, "CMAPCollection"), element = "exprs")
}
)
setMethod(
"connectivity_score",
signature(experiment = "eSet", query = "SignedGeneSet"),
function(experiment, query, ...) {
connectivity_score(experiment, as(query, "CMAPCollection"))
}
)
setMethod(
"connectivity_score",
signature(experiment = "matrix", query = "GeneSetCollection"),
function(experiment, query, ...) {
connectivity_score(ExpressionSet(experiment), as(query, "CMAPCollection"), element = "exprs")
}
)
setMethod(
"connectivity_score",
signature(experiment = "eSet", query = "GeneSetCollection"),
function(experiment, query, ...) {
connectivity_score(experiment, as(query, "CMAPCollection"), ...)
}
)
setMethod(
"connectivity_score",
signature(experiment = "ANY", query = "GeneSet"),
function(experiment, query, ...) {
stop("Connectivity score calculation requires gene sign information (up- / down- regulated gene categories).\n")
}
)
.ks <- function(V, n) {
t <- length(V)
if (t == 0) {
return(0)
} else {
if (is.unsorted(V)) {
V <- sort(V)
}
d <- (1:t) / t - V / n
a <- max(d)
b <- -min(d) + 1 / t
ifelse(a > b, a, -b)
}
}
.s <- function(V_up, V_down, n) {
ks_up <- .ks(V_up, n)
ks_down <- .ks(V_down, n)
ifelse(sign(ks_up) == sign(ks_down), 0, ks_up - ks_down)
}
.S <- function(scores) {
p <- max(scores)
q <- min(scores)
ifelse(
scores == 0,
0,
ifelse(scores > 0, scores / p, -scores / q)
)
}
|
55f6644fdbb02fc1b6f2db94cb886284bb9d5378
|
2d00505c7940f1bd1dcff122aa1e8bbd5d2edea2
|
/R/bindings.R
|
487d835f797351f59abd202d456ecfaa2d64ad72
|
[] |
no_license
|
kashenfelter/RGCCTranslationUnit
|
cb647e6c57e78656bb196e68834d60fd664e66cd
|
1bd45f5589516334afa57a75e936d2a36ff943b6
|
refs/heads/master
| 2020-03-23T00:32:22.815755
| 2013-04-21T21:38:45
| 2013-04-21T21:38:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 69,435
|
r
|
bindings.R
|
# Deal with structures, not just pointers to them, as arguments
# and also generate get and set methods for them.
# Default constructor if none present.
# or perhaps, just anyway.
# What is vfld? virtual?
# Yep.
# Get overloaded methods across classes,
# perhaps simply if they are virtual methods.
# map 'long int' to long in typeName
# R dispatch for polymorphic types.
# collapse the collection of functions into a dispatch.
# S4 approach in progress.
# need access to the individual functions.
# Done.
# Put the C++ routines in an extern "C" block for the declarations.
# [DONE]
# Add the this back if not a constructor
# Done.
#
# Handle case where there are no parameters,
# avoid the SEXP r_ by itself.
# Done.
#
# names for polymorphic routines. (Done - check)
# these are the names of the C wrapper routines and are hidden from the end user.
# collapsing the types into a string, if necessary.
# more coercion of R values.
# Leave to C where possible since we have to do run-time checks there anyway.
#
# registration of the generated C routines.
# contained in result.
#
# drop the this in the constructors. Done.
#
# Example of low-level use.
if(FALSE) {
library(RGCCTranslationUnit) ; my = parseTU("inst/examples/ABC.cpp.tu"); k = getClassNodes(my)
z = createClassBindings(my[[ k$B ]], my, "B")
invisible(sapply(z, function(x) cat(x[[2]])))
m = getClassMethods(my [[ k$B ]])
s = resolveType(m$shift, my)
z = createMethodBinding(s) # , "B", name = "shift")
mm = lapply(m, resolveType, my)
z = mapply(createMethodBinding, mm, MoreArgs = list("B"))
invisible(sapply(z, function(x) cat(x[[2]])))
}
createInterface =
function(decls, files = character(0), ..., classes = getClassNodes(decls, files))
{
decls = findFirstFileDecl(decls)
# classes,
# functions,
# enumerations
# registration information.
# class hierarchy information
# put in C code for efficient comparison of tags and class info.
ans = list()
# funcs = getFunctions(decls, files)
if(length(classes))
ans$classes = lapply(names(classes), function(id) createClassBindings(id, decls, classes[[id]], ...))
routines = getRoutines(decls, files, ...)
if(length(routines))
ans$routines = lapply(routines, function(f) createMethodBinding(resolveType(f, decls), nodes = decls))
class(ans) <- "GeneratedCode"
ans
}
isAbstractClass =
#
# Currently, given the resolved class methods (from getClassMethods
# followed by resolveType.
#
# This is not sufficient to ensure a class is not abstract.
# It may not implement necessary methods.
#
# We could find all the virtual methods in the ancestor classes
# and see if they are implemented in this or other ancestor classes.
#
function(methods, nodes)
{
any(
sapply(methods,
function(x) {
if("pure" %in% names(x))
return(x$pure)
n = nodes[[x$INDEX]]
if("spec" %in% names(n)) {
if("pure" %in% unlist(n[["spec"]]))
return(TRUE)
}
"pure" %in% names(n)
}))
}
ImplicitConstructorNames = c("__base_ctor ", "__comp_ctor ",
"__base_ctor", "__comp_ctor", "__comp_dtor", "__deleting_dtor", "__base_dtor")
Merge.lists =
function(from, to)
{
for(i in names(from)) {
to[[i]] = c(to[[i]], from[[i]])
}
to
}
createInterfaceInfo =
function(def, methods, otherMethods, fields = def@fields)
{
# Check for static?
acc = function(m) sapply(m, function(m) m$access)
name = function(m) sapply(m, function(m) m$name)
inh = structure(unlist(lapply(otherMethods[def@ancestorClasses], acc)),
names = unlist(lapply(otherMethods[def@ancestorClasses], name)))
if(length(inh) == 0)
inh = character()
m = if(length(methods))
own = c(structure(sapply(methods, function(x) x$access), names = names(methods)), inh)
else
inh
fields = list(names = structure(names(fields), names = sapply(fields, function(x) x@definedIn)),
access = structure(sapply(fields, function(x) x@access), names = names(fields)),
nativeTypes = structure(sapply(fields, function(field) getNativeDeclaration("", field@type, , FALSE)), names = names(fields))
# ,rTypes = structure(sapply(fields, getNativeDeclaration("", field@type, , FALSE)), names = names(fields)))
)
structure( list(name = def@name,
# use as.character to get rid of the names which are the INDEX id in the TU.
baseClasses = as.character(def@baseClasses),
ancestorClasses = as.character(def@ancestorClasses),
fields = fields,
methods = m),
class = "InterfaceInfo")
# ans = unique(unlist(c(own, inh)))
# tmp = c(own, unlist(inh, recursive = FALSE))
# x = unlist(tmp)
# structure(x, names = if(length(x)) names(x) else character())
}
createClassBindings =
#
# Remove the need for def
# We can get rid of a lot of parameters here.
#
# Don't really use def except for default parameters
#
#
# Deal with polymorphicNames and signatures when one or other or both is supplied.
#
#
#
function(def,
nodes,
className = rdef@name,
types = DefinitionContainer(nodes),
polymorphicNames = unique(names(mm)[duplicated(names(mm))]), # note that this is only within class.
abstract = isAbstractClass(mm, nodes),
resolvedMethods = resolveType(getClassMethods(def), nodes, types),
typeMap = list(),
generateOverloaded = TRUE,
ifdef = character(),
helperInfo = NULL,
access = "public", # , "protected",
dynamicCast = list(),
otherClassMethods = NULL,
useClassNameMethod = FALSE,
signatures = list(), # A collection of the future generics across the entire code base that we are considering.
# So this tells us what functions are overloaded.
useSignatureParameters = TRUE,
dispatchInfo = data.frame(),
defaultBaseClass = if(useClassNameMethod) "RC++ReferenceUseName" else "RC++Reference",
classDefs = NULL,
...)
{
if(is(def, "C++ClassDefinition"))
rdef = def
else if(is(def, "GCC::Node::type_decl")) #??? or a record_type perhaps?
rdef = resolveType(def, nodes)
else
stop("don't know how to work with ", class(def))
if(missing(otherClassMethods)) {
otherClassMethods = resolvedMethods[ - match(className, names(resolvedMethods)) ]
resolvedMethods = resolvedMethods[[className]]
}
# if the user gave us a list of ResolvedClassMethods elements then we pick out the ones
# for this class. Such a list comes from lapply(classNodes, function(i) resolvedType(getClassMethods(i), parser, type))
if(!is(resolvedMethods, "ResolvedClassMethods") && class(resolvedMethods) == "list") {
otherClassMethods = resolvedMethods
resolvedMethods = otherClassMethods[[className]]
}
# If we are using the flat, general naming convention of foo rather than A_foo,
# then go ahead and find all the methods for each name.
if(missing(signatures) && length(otherClassMethods) && !useClassNameMethod) {
signatures = computeOverloadedSignatures(otherClassMethods)
} else if(length(signatures) == 0)
signatures = computeOverloadedSignatures(list(resolvedMethods))
fieldDefs = getAccessibleFields(rdef, access = access, classDefs = classDefs)
a = fields = createRFieldAccessors(rdef, className, typeMap = typeMap, operator = "[[", fields = fieldDefs)
if(length(fields)) {
tmp = createRFieldAccessors(rdef, className, get = FALSE, typeMap = typeMap, operator = "[[", fields = fieldDefs)
fields = Merge.lists(tmp, fields)
fields$generic = c(fields$generic, createNamesMethod(rdef, fieldDefs))
}
isVar = sapply(rdef@fields, is, "C++StaticClassField")
if(any(isVar)) {
vars = rdef@fields[isVar]
#XXX Generate the bindings to this static variable.
# If it is constant, we can pull it across and define it now.
# If it is a variable, then we setup a dynamic variable or
# at least generate the C code to be able to access and provide an
# R function that invokes this.
tmp = lapply(vars, generateStaticClassVariableCode, fields, rdef, className, typeMap)
}
# Get rid of the destructors & implicit constructors.
mm = resolvedMethods
mm = mm[ !sapply(mm, inherits, c("NativeClassDestructor", "ResolvedNativeClassDestructor"))]
mm = mm[ !(names(mm) %in% ImplicitConstructorNames)]
# Get only the methods with the appropriate access status, i.e. public, protected, private.
if(length(mm)) {
ok = sapply(mm, function(x) x$access %in% access)
mm = mm[ok]
}
# Figure out if this is an abstract/pure class. If it is a logical, we know.
# Otherwise, if the user gave us a vector of class names identifying abstract classes,
# look in that and also be sure.
if(is.character(abstract))
abstract = className %in% abstract || isAbstractClass(mm, nodes)
# If this is an abstract class, we don't want to generate any R constructor functions
# and for non-abstract classes, we add our own if there is no constructor.
constructors = sapply(mm, inherits, c("NativeClassConstructor", "ResolvedNativeClassConstructor"))
if(abstract) {
mm = mm[ !constructors]
} else if(!any(constructors) || length(mm) == 0) {
# add our own default constructor which takes no arguments.
# Don't we need to call one of the actual ones??? We are only doing this if there is no explict constructor.
# i.e. !any(constructors)
mm[["new"]] =
structure(list(parameters = list("this" = list(INDEX = rdef@index, id = "this", defaultValue = NA,
type = PointerType(rdef, name = as.character(NA), typeName = className))),
returnType = new("voidType"),
INDEX = as.integer(NA),
name = "new", # className,
access = "public",
virtual = FALSE,
pure = FALSE
),
class = c("ResolvedNativeClassConstructor", "ResolvedNativeClassMethod"))
}
# Generate the bindings for each method, taking into account if it is overloaded.
#XXX are we supposed to be doing this here? or across all classes.
# Before we call createMethodBinding, we need to determine the number and names of the parameters.
# Need to find them across all "related" classes, i.e. those classes which have shared virtual methods
# in common. This is now supplied to us via signatures and dispatchInfo now.
# we need to deal with the overloading at an earlier stage.
ans = lapply(mm, function(meth) {
poly = meth$name %in% polymorphicNames || meth$name %in% names(signatures)
createMethodBinding(meth, className, poly, ...,
nodes = nodes, typeMap = typeMap, ifdef = ifdef,
helperInfo = helperInfo,
resolvedMethods = otherClassMethods,
useClassNameMethod = useClassNameMethod,
signature = signatures[[meth$name]],
dispatchInfo = dispatchInfo,
useSignatureParameters = useSignatureParameters)
})
gen = list()
if(generateOverloaded) {
# For each overloaded method name, create generic and methods for that method.
# Find the methods in this class which are overloaded
w = character()
if(length(signatures)) {
w = unique(names(mm)[ names(mm) %in% names(signatures)])
} else {
counts = table(names(mm))
if(any(counts > 1))
w = names(counts[counts > 1])
}
if(length(w)) {
# Loop over the names of the methods that are overloaded
# and generate the code for each collection of methods with the same names.
gen = lapply(w, function(id) {
# om is the collection of methods with this name within this class
# funcs is the already generated code for those methods
# funcs[[n]]$r is an RMethodDefinition (at present)
om = mm[ names(mm) == id ] # overloaded methods
funcs = ans[ names(ans) == id ]
createOverloadedDispatchCode(id, funcs, om, typeMap = typeMap,
signature = signatures[[id]], dispatchInfo = dispatchInfo,
useSignatureParameters = useSignatureParameters)
})
names(gen) = w
}
i = names(ans) %in% w
k = class(ans)
ans[i] = lapply(ans[i], function(x) { x$r = character(); x})
class(ans) = k
}
#??? Do we need to do the recursive step here? Yes if we are generating and using
# this code in isolation from the general TU
defs = getRClassDefinitions(def, recursive = TRUE, className = className,
defaultBaseClass = defaultBaseClass)
if(!is.logical(dynamicCast) || dynamicCast) {
classes = getBaseClasses(def)
#??? is this in the def?
ancestors = getBaseClasses(def, recursive = TRUE)
cast = list() # createDynamicCastCode(rdef, classes, ancestors, doCast = dynamicCast) #XXX let dynamic cast contain more information.
} else
cast = list()
# If want to return an empty binding, use
# structure(list(), class = c("EmptyC++ClassBindings", "C++ClassBindings"))
if(any(w <- sapply(resolvedMethods, inherits, "ResolvedNativeClassCopyConstructor"))) {
fun = names(ans[[which(w)]]$registrationInfo$name)
gen$duplicate = RMethodDefinition("duplicate", className, paste(".Call(", sQuote(fun), ", x)"), c("x", "...", ".finalizer"), c(.finalizer = "NA"))
}
structure(list(regular = ans,
overloaded = gen,
classDefinitions = defs,
dynamicCast = cast,
fields = fields,
interfaceInfo = createInterfaceInfo(rdef, resolvedMethods, otherClassMethods, getAccessibleFields(rdef, c("public", "protected"), , classDefs)),
className = className
),
class = "C++ClassInterfaceBindings")
}
generateStaticClassVariableCode =
# only called from createClassBindings
function(var, fields, rdef, className, typeMap = list())
{
cname = paste("R", className, "get", var@name, sep = "_")
cvar = paste(rdef@name, var@name, sep = "::")
get = c(externC, "SEXP", paste(cname, "()"), "{",
paste( "return(", convertValueToR(cvar, var@type, parameters = character(), typeMap = typeMap), ");"), "}")
cget = CRoutineDefinition(cname, code = get, nargs = 1L)
csetName = sub("_get_","_set_", cname)
cset = c(externC, "SEXP", paste(csetName, "(SEXP r_value)"), "{",
getNativeDeclaration("value", var@type, character()),
getNativeDeclaration("ans", var@type, character()),
paste("ans =", cvar, ";"),
convertRValue("value", "r_value", var@type, typeMap = typeMap),
paste(cvar, "= value;"),
paste( "return(", convertValueToR("ans", var@type, parameters = character(), typeMap = typeMap), ");"), "}")
cset = CRoutineDefinition(csetName, code = cset, nargs = 1L)
#fields$cRoutines[[cname]] <<- cget
#fields$cRoutines[[csetName]] <<- cset
rcode = c(
"if(missing(value))",
paste(" .Call(", dQuote(cget@name), ")"),
"else",
paste(" .Call(", dQuote(cset@name), ",", coerceRValue("value", var@type, typeMap = typeMap), ")")
)
rfun = RFunctionDefinition(gsub("::", "_", cname), rcode, "value")
#fields$rFunctions[[rfun@name]] <<- rfun
list(cget = cget, cset = cset, raccess = rfun)
}
getRClassDefinitions =
#
# ? Get the definitions for R-level classes from the given TU node for a C++ class
# If recursive, chase the base classes down.
#
# Does this deal with multiple inheritance? i.e. when we have to go down two branches.
# specifically in the lapply(seq(along = r)....)
#
function(node, recursive = FALSE, className = getNodeName(node), defaultBaseClass = "RC++Reference")
{
if(recursive) {
ans = list()
ans[[className]] = getRClassDefinitions(node, FALSE, className, defaultBaseClass)
r = getBaseClasses(node, getReferences = TRUE, recursive = FALSE)
if(!inherits(r, "BaseClassesInfo"))
return(ans)
tmp = lapply( seq(along = r),
function(i) {
k = r[[i]] # [["class"]] was needed in the Perl parser but seems superfluous.
getRClassDefinitions(k, recursive = TRUE, names(r)[i], defaultBaseClass)
})
tmp = unlist(tmp, recursive = FALSE)
ans[names(tmp)] = tmp
return(ans)
}
base = getBaseClasses(node, recursive = FALSE)
if(length(base) == 0) {
rbase = defaultBaseClass
contains = character()
ancestors = character()
} else {
#XXX deal with public, etc.
rbase = getReferenceClassName(base, isClass = TRUE)
ancestors = getBaseClasses(node, recursive = TRUE)
names(ancestors) = sapply(ancestors, getReferenceClassName, isClass = TRUE)
}
if(length(ancestors))
contains = paste("c(", paste('"', names(ancestors), '"', sep = "", collapse = ", "), ")")
else
contains = 'character()'
newClassName = getReferenceClassName(className, isClass = TRUE)
def = paste(
'if(!isClass("', newClassName, '"))',
' setClass("', newClassName, '",',
" contains = c(",
paste('"', rbase, '"', sep = "", collapse = ", "), # collapse is for multiple inheritance
")",
", prototype = list(classes = ",
contains,
")",
")", sep = "")
names(def) = className
structure(list(definition = def, baseClasses = base, ancestors = ancestors, className = className),
class = "ClassDefinition")
}
createOverloadedDispatchCode =
#
# Generate R code to handle dispatching to the different
# overloaded C++ methods via their associated R wrappers.
#
# This version uses the S4 dispatch system.
#
# We may build a specialized dispatch mechanism to handle C++ dispatch.
#
#XXX This currently ignores default arguments on the C++ side.
# ?Still. I think we have that in hand now by determining the number of arguments needed to differentiate each call.
#
#
#
# wrap is intended as a logical value that would control whether we create a
# method that calls the true function. Otherwise, we try to use the raw function
# directly and get the names right!
function(id, funcs, defs, wrap = TRUE, typeMap = list(), signatures = NA, useMinSignature = TRUE,
dispatchInfo = data.frame(), createGeneric = FALSE,
useSignatureParameters = TRUE)
#
# id
# funcs - output from createMethodBinding containing the function definitions
# each element an object of class C++MethodInterface
# defs - C++ methods (resolved) for the given method/routine name
# that are to be combined for a generic and have setMethod
# wrap - logical - ignored!
# typeMap
{
unbound = sapply(funcs, is, "UnboundMethod")
if(all(unbound))
return(list())
funcs = funcs[!unbound]
defs = defs[!unbound]
# Determine the maximum number of arguments across all the different overloaded methods.
# By calculating them from the registrationInfo, they should already be adjusted for constructors, etc.
if(!(length(signatures) == 1 && is.vector(signatures) && is.na(signatures))) {
if(is.list(signatures))
sig = signatures[[id]]
else if(is(signatures, "RGenericDefinition"))
sig = signatures
# else if(is.null(signatures))
else
stop("Don't know what we have here")
gparmNames = sig@signature
numRealArgs = length(gparmNames)
} else {
# work from the collection of methods we have and find the longest number of parameters.
# and use their names.
# We can try to find the common names if they exist by position.
# numArgs = max(sapply(funcs, function(x) x$registrationInfo$nargs))
parmNames = lapply(defs, function(x) names(x$parameters))
gparmNames = parmNames[[ which.max(sapply(parmNames, length)) ]]
if(all(sapply(funcs, inherits, "ConstructorMethod")))
gparmNames = gparmNames[-1]
numRealArgs = length(gparmNames)
}
gparmNames = fixReservedWords(gparmNames)
# Get the number of arguments we need to uniquely identify each method here.
# Hopefully we have the dispatchInfo computed globally, i.e. across all routines and methods in the TU.
if(!is.null(signatures) && length(dispatchInfo)) {
numDispatchArgs = sapply(defs, getParameterDispatchCount, dispatchInfo)
} else {
numDispatchArgs = numUniqueArgs(defs)[,1] #, numRealArgs - for constructors this needs to be 1 more than we say
} # adjust signature table loop over parameters to drop first one.
# Loop over the different definitions for the methods that are overloaded for this particular generic
# and generate the R code to set an S4 method for this signature.
genericFunDef = paste("function(", paste(gparmNames, collapse = ", "), ")")
methods = sapply(seq(along = defs),
function(i) {
generateOverloadedMethod(defs[[i]], genericFunDef, funcs[[i]], id, numRealArgs, gparmNames,
numDispatchArgs[i], typeMap, useMinSignature, useSignatureParameters)
})
# C++ signature
# names(els) <- sapply(defs, as, "character")
# R signature
names(methods) <- sapply(funcs, function(x) paste(x$r@dispatchSignature, collapse = ", "))
if(createGeneric)
methods$generic = new("RGenericDefinition", name = id, signature = gparmNames)
# a character vector containing the different elements.
structure(methods, class = "OverloadedMethodRCode")
}
generateOverloadedMethod =
# Was inlined into the methods = sapply() in the createOverloadedDispatchCode.
#
# def - the description of the C++ method -
# funDeclaration - the declaration of the R function used as the generic, i.e. the function(arg1, arg2, ...)
# func - the code generated for this actual method without the setMethod() stuff, i.e. the function itself (+ the C/C++ code).
# id - the name of the function
# numGenericArgs - the number of arguments in the generic.
# gparmNames - additional parameter names such as .copy, .inherited...
# typeMap - user specifiable conversion table.
function(def, funDeclaration, func, id, numGenericArgs, gparmNames,
numDispatchArgs, typeMap = list(), useMinSignature = TRUE,
useSignatureParameters = TRUE)
{
params = def$parameters
# Get rid of the implicit this in a constructor.
if(inherits(def, "ResolvedNativeClassConstructor"))
params = params[-1]
# Get the types for the arguments in this method, and then
# pad out the remaining arguments with "missing".
if(length(params))
sig = sapply(params, function(p) getRTypeName(p$type, typeMap))
else
sig = character()
# This adds the missings to the signatures. This fixes up problems when there are no arguments
# and gives more specificity.
sig = c(sig, rep("missing", max(0, numGenericArgs - length(params))))
# XXX deal with default values in sig, either before or after this.
hasDefaultValue = sapply(params, function(x) !is.na(x$defaultValue))
if(!useMinSignature)
numDispatchArgs = if(any(hasDefaultValue)) seq(along = hasDefaultValue)[hasDefaultValue][1] - 1 else length(params)
if(numDispatchArgs > 0)
sig = sig[seq(length = numDispatchArgs)]
# Add the if(missing(args)) for the default values
# that don't make it into the signature for the S4 method.
if(any(hasDefaultValue)) { #&& (start <- seq(along = hasDefaultValue)[hasDefaultValue][1]) > numDispatchArgs) {
defaults = sapply(names(params[hasDefaultValue]),
function(id) {
c(paste("if(missing(", id, "))"),
paste(id, "=", params[[id]]$defaultValue))
})
} else
defaults = character()
# Now, create the code to define the method.
signature = paste("c(", if(length(sig)) paste(paste("'", sig, "'", sep = ""), collapse = ", "), ")")
extra = any(c(".inherited", ".copy") %in% gparmNames)
hasParams = length(params) > 0
if(is(func$r, "RMethodDefinition")) {
if(length(defaults)) {
func$r@code = c(defaults, func$r@code)
}
#!!!!!! We are returning here, so the rest of the code is ignored!
if(all(gparmNames == func$r@signature))
return(func$r)
}
funCode = if(is(func$r, "RMethodDefinition"))
as(func$r@code, "character")
else
as(func$r, "character")
txt = c(paste("setMethod('", id, "', ", sep = ""),
paste(signature, ","),
paste("#", as(def, "character")),
funDeclaration,
"{",
paste("#", paste(gparmNames[seq(along = params) ], names(params), sep = " <-> ")),
defaults,
# paste("return(c(", dQuote(as(def, "character")), if(length(params)) ", ", paste(gparmNames[seq(along = params)], collapse = ", "), "))"),
paste("..m = ", gsub("\\\n", "\\\n\\\t\\\t", funCode)),
if(all(c(".missing", ".copy") %in% gparmNames)) {
c("if(!missing(.copy) && !missing(.inherited) && c('.copy', '.inherited') %in% names(formals(..m)))",
paste(Indent, "..m(", paste(gparmNames[ seq(along = params)], collapse = ", "), if(hasParams) ", ", ".copy = .copy, .inherited = .inherited)"))
},
if(".copy" %in% gparmNames) {
c("if(!missing(.copy) && '.copy' %in% names(formals(..m)))",
paste(Indent, "..m(", paste(gparmNames[ seq(along = params)], collapse = ", "), if(hasParams) ", ", ".copy = .copy)"))
},
if(".inherited" %in% gparmNames) {
c("if(!missing(.inherited) && '.inherited' %in% names(formals(..m)))",
paste(Indent, "..m(", paste(gparmNames[ seq(along = params)], collapse = ", "), if(hasParams) ", ", ".inherited = .inherited)"))
},
if(extra) "else",
paste(if(extra) Indent, "..m(", paste(gparmNames[ seq(along = params)], collapse = ", "), ")"),
"}",
")")
paste(c("", rep(Indent, length(txt)-2), ""), txt, sep = "", collapse = "\n")
}
# Need classes, methods, etc.
getExportNames =
function(obj)
{
UseMethod("getExportNames")
}
"getExportNames.C++ClassInterfaceBindings" =
function(obj)
{
list(functions = unique(unlist(sapply(obj$regular, function(x) if(inherits(x$r, "NamedFunctionDefinition")) names(x$r)))),
classes = unique(names(obj$classDefinitions)),
methods = unique(names(obj$overloaded))
)
}
NullBinding =
structure(list(r = character(),
native = character(),
nativeDeclaration = character(),
registrationInfo = list("", nargs = 0)),
class = "NoopRoutine")
setGeneric("toRInitializer",
function(value, param, method = NULL)
{
standardGeneric("toRInitializer")
})
setMethod("toRInitializer", "ANY",
function(value, param, method = NULL)
NA
)
setMethod("toRInitializer", "character",
function(value, param, method = NULL)
{
dQuote(value)
})
setMethod("toRInitializer", c("integer", "list"),
function(value, param, method = NULL)
{
toRInitializer(value, param$type, method)
})
setMethod("toRInitializer", c("integer", "PointerType"),
function(value, param, method = NULL)
{
if(value == 0) {
CNULLValue
} else
value
})
setMethod("toRInitializer", "InitializerValue",
function(value, param, method = NULL)
{
#XXX
warning("Need to fix the default/initial value from a InitializerValue object")
"fix this default value"
# NA
})
setMethod("toRInitializer", "VariableDefaultValue",
function(value, param, method = NULL)
{
value$name
})
ReservedWords = c("function", "next") # for and if are reseverd in C/C++ also so not an issue.
fixReservedWords =
function(args)
{
i = match(args, ReservedWords)
if(any(!is.na(i)))
args[!is.na(i)] = paste(args[!is.na(i)], "_", sep = "")
args
}
createMethodBinding = createRoutineBinding =
#
# m - an instance of what class?
# NativeClassMethod, NativeClassConstructor which are constructed in getClassMethods() in findDecl.R
#
# To work for regular routines, we need a similar structure.
# From a function_decl or function_type node in the TU, we need
#
#
# See makeRoutineDescription()
#
# library(RGCCTranslationUnit); p = parseTU("inst/examples/structs.cpp.tu"); dd = getAllDeclarations(p, "structs")
# f = makeRoutineDescription( p [[ dd$createA ]], "createA")
#
# f = resolveType(f, p)
# createMethodBinding(f)
#
function(m,
className = if(is(m, "ResolvedNativeClassMethod")) m$className else character(),
isPolymorphic = FALSE,
addRFunctionNames = !isPolymorphic && length(inheritedClassNames) == 0,
name = m$name,
rfuncName = if(length(prefix)) sprintf("%s%s", prefix, name) else name,
nodes = list(),
typeMap = list(),
paramStyle = if("paramStyle" %in% names(m)) m$paramStyle else rep(NA, length(m$parameters)),
defaultRValues = list(),
ifdef = character(),
helperInfo = NULL,
resolvedMethods = list(),
extern = length(className) > 0,
useClassNameMethod = FALSE,
force = FALSE,
signature = NULL,
dispatchInfo = data.frame(),
useSignatureParameters = TRUE,
prefix = if(addDot) "." else character(),
addDot = FALSE
)
{
if(class(m) %in% c("list", "ResolvedRoutineList") &&
all(sapply(m, inherits, c("ResolvedNativeRoutine", "StaticMethod")))) { #XXX need to catch more types here.
k = sys.call()
# loop over the elements of this list and call this function on each and return the results.
ans = lapply(m, function(el) {
k[[2]] = el
# eval(k, env = sys.frame(-3))
eval.parent(k, 3)
})
class(ans) = "ResolvedRoutineList"
return(ans)
}
# Ignore _destructors_ as we do not call them from R.
if(any(inherits(m, c("NativeClassDestructor", "ResolvedNativeClassDestructor"))))
return(NullBinding)
# only deal with routines/methods that are within our specified accessibility
if(!force && length(m$access) && m$access %in% c("protected", "private")) {
# warning("protected method ", m$name, " in ", className)
return(NullBinding)
}
# if this is a C++ method, then see if there is a virtual method definition
# in one of the ancestor classes. If so, then we want to add a mechanism to call
# each of the inherited methods.
addInherited = FALSE
inheritedClassNames = character()
if(is(m, "ResolvedNativeClassMethod")) {
tmp = getInheritedMethod(m, resolvedMethods, classNames = TRUE)
addInherited = length(tmp) > 0
inheritedClassNames = names(tmp)
}
# Are we dealing with a constructor or regular method.
# For a constructor, the this in the parameters is artificial and should be omitted from the
# interface routine & function.
isConstructor = inherits(m, "ResolvedNativeClassConstructor")
# if there are any parameters. This could be 0 if this a constructor with no arguments
# or a routine with no arguments or a static method in a class.
# For a method, we will have the this.
hasParameters = length(m$parameters)
# Discard the this parameter for each of these methods.
# Constructors don't have these as regular arguments.
# And for regular methods, we will explicitly add it.
if(isConstructor) {
m$parameters = m$parameters[-1]
# Because of lazy evaluation, this will happen automatically and will be an error here.
# paramStyle = paramStyle[-1]
}
# An object to return if we cannot bind to this.
unbound = structure(list(name = m$name,
registrationInfo = list(name= m$name, nargs = 0)), class = "UnboundMethod")
# Check that all the types in the inputs and outputs are legitimate, top-level types.
# If they are defined in nested scopes, then we can't refer to them.
if(!checkScope(m$returnType)) { # do we need to include the namespace.
warning("method ", m$name, " in ", className, " has a return type ", as(m$returnType, "character"), "in a 'private'/nested scope. Ignoring method")
return(unbound)
}
for(p in m$parameters) {
if(!checkScope(p$type)) {
warning("method ", m$name, " has a parameter type in a 'private'/nested scope. Ignoring method")
return(unbound)
}
}
# Remove the const from the "this" parameter. Why?
#XXX Shouldn't we just declare the This as const?
if(length(m$parameters) > 0 && length(className) && className != ""
&& !is.na((idx <- match("const", m$parameters[[1]]$type@qualifiers))))
m$parameters[[1]]$type@qualifiers = m$parameters[[1]]$type@qualifiers[-idx]
omitArgs = integer()
#XXX merge with .copy
if(is(m$returnType, "ContainerDefinition") ||
(is(m$returnType, "C++ReferenceType") )) # && is(m$returnType@type, "ContainerDefinition")))
{
#XXX check this does not conflict with an existing parameter name
m$parameters[["copy"]] = structure(list(id = "copy", defaultValue = "2", type = new("intType"), class = "CopyArgument"))
omitArgs = "copy"
}
if(any(is.na(paramStyle))) {
w = is.na(paramStyle)
paramStyle[w] = sapply(m$parameters[w],
function(x) {
if(!is(x$type, "UserDataType") && is(x$type, "PointerType") && !("const" %in% x$type@type@qualifiers))
"inout"
else
"in"
})
}
if(inherits(m, "ResolvedNativeClassMethod"))
paramStyle[1] = "in"
if(inherits(signature, "GenericDefinitionList")) {
signature = signature[[m$name]]
isPolymorphic = !is.null(signature)
}
# out and inout parameters.
outArgs = (paramStyle %in% c("inout", "out"))
names(outArgs) = names(m$parameters)
outs = which(outArgs) # grep("(inout|out)", paramStyle) # out or inout
# Fix up names to protect against parameters that are
# reserved R words like next, function, ...
names(m$parameters) = fixReservedWords(names(m$parameters))
# change the names starting with _ or a number to have a r prefix.
nums = grep("^[0-9]+$", names(m$parameters))
if(length(nums) > 0)
names(m$parameters)[nums] <- paste("r", names(m$parameters)[nums], sep = "")
nums = grep("^_+", names(m$parameters))
if(length(nums) > 0)
names(m$parameters)[nums] <- paste("x", names(m$parameters)[nums], sep = "")
# Get the signature for the R function, including default values.
# XXX need to handle more exotic (i.e. non-primitive) default values.
# This is a subset of m$parameters corresponding the the in and inout parameters.
params = sapply(seq(along = m$parameters), #names(m$parameters)[!outArgs], #XXXX note the !outArgs.
function(i) {
id = names(m$parameters)[i]
v = m$parameters[[id]]
if(id %in% names(defaultRValues))
v$defaultValue = defaultRValues[[id]]
else if(length(v$defaultValue)) {# && !is.na(v$defaultValue)) # inherits(v$defaultValue, c("InitializerValue")))
v$defaultValue = toRInitializer(v$defaultValue, v, m)
}
m$parameters[[i]]$defaultValue <<- v$defaultValue
if(outArgs[i]) {
# call the constructor for this reference type.
# Must be a pointer type (or perhaps a reference type).
#XXX must be a PointerType for the @typeName to make sense.
v$defaultValue = paste(getRConstructorFunctionName(v$type@type, v$type@typeName), "()", sep = "")
}
if(length(grep("^_+", id)))
id = paste("r", id, sep = "")
if(length(v$defaultValue) && !is.na(v$defaultValue)) {
paste(id, "=", as(v$defaultValue, "character"))
} else
id
})
names(params) = names(m$parameters)
hasDotCopy = any(outArgs) #XXX should include inout args also.
# add a .copy argument if there are any out arguments.
# could put the names on the elements
#params[".copy"] = paste(".copy = rep(FALSE, ", sum(outArgs), ")")
if(hasDotCopy) {
params[".copy"] = paste(".copy = c(", paste(paste("'", names(params)[outArgs], "'", sep = ""), "FALSE", sep = " = ", collapse = ", "), ")")
#XXX generate code to validate this argument.
# i.e. ensure correct length, entries for each out parameter and is NA, TRUE or FALSE.
# call a function at run-time or inline the code here?
}
# if(addInherited)
# params[".inherited"] = ".inherited = logical()"
# If the name has 2 or more elements, then the R name is taken to be the second one.
# rfuncName = if(length(name) > 1) name[2] else name
if(isConstructor)
rfuncName = paste(getTUOption("constructorNamePrefix", ""), className, sep = "") # className #XXX use newClassName for constructor name
if(length(className) > 0 && useClassNameMethod && !isConstructor)
rfuncName = paste(className, rfuncName, sep = "_")
# Compute the name of the C wrapper routine, taking into account multiple polymorphic methods for this method.
routine = NativeMethodName(name, className, isPolymorphic, m$parameters)
isVoidRoutine = !isConstructor && is(m$returnType, "voidType")
# Use the name in the method object, or if it is empty use the specified name.
# This allows the caller to specify the name of the wrapper routine via the name argument,
# but to leave the internal call to the real routine/method as defined in the C code.
routineName = if(length(m$name) && m$name != "") m$name else name
indent = ""
funcDef = createRCode(m, rfuncName, routine, typeMap,
hasDotCopy, addInherited, isVoidRoutine, inheritedClassNames, outArgs = outArgs,
signature = if(useSignatureParameters) signature else NULL)
if(isConstructor) {
m$returnType = new("PointerType", typeName = className)
m$returnType@type = new("C++ClassDefinition", name = className, index = -1L)
}
native = createNativeCode(routineName, m, params, routine, className,
typeMap, hasDotCopy, outArgs, outs, omitArgs,
isConstructor, isVoidRoutine, inheritedClassNames,
extern, ifdef, nodes, paramStyle, helperInfo = helperInfo)
if(!is.null(signature)) {
if(!is.numeric(dispatchInfo))
dispatchInfo = getParameterDispatchCount(m, dispatchInfo)
if(is.na(dispatchInfo))
dispatchInfo = length(m$parameters)
genericSig = if(is.character(signature))
signature
else
signature@signature
if(dispatchInfo > 0) {
# do we want the minimum # of elements in the signature or the full number up to the
# number up to where the defaults start.
if(FALSE) {
len = length(funcDef@signature) - dispatchInfo - ("..." %in% funcDef@signature)
missings = rep("missing", length = len)
sig = c(sapply(m$parameters[seq(1, length = dispatchInfo)], function(x) getRTypeName(x$type)), missings)
} else {
i = sapply(m$parameters, function(x) is.na(x$defaultValue))
if(all(i))
n = length(m$parameters)
else
n = which((!i)[1])
len = max(dispatchInfo, n)
sig = c(sapply(m$parameters[seq(1, length = len)], function(x) getRTypeName(x$type))) #, missings)
}
} else
sig = if(length(genericSig)) 'missing' else character()
funcDef@dispatchSignature = sig
funcDef@signature = genericSig
funcDef
}
els = list(r = funcDef,
native = native$code,
nativeDeclaration = native$cdecl,
registrationInfo = list(name = structure(routineName, names = routine[1]),
nargs = native$code@nargs), # length(m$parameters) + hasDotCopy + addInherited
ifdef = ifdef)
if(is(m, "ResolvedNativeOperatorClassMethod") && m$name == "subs")
els$operatorMethods = createSubsOperatorAccessors(m, typeMap = typeMap)
if(addInherited)
els$methodNames = paste(inheritedClassNames, m$name, sep = "_")
klass = ifelse(length(className) && nchar(className), 'C++MethodInterface', 'C++RoutineInterface')
if(isConstructor)
klass = c(klass, "ConstructorMethod")
structure(els, class = klass)
}
createSubsOperatorAccessors =
function(m, typeMap = list())
{
coerceIndex = coerceRValue("index", m$parameters[[2]]$type, typeMap = typeMap)
singleCode = paste("sapply(i, function(index) subs(x,", coerceIndex, "))")
doubleCode = paste("subs(x,", coerceRValue("i", m$parameters[[2]]$type, typeMap = typeMap), "[1])")
list("[[" = RDoubleBracketDefinition(m$className, doubleCode),
"[" = RSingleBracketDefinition(m$className, singleCode))
}
createNativeCode =
#
# routineName = character, method name to invoke
# m = method definition , e.g. ResolvedNativeClassMethod
# params = character vector giving the names of the parameters
# routine = character vector, name of actual routine we are generating which is prefixed with R_ and has the argument types.
# ?? same as routineName
# className
# typeMap
# hasDotCopy = logical indicating if .copy parameter
# outArgs = names of outArgs
# outs = names of the out parameters
#??? why both outArgs and outs?
# omitArgs - character vector giving parameters to throw away.
# isConstructor - logical
# isVoidRoutine - logical
# inheritedClassNames - character vector of ancestor classes
# ?? what for
# extern
function(routineName, m, params, routine, className, typeMap, hasDotCopy, outArgs, outs, omitArgs,
isConstructor, isVoidRoutine, inheritedClassNames, extern, ifdef, nodes = NULL,
paramStyle = character(), helperInfo = NULL)
{
addInherited = length(inheritedClassNames) > 0
parmNames = names(params) # m$parameters
if(length(parmNames) && parmNames[1] == "this") {
parmNames[1] = "This"
i = match("this", names(m$parameters))
if(!is.na(i))
names(m$parameters)[i] = "This"
}
parmNames = gsub("\\.", "_", parmNames)
native = c(externC, "SEXP")
# Create the declaration for the routine using parameter names with a "r_" prefixed for all of them.
#NOTE: we could remove the _copy argument if hasDotCopy == TRUE as we currently do the processing in R code.
# XXX Is this still true?
cdecl <- paste(routine, "(", if(length(parmNames)) paste("SEXP", paste("r_", parmNames, sep = ""), collapse = ", "),
if(hasDotCopy) ", SEXP r_resultLength",
if(addInherited) ", SEXP r__inherited",
")", sep = "")
native = c(native, cdecl, "{")
cdecl <- paste("SEXP", cdecl, sep = " ")
indent = "\t"
native = c(native, "",
paste(indent, "SEXP r_ans = R_NilValue;", sep = ""),
if(hasDotCopy)
paste(indent, "SEXP r_names = R_NilValue;", sep = "")
# , if(!isConstructor) paste(indent, className, "* This;")
)
if(hasDotCopy)
native = c(native, paste(indent, "int r_ctr = 0;", sep = ""))
outArgReferencePrefix = "_p_"
# Get the declarations for the out arguments.
if(length(outArgs)) {
args = m$parameters[outArgs]
outDecls = sapply(names(m$parameters[outArgs]),
function(id) {
#XXX need to know we have a pointer here.
# Create <id> and _p_<id>, e.g. a and _p_a
paste(indent, getNativeDeclaration(id, m$parameters[[id]]$type@type, addSemiColon = FALSE, const = FALSE),
", *", paste(outArgReferencePrefix, id, sep = ""), " = &", id, ";", collapse = "", sep = "")
}
)
native = c(native, outDecls)
}
# Declarations for the the regular C values corresponding to the R object parameters.
if(length(outArgs) == 0)
outArgs = rep(FALSE, length(m$parameters))
if(length(params)) {
native = c(native, paste(indent,
# loop over the indices so we can index parmNames and m$parameters
# by index since they don't have the same names necessarily since
# we may have changed the this to the This!
sapply(seq(along = m$parameters)[!outArgs], #names(m$parameters)[!outArgs],
function(i) {
if(parmNames[i] == "_copy")
return(character())
type = m$parameters[[i]]$type
if(is(type, "C++ReferenceType")) {
type = PointerType(type@type) # const issues?
}
getNativeDeclaration(parmNames[i], type, const = NA) # XXX FALSE)
}), sep = ""))
}
argNames = names(m$parameters)
if(length(m$parameters))
refs = sapply(m$parameters, function(x) {
if(is(x$type, "ResolvedTypeReference"))
x$type = resolveType(x$type)
is(x$type, "C++ReferenceType")
})
else
refs = logical()
if(any(refs))
argNames[refs] = paste("*", argNames[refs])
if(length(omitArgs)) {
idx = match(omitArgs, argNames)
argNames = argNames[ - idx]
outArgs = outArgs[-idx]
}
if(length(argNames) && length(outArgs))
argNames[outArgs] = paste(outArgReferencePrefix, argNames[outArgs], sep = "")
# Determine how to call the C/C++ method, i.e. with obj->foo(), Class::foo, or simply foo()
# and determine the arguments to this call.
testProtected = character()
if(inherits(m, "ResolvedNativeClassMethod")) {
if(isConstructor) {
if(length(m$parameters))
cargs = paste(argNames, collapse = ", ")
else
cargs = ""
invocation = "new"
} else {
if(inherits(m, "StaticMethod")) {
invocation = paste(className, "::")
cargs = paste(argNames, collapse = ", ")
} else {
invocation = "This ->"
cargs = paste(argNames[-1], collapse = ", ")
if(m$access == "protected")
testProtected = "CHECK_IS_PROTECTED(r_This)"
}
}
} else {
if(TRUE || length(m$parameters[!outArgs]))
cargs = paste(argNames, collapse = ", ")
else
cargs = ""
invocation = ""
}
routineName = if(isConstructor) className
else if(inherits(m, "ResolvedNativeOperatorClassMethod")) getOperatorSymbol(m$name, TRUE)
else routineName
call = paste(invocation, routineName , "(", cargs, ")")
native = c(native, testProtected)
# if not a void return, declare the local return value
#XXX Check ans is not already a used name.
#XXX
# Want to allow either the caller or the method definition indicate whether
# the object needs to be copied or if we want to have the reference to it
# so that we can update it directly, i.e. a shared instance between R and wxWidgets.
#XXX The logic seems dubious here in general.
#
# This is bypassing the method dispatch system. We know that we are
# processing the return type and not a general parameter.
# If we are dealing with a real C++ object and not a pointer to it,
# then we will do the conversion inline and don't need a declaration.
#XXX IMPORTANT:
#XXX We need to differentiate between a struct and C++ class.
# If we are not in C++, then the struct needs to be copied!
# use isCPlusPlus(nodes)
# If the class of interest does not have a constructor that accepts an
# instance of that same type, we are screwed.
#
noAnsAssign = FALSE
if(isVoidRoutine) {
r = NULL # character()
} else if(FALSE && is(m$returnType, "C++ClassDefinition")) #XXX was active
r = ""
else if(is(m$returnType, "C++ReferenceType") && is(m$returnType@type, "C++ClassDefinition")) {
r = ""
noAnsAssign = TRUE
call = paste(ifelse("const" %in% m$returnType@type@qualifiers, "const", ""), m$returnType@type@name, "&", "ans", "=", call)
} else {
r = getNativeDeclaration("ans",
if(is(m$returnType, "C++ReferenceType")) m$returnType@type else m$returnType,
names(m$parameters), const = FALSE)
}
if(!is.null(r)) { # can't be null, just ""
native = c(native, paste(indent, r))
# Now get the code to compute the return value for R.
if(length(names(r)) == 0)
names(r) = "ans"
r = convertValueToR(names(r), m$returnType, m$parameters, invoke = call, typeMap = typeMap, helperInfo = helperInfo)
if(!length(outs) && !inherits(r, c("C++Block", "CBlock")))
r = paste(indent, "r_ans = ", r, ";")## Convert the data type.
if(inherits(r, "InlineInvocation"))
call = ""
} else
r = character()
# Build the code that takes all the out arguments and puts them in a list.
if(length(outs))
#XXX Need to handle the copy argument.
rtnCode = collectOutVars(m$parameters[outs], m, r, typeMap, paramStyle[outs])
else
rtnCode = character()
getLocalArgumentValue = function(id, type, parameters, out = FALSE) {
if(inherits(parameters[[id]], "UnusedParameter"))
return("")
if(is(type, "FunctionPointer"))
attr(type, "Caller") = m
#XXXX Check.
rhs = convertRValue("", paste("r", id, sep = "_"), type, parameters, typeMap = typeMap, helperInfo = helperInfo)
if(inherits(rhs, "FailedConversion") || rhs == "")
rhs
else {
if(is.na(out)) out = FALSE
origId = id
if(out) id = paste(outArgReferencePrefix, id, sep = "")
if(!inherits(rhs, c("IfStatement", "StatementBlock", "Statement")))
rhs = paste(ifelse(id == "this", "This", id) , " = ", rhs, ";")
if(out)
rhs = c(paste("if(GET_LENGTH(", paste("r", origId, sep = "_"), ") > 0) {"),
paste(indent, rhs, sep = ""),
"}")
}
rhs
}
indent = "\t"
native = c(native, "",
paste(indent, unlist(sapply(seq(along = m$parameters), ## names(m$parameters)[!outArgs],
function(i) {
id = names(m$parameters)[i]
getLocalArgumentValue(id, m$parameters[[id]]$type, m$parameters, outArgs[i])
})))
)
if(addInherited)
native = c(native, "", createCallInheritedCode(routineName, names(m$parameters), inheritedClassNames, result = if(isVoidRoutine) character() else "ans", m$parameters))
else if(call != "")
native = c(native, "",
paste(indent, if(isConstructor || (!noAnsAssign && length(r) && r != "")) " ans = ", call, ";", sep = ""), "")
if(length(rtnCode))
r = rtnCode
native = c(native, r, "", paste(indent, "return(r_ans);"))
native = c(native, "}", "")
# Add the #ifdef NAME ... #endif around the code.
if(is.function(ifdef))
ifdef = ifdef(m, className)
if(length(ifdef)) {
native = c(paste("#ifdef", ifdef,), native, paste("#endif /*", m$name, ":", ifdef, "*/"))
}
# Provide the information about what file and line number the method declaration comes from.
if(length(nodes))
location = ifelse(!missing(nodes), paste("/*", ifelse(!is.na(m$INDEX), nodes[[ m$INDEX ]][["source"]], "artificially constructed"), "*/"), "")
else
location = character()
list(code = CRoutineDefinition(name = routine, code = native, nargs = length(parmNames) + as.integer(hasDotCopy)),
cdecl = cdecl)
}
createRCode =
#
# Returns an RFunctionDefinition or RMethodDefinition
#
function(m, rfuncName, routine,
typeMap, hasDotCopy, addInherited, isVoidRoutine, inheritedClassNames,
useClassNameMethod = FALSE, outArgs = character(), signature = NULL,
params = m$parameters)
{
txt = character()
if(!is.null(signature)) {
# display the signature of the C/C++ routine/method as a comment.
txt = c(txt, paste("\t#", c(as(m, "character"), paste(names(m$parameters), signature@signature[1:length(m$parameters)], sep = " <-> "))), "")
originalParamNames = names(m$parameters)
# Deal with ...
if(!inherits(m, "ResolvedNativeClassConstructor")) # length(m$parameters) = 0
names(m$parameters) = signature@signature[1:length(m$parameters)] #XXX need to switch the out args too!
} else
originalParamNames = character()
funcDef = new(if(!is.null(signature)) "RMethodDefinition" else "RFunctionDefinition", name = rfuncName)
if(!is.null(signature)) {
if(length(params) == 0)
funcDef@signature = signature@signature
else
funcDef@signature = c(names(params), signature@signature[ - seq(along = params) ])
} else
funcDef@signature = if(length(names(params))) names(params) else character()
# Deal with default values for parameters. Should be cleaned up and accompany the params.
# Here we have to deal with getting it from the almost parallel list in m$parameters
# but because we add parameters such as .copy, we have to be more careful.
if(length(params)) {
o = is.na(params) | names(params) %in% c(".copy", ".inherited")
mparams = params[!o]
funcDef@paramDefaults = character(length(params))
funcDef@paramDefaults[!o] = sapply(mparams, function(x) { if(!is.na(x$defaultValue))
as(x$defaultValue, "character")
else
""
})
}
# get rid of NAs from out arguments
# but if we want them left in and with default arguments, then we have to
# add them back.
# txt = c(txt, paste("function(", paste(tmp, collapse = ", "), ") ", ""), "{")
indent = " "
# Do the coercion of the R arguments.
txt = c(txt, sapply(names(params), #[!outArgs],
function(id) {
if(inherits(params[[id]], "UnusedParameter"))
""
else {
tmp = coerceRValue(id, m$parameters[[id]]$type, m, typeMap, helperInfo = helperInfo)
if(!identical(id, tmp))
if(inherits(tmp, "RCode")) tmp else paste(indent, id, "=", tmp)
}
}))
if(hasDotCopy) {
# need to ensure that .copy is not in this collection. If it is added to outArgs,
# then it will be included.
tmp = names(params)[outArgs]
tmp = tmp[tmp != ".copy"]
parms = paste(sQuote(tmp), sep = "", collapse = ", ")
txt = c(txt, paste(indent, ".copy = validateCopy(.copy, c(", parms, "))", sep = ""))
}
if(addInherited) {
inames = paste("'", inheritedClassNames, "'", sep = "", collapse = ", ")
txt = c(txt, paste(indent, "if(!is.logical(.inherited)) {"),
paste(indent, indent, ".inherited = as.character(.inherited)"),
paste(indent, indent, "if(!(.inherited %in% c(", inames,")))"),
paste(indent, indent, indent, "stop(\".inherited must be ", if(length(inheritedClassNames) > 1) paste("one of", inames) else paste("TRUE or", inames), "\")", sep = ""),
paste(indent, "}"))
}
txt = c(txt, "")
.ans = if(FALSE && hasDotCopy) .ans = ".ans =" else character()
invoke = paste(.ans, ".Call('", routine, "'",
ifelse(length(params), ", ", ""),
paste(names(params), collapse = ", "),
if(hasDotCopy) paste(if(length(params)) ",", ".copy", ", as.integer(sum(!is.na(.copy))", if(!isVoidRoutine) "+ 1", ")"),
")", sep = "")
if(isVoidRoutine && !hasDotCopy)
invoke = paste("invisible(", invoke, ")")
# Make the call to the wrapper routine.
txt = c(txt, paste(indent, invoke, sep = ""))
#XXX Do we need to do any wrap up, e.g. to convert the return value further.
# Yes, for enumerations. Could do it with initialize method for a class.
# Done in C code now.
if(FALSE && hasDotCopy) # we include the values and the names of the out parameters
txt = c(txt, paste(indent, "collectOutResults(", if(!isVoidRoutine) ".ans", ",",
paste(names(params)[outArgs], names(params)[outArgs], sep = " = ", collapse = ", "),
", .copy = .copy)", collapse = ""), sep = "")
if(hasDotCopy) {
funcDef@signature = c(funcDef@signature, ".copy")
funcDef@paramDefaults = c(funcDef@paramDefaults, "TRUE")
}
if(addInherited) {
funcDef@signature = c(funcDef@signature, ".inherited")
funcDef@paramDefaults = c(funcDef@paramDefaults, "FALSE")
}
funcDef@code = unlist(txt)
funcDef
}
createCallInheritedCode =
#
# This generates the code for calling the inherited methods from super classes
# for a given method.
#
# methodName - name of the method being called.
# params - character vector giving the names of the C++ variables to be put in the call.
# e.g. c("x", "y"). These are typically names(method$parameters)
#
# inheritedClassNames - character vector giving the names of the classes whose inherited methods
# we are allowing to be invoked, e.g. c("A", "C").
# result - a character vector giving the name of the C++ variable to assign the result.
# if the return type is void, specify this as character()
#
#
function(methodName, params, inheritedClassNames, result = character(), parameterInfo = list())
{
if(length(parameterInfo)) {
refs <- sapply(parameterInfo, function(x) is(x$type, "C++ReferenceType"))
if(any(refs))
params[refs] = paste("*", params[refs])
}
args = paste("(", paste(params[-1], collapse = ", "), ")")
if(length(result))
result = paste(result, "=")
txt = c(
"if(GET_LENGTH(r__inherited) == 0",
" || TYPEOF(r__inherited) == LGLSXP && LOGICAL(r__inherited)[0] == FALSE) {",
" // default call to own or inherited method.",
paste(" This->", methodName, args, ";"),
"",
"} else if (TYPEOF(r__inherited) == LGLSXP && LOGICAL(r__inherited)[0] == TRUE) {",
paste(" This->", inheritedClassNames[1], "::", methodName, args, ";"),
"",
"} else if (TYPEOF(r__inherited) == STRSXP) {",
" // use the names to find out which one.",
"",
paste(Indent, "const char *className = CHAR(STRING_ELT(r__inherited, 0));"))
txt = c(txt, unlist(sapply(seq(along = inheritedClassNames),
function(i) {
c(paste(Indent, if(i > 1) "else ", 'if(strcmp(className, "', inheritedClassNames[i], '") == 0)', sep = ""),
paste(Indent, Indent, result, "This->", inheritedClassNames[i], "::", methodName, args, ";")
)
})),
paste(Indent, "else {"),
paste(Indent, Indent, 'PROBLEM ".inherited specified, but class name does not match parent classes with method \\"', methodName, '\\""', sep = ""),
paste(Indent, Indent, "WARN;"),
paste(Indent, "}"),
"}")
# txt
paste(Indent, txt) #, collapse = "\n")
}
collectOutVars =
#
# This is responsible for generating the code that collects the out parameters
# (not the inout parameters yet)
# and returning them.
#
function(parms, method, returnType, typeMap, styles, pointerPrefix = "_p_")
{
isVoid = length(returnType) == 0
# length(parms) + if(isVoid) 0 else 1
txt = c(paste("PROTECT(r_ans = NEW_LIST( INTEGER(r_resultLength)[0]));"),
paste("PROTECT(r_names = NEW_CHARACTER( INTEGER(r_resultLength)[0]));"))
# Deal with C++ block and inline invocation
if(!isVoid)
txt = c(txt,
paste("SET_VECTOR_ELT(r_ans, 0, ", returnType, ");"),
'SET_STRING_ELT(r_names, 0, mkChar(".result"));',
'r_ctr++;', # move to the next position.
"")
tmp = lapply(seq(along = parms),
function(i) {
type = parms[[i]]$type
if(styles[i] == "out")
type = type@type
# do we need to add the & ?
id = names(parms)[i]
# This is used to make a deep copy of a variable on the stack!
# Doesn't really make sense
# copyRoutineName = getStructCopyRoutineName(type)
# copy = paste(copyRoutineName, "( ", paste(pointerPrefix, id, sep = ""), " )", sep = "")
copy = convertValueToR(paste("*", pointerPrefix, id, sep = ""), type@type, parms, "", typeMap, out = TRUE, helperInfo = helperInfo)
copyVal = paste('LOGICAL(r__copy)[', i - 1, ']')
code = paste(copyVal, "== FALSE && GET_LENGTH(", paste("r_", id, sep = ""), ") > 0 ? ", paste("r_", id, sep = ""), ":", copy)
c(paste('if(', copyVal, ' != NA_LOGICAL) {'),
paste(Indent, 'if(', copyVal, " == FALSE && GET_LENGTH(", paste("r_", id, sep = ""), ") == 0) {"),
paste(Indent, Indent, 'PROBLEM "ignoring request to not copy argument', id, 'as only local/stack value is available"'),
paste(Indent, Indent, "WARN;"),
paste(Indent, "}"),
paste(Indent, "SET_VECTOR_ELT( r_ans, r_ctr,", code, ");"),
paste(Indent, 'SET_STRING_ELT( r_names, r_ctr++, mkChar("', id, '"));', sep = ""),
'}', ""
)
})
txt = c(txt,
unlist(tmp),
"SET_NAMES(r_ans, r_names);",
"UNPROTECT(2);")
paste("\t", txt, collapse = "\n")
}
checkScope =
function(type)
{
if(is(type, "C++ReferenceType"))
return(checkScope(type@type))
if(is(type, "TypeDefinition"))
return( length(type@scope) == 0)
if(is(type, "Gcc::Node::function_decl")) {
if("scpe" %in% names(type) && inherits(type[["scpe"]], "GCC::Node:record_type"))
return(FALSE)
}
if(is(type, "BuiltinPrimitiveType"))
return(TRUE)
if(is(type, "PointerType"))
return(checkScope(type@type))
if(is(type, "GCC::Node::record_type")) {
if("scpe" %in% names(type) && inherits(type[["scpe"]], "GCC::Node:record_type"))
return(FALSE)
}
TRUE
}
getReferenceClassName =
function(parm, name = character(), isClass = FALSE)
{
if(is(parm, "ResolvedTypeReference"))
parm = resolveType(parm)
#XXX For classes
# parm@typeName
if(is.character(parm))
return(if(isClass) parm else paste(parm, "Ptr", sep = ""))
if(is(parm, "BuiltinPrimitiveType"))
name = capitalize(parm@name, first = FALSE)
else if(is(parm, "EnumerationDefinition"))
name = capitalize(parm@name[length(parm@name)], first = FALSE)
else if(is(parm, "TypedefDefinition"))
name = parm@name
else if(is(parm, "C++ClassDefinition"))
return(parm@name)
else if(is(parm, "C++ReferenceType"))
return( parm@type@name )
else if(is(parm, "ArrayType")) {
parm = fixArrayElementTypeNames(parm)
return(getCopyArrayName(parm, c("", ""), "Ptr"))
} else if(is(parm, "PointerType")) {
#XXX
if(is(parm@type, "ResolvedTypeReference"))
parm@type = resolveType(parm@type)
if(is(parm@type, "C++ClassDefinition"))
return(parm@typeName) #XXX changed this from parm@depth - 1
name = paste(parm@typeName, paste(rep("Ptr", parm@depth - 1), collapse = ""), sep = "")
} else
name = parm@name
name = gsub("^struct ", "", name)
paste(name, "Ptr", sep = "")
}
# Get the declaration for the local variables in our wrapper routine that
# hold the values from the R objects.
NativeMethodName =
function(name, className, isPolymorphic = FALSE, types = list(), prefix = "R_")
{
if(isPolymorphic) {
if(length(types)) {
e = paste(sapply(types, function(x) typeName(x$type)), collapse = "_")
name <- paste(name, e, sep = "_")
} else
name <- paste(name, "void", sep = "_")
}
name = gsub(" ", "_", name)
name = gsub("::", "__", name) # for enumerations within a scope, e.g. wxFileData::fileListFieldType
paste(prefix, className, ifelse(length(className), "_", ""), name, sep = "")
}
setGeneric("typeName", function(type) standardGeneric("typeName"))
setMethod("typeName", "PointerType",
function(type)
paste(paste("p", type@depth, sep = ""), type@typeName, sep = "")
)
setMethod("typeName", "C++ReferenceType",
function(type)
paste("r", typeName(type@type), sep = "")
)
setMethod("typeName", "TypeDefinition",
function(type)
#XXX need to map, e.g. 'long int' to 'long'
gsub(" ", "_", type@name)
)
getStructCopyRoutineName =
# function to produce the name of the C routine responsible for copying an
# instance of the structure given by 'def' to an R object.
# This is short but centralized to avoid synchronizing code in different locations
# and thus ensuring that the name used to define the routine is the same as the name
# used to call that routine in generated code.
function(def, name = ifelse(length(def@alias), def@alias, def@name))
{
if(is(def, "PointerType"))
def = def@type
paste("R_copyStruct_", name, sep = "")
}
startsWith =
function(char, txt)
{
substring(txt, 1, 1) == char
}
|
2bd554d92847d478004a95c9328092007d893241
|
d24c36a4eeff0f3911179a6747f8fbc9cdcadacf
|
/eqtl/TIMBR_eqtl.R
|
b3a72d8415af03fbbdc673b060328defd69e092e
|
[] |
no_license
|
wesleycrouse/TIMBR_data
|
9ab2d4a119b0bf1392737e489401a3fd239d4fbd
|
9a822473158c676d18657c051f5a711feb09d5d0
|
refs/heads/master
| 2022-12-28T06:55:56.593654
| 2020-10-16T17:35:07
| 2020-10-16T17:35:07
| 267,590,613
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,668
|
r
|
TIMBR_eqtl.R
|
command.line <- commandArgs(trailingOnly = TRUE)
phenotype.var <- as.character(command.line[1])
locus <- as.character(command.line[2])
#phenotype.var <- "X1212612"
#locus <- "M17.345"
#drop \r that appears when running from command line
locus <- unlist(strsplit(locus, "[^[:print:]]"))
####################
library(TIMBR)
library(data.table)
#load phenotype data
phenotype.data <- fread("data/rankz-filtered-precc-geneexp.txt", header=T, stringsAsFactors=F, select=c("SUBJECT.NAME", phenotype.var))
phenotype.data <- as.data.frame(phenotype.data)
#drop subjects with any missing phenotype data
phenotype.data <- phenotype.data[!is.na(phenotype.data[,2]),]
#sort phenotype data by subject name
phenotype.data <- phenotype.data[order(phenotype.data[,1]),]
#format dependent variable
y <- phenotype.data[,2]
names(y) <- phenotype.data[,1]
#load diplotype data
chr <- substring(unlist(strsplit(locus, split="[.]"))[1], 2)
load(paste0("../precc_cache/full/chr", chr, "/@", locus, ".RData"))
load(paste0("../precc_cache/full/chr", chr, "/subjects.RData"))
P <- get(locus)
rownames(P) <- subjects
do.call("rm", list(eval(locus)))
rm(subjects)
#sort diplotype probabilities by subject name
P <- P[order(rownames(P)),]
#drop subjects without phenotype data
P <- P[rownames(P) %in% phenotype.data[,1],]
#specify prior.D
prior.D <- list(P=P, A=additive.design(8, "happy"), fixed.diplo=F)
#call TIMBR with CRP model
prior.M <- list(model.type="crp", prior.alpha.type="gamma", prior.alpha.shape=1, prior.alpha.rate=2.333415)
results.crp <- TIMBR(y, prior.D, prior.M, samples=100000)
save(results.crp, file=paste0("results/results_crp_", phenotype.var, ".RData"))
|
944f61b02a8523882210332519be29f2ca4a0429
|
0ed1b94c9712f4a4e1bf3bebcd0946baed15cfb3
|
/man/localrank.Rd
|
3a0322ffc537c86f939ba6455bb103bfe8c2652e
|
[
"BSD-2-Clause"
] |
permissive
|
RBigData/localrank
|
0df97f1e9c7bd798c7ff8d37d323fc381d87eef5
|
5510e641eb5d5a935adc77970d93da63b6ab3089
|
refs/heads/master
| 2020-05-07T14:49:22.653782
| 2019-04-10T15:23:54
| 2019-04-10T15:23:54
| 180,610,032
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 240
|
rd
|
localrank.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/localrank.r
\name{localrank}
\alias{localrank}
\title{localrank}
\usage{
localrank()
}
\description{
Get the node-local MPI rank from the default communicator.
}
|
fdb1bbcd24254e5d3873d7c152620fe0330240a9
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/DACF/examples/lw.t.test.Rd.R
|
997dd68cd5b5a2de0623ad732b921149bf440997
|
[] |
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
| 341
|
r
|
lw.t.test.Rd.R
|
library(DACF)
### Name: lw.t.test
### Title: lw.t.test
### Aliases: lw.t.test
### ** Examples
x1.c=induce.cfe(0,.3,rnorm(1000,20,5)) #group 1 scores with 30% ceiling data
x2.c=induce.cfe(.15,0,rnorm(1000,30,5)) #group 2 scores with 15% floor data
lw.t.test(x1.c,x2.c,"a") #using truncated n
lw.t.test(x1.c,x2.c,"b") #using original n
|
fe5a989db173345e71495ab15688dc9f239b2cf8
|
23fba2056e355417694f0f2eaac36076f20fb643
|
/R/config_hello.R
|
9ab4206d767ccc3666bcb04c2f18896ac4d6b305
|
[
"MIT"
] |
permissive
|
gcinar/covr-config-issue
|
1585688505345bf030b71d4f6724b28967976012
|
f59190e455b937bd2ee661bda4a9ad54a66a1c0c
|
refs/heads/master
| 2020-08-26T20:58:09.618707
| 2019-11-06T02:21:24
| 2019-11-06T02:21:24
| 217,146,714
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 218
|
r
|
config_hello.R
|
library(config)
config_hello <- function() {
msg <- config::get("some_config", file = system.file("config.yml", package = "covrconfig"))
return(msg)
}
hello <- function() {
msg <- "hi"
return(msg)
}
|
51116ce8ae5a7c3fe69e376c79c2703782a5a6b9
|
ca89150de15796fe9d6046dc10170b4c6f905e48
|
/Project 2 - Outlier Detection Benchmark Datasets/generate_silhouette_scores.R
|
381a8d9670a674985fbf577570103b9ff1ff231b
|
[] |
no_license
|
shouyang/NSERC2019
|
b716d2c580c6c433cafa85434e873715751fb426
|
67649e46ade9800b6475c2077e1a2ec8e49b4c63
|
refs/heads/master
| 2020-07-15T13:19:07.757327
| 2019-08-31T21:36:02
| 2019-08-31T21:36:02
| 205,570,049
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 548
|
r
|
generate_silhouette_scores.R
|
library(foreign)
library(glue)
library(NbClust)
#
DATASET_NAME <- "WBC_withoutdupl_v10"
FILE_PATH <- "datasets/literature/WBC/WBC_withoutdupl_norm_v10.arff"
df <- read.arff(FILE_PATH)
df.inliers <- df[df$outlier == "no", ]
df.outliers <- df[df$outlier == "yes", ]
attribute_names <- names(df)[!names(df) %in% c("id", "outlier", "alphaLevel")]
attribute_indexes <- subset(1:ncol(df), !names(df) %in% c("id", "outlier", "alphaLevel"))
#
NbClust(df[, attribute_names], max.nc = 100, method = "ward.D2", index = c("silhouette", "ch", "db"))
|
65751c91ec7e89dbd757a273f236c83521b6ad60
|
55926613ee7503229c9f4a5560a205e30b2956cf
|
/secondpart.R
|
d822f2fd11f31f4696db77da6bcc8c1f2ad946eb
|
[] |
no_license
|
biofelip/Nitrates-and-Valvometry
|
67fd8f819052fbc7805760b5678bd0641e885488
|
c050e206bf734b2b808c521bf23d6f62fb5e30ca
|
refs/heads/master
| 2023-03-11T17:59:50.792302
| 2021-02-22T13:05:44
| 2021-02-22T13:05:44
| 275,123,057
| 0
| 0
| null | null | null | null |
WINDOWS-1250
|
R
| false
| false
| 5,960
|
r
|
secondpart.R
|
##este script busca extraer los datos de valvometria y analsisis de videos
##para todos los videos de Control, 250 y 500 mg para los 5 primeros minutos
##posteriores a la adicion de los nitratos
setwd("C:/Users/felip/Documents/PhD/Douda/experiments joanna/Second approach/analisis videos completo")
library(tidyverse)
library(ggplot2)
library(changepoint)
library(gganimate)
library(plotly)
completedata=read.csv("5obsseccompleto.csv", header = TRUE)
Valvom=completedata %>% filter(CONCENTRATION %in% c("250mg", "500mg") & TFE >= 0 & TFE <=180)
Valvoml=split(Valvom, f=list(Valvom$BIVALVE, Valvom$CONCENTRATION))
Valvoml=Valvoml[lapply(Valvoml, nrow)>0]
names(Valvoml)=c("T5M1-250", "T4M3-250","T6M4-250", "NA1","T4M2-250", "T4M5-250", "T6M1-250","NA2","T3M1-500","T5M3-500","NA3","T4M1-500","T3M3-500","T5M5-500","T6M5-500","T6M2-500")
Valvoml=Valvoml[-grep(pattern = "NA", names(Valvoml))]
valp=ggplot(Valvom, aes(x=TFE, y=Percentage))+geom_line()+facet_wrap(~CONCENTRATION+BIVALVE)
valp=valp + geom_point() +transition_reveal(TFE)
b=animate(valp, fps = 5, nframes=900, renderer = ffmpeg_renderer())
anim_save("allvalv.mp4", b)
###haciendo el video para el anexo vien aspero
valanex=Valvoml2[[2]]
plotvanex=ggplot(valanex, aes(x=index(valanex)+35, y=Percentage, col="Valvometry"))+geom_line()+
geom_line(data = imagelist[[9]], aes(x=index(imagelist[[9]]), y=Area, col="Image analysis"))+
labs(x="Index", y="Percentage")
plotvanex=plotvanex + transition_reveal(index(imagelist[[9]]))
plotanexb=animate(plotvanex, fps=5, nframes=900, renderer=ffmpeg_renderer())
anim_save("pltoanex.mp4", plotanexb)
setwd("CUTVIDEOS")
filenames=list.files(pattern = ".csv")
imagelist=lapply(filenames,read.csv)
names(imagelist)=filenames
imagelist=lapply(imagelist, function(x) x=x[,1:3])
for ( i in 1: length(imagelist)){imagelist[[i]]$TEF=1:nrow(imagelist[[i]])}
imagelist=lapply(imagelist, function(x) x=subset(x, TEF<= 900 ))
for ( i in 1: length(imagelist)){imagelist[[i]]$video=filenames[i]}
for ( i in 1: length(imagelist)){imagelist[[i]]$Area=imagelist[[i]]$Area/max(imagelist[[i]]$Area)}
##utlizando ´pltly para encontrar los puntos erroneos, el rollmena sirve para quitar los cambios
##fuerte que no representan cambio real
for ( i in 1: length(imagelist)){imagelist[[i]]$Area=rollmean(imagelist[[i]]$Area,5,fill = c(mean(imagelist[[i]]$Area[1:300]),mean(imagelist[[i]]$Area[300:600]), mean(imagelist[[i]]$Area[600:900])))}
for ( i in 1: length(imagelist)){imagelist[[i]]$Eccentricity=rollmean(imagelist[[i]]$Eccentricity,5,fill = c(mean(imagelist[[i]]$Eccentricity[1:300]),mean(imagelist[[i]]$Eccentricity[300:600]), mean(imagelist[[i]]$Eccentricity[600:900])))}
p=do.call(rbind, imagelist[-c(1,2,3,6,10)]) %>% ggplot( aes(x=TEF, y=Area))+geom_line()+geom_line(aes(x=TEF, y=Eccentricity), color="red")+facet_wrap(~video)
p=p + geom_point() +transition_reveal(TEF)
a=animate(p, fps = 5, nframes=900, renderer = ffmpeg_renderer())
anim_save("all.mp4", a)
ggplotly(p)
##changepoint media
cptmvars=lapply(imagelist[-c(1,2,3,6,10)], function(x) cpt.mean(x$Area, method = "PELT",penalty = "Manual", pen.value = 0.015 ))
for ( i in 1:length(cptmvars)){plot(cptmvars[[i]], main=names(cptmvars)[i])}
cptvalv=lapply(Valvoml, function(x) cpt.mean(x$Percentage, method = "PELT",penalty = "Manual", pen.value = 0.015 ))
for ( i in 1:length(cptvalv)){plot(cptvalv[[i]], main=names(cptvalv)[i])}
correccion=c(11,18,37,0,38,10,-161,17,11,-232,9,50,18)
##Because the algotithm is detecting some point that are not the
##ones we are interested in we will select the correct points from
##each set of changepoint to match the actual initial change
fstVid=c(1,2,4,1,1,2,1,1,1,1,3,1,1,2)
fstvalv=c(1,1,1,1,1,1,2,1,1,1,1,1,1,1)
firstovs=data.frame(matrix(nrow = 14, ncol = 2))
colnames(firstovs)=c("video", "Img")
for ( i in 1:length(cptmvars)){
firstovs$video[i]=names(cptmvars)[i]
firstovs$Img[i]=cpts(cptmvars[[i]])[fstVid[i]]}
firstovs$video=gsub("resultados","",firstovs$video); firstovs$video=gsub(".mp4.csv","",firstovs$video)
firstovs2=data.frame(matrix(nrow = 13, ncol = 2))
colnames(firstovs2)=c("video", "valv")
for ( i in 1:length(cptvalv)){
firstovs2$video[i]=names(cptvalv)[i]
firstovs2$valv[i]=cpts(cptvalv[[i]])[fstvalv[i]]+correccion[i]}
fobs=merge(firstovs, firstovs2, by="video", all.x = TRUE)
## erase the two rowa that did not work properly or were not
##represented in both data types T4M2-250 and T5M4-500
fobs=fobs[-c(4,9),]
fobs$conc="500mg"
fobs$conc[grep("250", fobs$video)]="250mg"
fobs$valvs=fobs$valv*0.20;fobs$Imgs=fobs$Img*0.20
##comparison in reaction times
##tip for the future: the default device for plots in r studio renders
##the grpahed jagged and awfull the last line prevents this in the final
#plot by using the cairo device instead
P2=fobs %>% select(-c(Img, valv)) %>% pivot_longer(cols = -c(video, conc), names_to="variable", values_to="time") %>%
ggplot( aes(x=variable, y=time, col=conc))+geom_point()+geom_line(aes(group=video), size=0.7)+facet_wrap(~conc)+ylab("Time to first reaction (seconds)")+
scale_x_discrete("Detection method", labels=c("Image \n analysis", "Valvometry"))+theme(legend.position = "none")+
ggsave("ttestcomp.png", type = "cairo")
## t test 250###
plot(lm(valvs-Imgs~c(1:5), data = filter(fobs, conc=="250mg")))
plot(lm(valvs-Imgs~c(1:7), data = filter(fobs, conc=="500mg")),which=4)
pt250=with(subset(fobs, conc=="250mg"), t.test(valvs,Imgs, paired = TRUE))
pt500=with(subset(fobs, conc=="500mg"), t.test(valvs,Imgs, paired = TRUE))
table(fobs$conc)
correccion2=correccion[-c(7,10)]
Valvoml2=Valvoml[-c(7,10)]
for (i in 1:length(Valvoml2)){print(ymd_hms(Valvoml2[[i]]$TIME[fobs$valv[-c(7,10)][i]])-ymd_hms(Valvoml2[[i]]$TIME[1+correccion2[i]]))}
for (i in 1:length(Valvoml)){print(ymd_hms(Valvoml[[i]]$TIME[fobs$valv[i]])-ymd_hms(Valvoml[[i]]$TIME[correccion[i]]))}
diferencia=fobs$valvs-fobs$Imgs
tapply(diferencia[-8], fobs$conc[-8], sd)
|
826a3bb2ac71a02be5567856fe78f9ebb8bb2102
|
c8c8e105b1d397477aef2b1f8408dbe9ea74ebc7
|
/R/internal_functions.r
|
a809a60149e3b19ef79d6acef67b8d1005e4883d
|
[] |
no_license
|
Arothron/deformetrics
|
d251b80231afc185d0ad0a6f60ee7037fb522fd8
|
1b21cffe153d5139f0db41e7198e0e2a527d8edf
|
refs/heads/master
| 2021-01-21T23:13:18.349232
| 2017-04-11T17:14:01
| 2017-04-11T17:14:01
| 95,209,056
| 1
| 0
| null | 2017-06-23T10:11:30
| 2017-06-23T10:11:30
| null |
UTF-8
|
R
| false
| false
| 108,984
|
r
|
internal_functions.r
|
#' Internal_functions
#'
#' Here are reported a collection of internal functions
#' @author Paolo Piras
#' @export
plot2dhull<-function(matrix,group,scalevariable=1,asp=1,extl=F,legend=T,xl=NULL,yl=NULL,posl=c("topright"),labels=NULL,clabel=0,pch=19,lwd=0.5,colhull=NULL,col=as.numeric(group),xlab=NULL,ylab=NULL,grey=F,xlimi=range(matrix[,1])*1.3,ylimi=range(matrix[,2])*1.3,reorder=T,alpha=rep(0,nlevels(group))){
library(MASS)
library(compositions)
library(spatstat)
library(gdata)
library(TeachingDemos)
library(ade4)
library(calibrate)
if (!is.factor(group)) stop("'group' must be a factor")
makeTransparent = function(..., alpha=0.5) {
if(alpha<0 | alpha>1) stop("alpha must be between 0 and 1")
alpha = floor(255*alpha)
newColor = col2rgb(col=unlist(list(...)), alpha=FALSE)
.makeTransparent = function(col, alpha) {
rgb(red=col[1], green=col[2], blue=col[3], alpha=alpha, maxColorValue=255)
}
newColor = apply(newColor, 2, .makeTransparent, alpha=alpha)
return(newColor)
}
x<-matrix[,1]
y<-matrix[,2]
if(reorder==T){group<-factor(group,levels=unique(group))}
species<-as.numeric(group)
col=col
if(grey==T){col=col2grey(col)}
coli<-data.frame(group,as.numeric(group),col,pch)
if(is.null(colhull)){colhull=aggregate(coli[,-1],by=list(coli[,1]),mean)[,-3][,2]}else{colhull=colhull}
colim<-cbind(aggregate(coli[,-1],by=list(coli[,1]),mean)[,-c(3,4)],colhull)
plot(x,y,type="p",cex=scalevariable,col=as.character(coli[,3]),pch=pch,xlim=xlimi,ylim=ylimi,xlab=xlab,ylab=ylab,asp=asp)
if(!is.null(labels)){textxy(x,y,labels)}else{NULL}
for(i in 1:(max(species)))
{
abline(h=0,v=0)
if(length(x[species==i])<3){NULL}else{
hulli<-convexhull.xy(subset(cbind(x,y),species==i))
par(new=T)
plot(hulli,col=makeTransparent(colim[,3][i], 1,alpha=alpha[i]),lwd=lwd,lty=i,add=T,asp=asp)
par(new=T)
daplotx<-c(hulli$bdry[[1]][[1]][length(hulli$bdry[[1]][[1]])],hulli$bdry[[1]][[1]])
daploty<-c(hulli$bdry[[1]][[2]][length(hulli$bdry[[1]][[2]])],hulli$bdry[[1]][[2]])
par(new=T)
plot(daplotx,daploty,lwd=lwd,type="l",lty=i,col=colim[,3][i],xlim=xlimi,ylim=ylimi,axes=F,xlab="",ylab="",asp=asp)
}
}
opar <- par(mar = par("mar"))
par(mar = c(0.1, 0.1, 0.1, 0.1))
on.exit(par(opar))
meansx<-aggregate(matrix[,1],by=list(group),FUN=mean)
meansy<-aggregate(matrix[,2],by=list(group),FUN=mean)
if (clabel > 0)
for(i in 1:nlevels(group)){ scatterutil.eti(meansx[i,-1],meansy[i,-1], meansx[,1][i], clabel,coul=1)}
if(legend==T){
if(extl==T){
x11()
plot(x,y,col="white")
legend(min(x),max(y),unique(coli[,1]), cex=1, col=unique(coli[,3]), pch=unique(coli[,4]),box.col="white")
}else{
if(is.null(xl)==T&is.null(yl)==T){
legend(posl,legend=unique(coli[,1]), col=unique(coli[,3]), pch=unique(coli[,4]),bty='n')}else{
legend(xl,yl,unique(coli[,1]),col=unique(coli[,3]),pch=unique(coli[,4]),bty='n')}
}
}
}
#' export
ptau6<-function(array,factor,CSinit=T,sepure=F,polyn=1,CR=NULL,locs=NULL,perm=999){
library(Morpho)
library(shapes)
library(vegan)
warning("WARNING: this function reorders data (if they are not) in increasing size order within each level")
k<-dim(array)[1]
m<-dim(array)[2]
n<-dim(array)[3]
newarray<-array[,,order(factor,centroid.size(array))]
factor<-factor[order(factor)]
cbind(dimnames(newarray)[[3]],as.character(factor))
depepure<-array2mat(procSym(newarray,pcAlign=F,CSinit=CSinit,scale=F)$orpdata,n,k*m)
if(sepure==T){depepure<-array2mat(sepgpa(newarray,factor,CSinit=CSinit,scale=F)$mountedorpdata,n,k*m)}
indepepure<-centroid.size(newarray)
print("Individual multivariate (linear) regression between shape and size" )
print(manymultgr(depepure,indepepure,factor,steps=perm))
print("Pairwise *linear* mancova p-values on original data")
print(pwpermancova(depepure,indepepure,factor,nperm=perm)$p_adonis_pred1_pred2)
thedatapure<-data.frame(indepure=indepepure,depure=depepure)
thelmlistpure<-NULL
mypredictpure<-NULL
myresidpure<-NULL
for(i in 1:nlevels(factor)){
thelmpurei<-lm(as.matrix(thedatapure[,-1][as.numeric(factor)==i,])~poly(indepure[as.numeric(factor)==i],degree=polyn,raw=TRUE),data=thedatapure)
mypredictpurei<-predict(thelmpurei)
myresidpurei<-resid(thelmpurei)
thelmlistpure<-c(thelmlistpure,list(thelmpurei))
mypredictpure<-rbind(mypredictpure,mypredictpurei)
myresidpure<-rbind(myresidpure,myresidpurei)
}
mypredictpure<-read.inn(mypredictpure,k,m)
myresidpure<-read.inn(myresidpure,k,m)
if(is.null(CR)==T){CR<-procSym(mypredictpure[,,firstsfac(factor)],scale=F,pcAlign=F,reflect=F,CSinit=F)$mshape}else{CR<-CR}
if(is.null(locs)==T){locs<-mypredictpure[,,firstsfac(factor)]}else{locs<-locs}
prls<-lshift2(mypredictpure,factor,CSinit=CSinit,CR=CR,locs=locs)
common<-array2mat(procSym(newarray,pcAlign=,scale=F,CSinit=CSinit)$orpdata,n,k*m)
print("Pairwise multivariate (linear) regression between shape and size" )
print(pwpermancova(common,indepepure,factor,nperm=perm)$p_adonis_pred1_pred2)
space1<-prcomp(array2mat(prls$transported,n,k*m))
space1mshape<-procSym(prls$transported,pcAlign=F)$mshape
origtrasp<-prls$transported+myresidpure
origproj<-predict(space1,array2mat(origtrasp,n,k*m))
print("Pairwise multivariate (linear) regression between shape of transported data and size" )
print(pwpermancova(array2mat(origtrasp,n,k*m),indepepure,factor,nperm=perm)$p_adonis_pred1_pred2)
depepure2<-origtrasp
print("Individual multivariate (linear) regression between shape of transported data and size" )
print(manymultgr(array2mat(depepure2,n,k*m),indepepure,factor,steps=perm))
thedatapure2<-data.frame(indepure2=indepepure,depure2=array2mat(depepure2,n,k*m))
thelmlistpure2<-NULL
mypredictpure2<-NULL
myresidpure2<-NULL
for(i in 1:nlevels(factor)){
thelmpure2i<-lm(as.matrix(thedatapure2[,-1][as.numeric(factor)==i,])~poly(indepure2[as.numeric(factor)==i],degree=polyn,raw=TRUE),data=thedatapure2)
mypredictpure2i<-predict(thelmpure2i)
myresidpure2i<-resid(thelmpure2i)
thelmlistpure2<-c(thelmlistpure2,list(thelmpure2i))
mypredictpure2<-rbind(mypredictpure2,mypredictpure2i)
myresidpure2<-rbind(myresidpure2,myresidpure2i)
}
out<-list(k=k,m=m,n=n,arrayord=newarray,factorord=factor,CR=CR,locs=locs,depepure=depepure,indepepure=indepepure,thelmlistpure=thelmlistpure,predictpure=mypredictpure,residpure=myresidpure,shifted=array2mat(prls$transported,n,k*m),thelmlistpure2=thelmlistpure2,predictpure2=array2mat(prls$transported,n,k*m),predictpure3=mypredictpure2,residpure2=myresidpure2,space1=space1,origtrasp=array2mat(origtrasp,n,k*m),origproj=origproj,space1mshape=space1mshape)
}
#' export
plsgen<-function(block1,block2,plsn=1,links1=NULL,links2=NULL,commonref=F,heatmap=F,heatcolors=c("blue4","cyan2","yellow","red4"),triang1=NULL,triang2=NULL,alpha=1,S1=NA,S2=NA,from1=NULL,to1=NULL,from2=NULL,to2=NULL,rounds=0,sdx=1,sdy=1,labels=NULL,group=NULL,col=1,pch=19,colgroup=NULL,zlim2d=NULL){
require(Morpho)
require(shapes)
thepls<-pls2B(block1,block2,rounds=rounds)
XScores<-thepls$Xscores
YScores<-thepls$Yscores
plot(XScores[, plsn],YScores[,plsn],asp=1,col=col,pch=pch)
if(!is.null(labels)){textxy(XScores[, plsn],YScores[, plsn],labels)}
if(!is.null(group)){plot2dhull(cbind(XScores[, plsn],YScores[, plsn]),group,1,pch=pch,col=col,colhull=colgroup,labels=labels)}else{NULL}
if(!is.null(group)){
xscoresmeans<-as.matrix(aggregate(XScores,by=list(group),mean)[,-1])
rownames(xscoresmeans)<-aggregate(XScores,by=list(group),mean)[,1]
yscoresmeans<-as.matrix(aggregate(YScores,by=list(group),mean)[,-1])
rownames(yscoresmeans)<-aggregate(YScores,by=list(group),mean)[,1]
x11()
plot(xscoresmeans[,plsn],yscoresmeans[,plsn])
textxy(xscoresmeans[,plsn],yscoresmeans[,plsn],rownames(xscoresmeans))
}else{NULL}
if(!is.null(links1)&is.na(S1)==T){S1<-list2matrix(links1)}
if(!is.null(links2)&is.na(S2)==T){S2<-list2matrix(links2)}
theshapes<-plsCoVar(thepls,plsn,sdx=sdx,sdy=sdy)
if(is.matrix(block1)==F){
plsnxpos<-theshapes$x[,,2]
plsnxneg<-theshapes$x[,,1]
css1<-c(cSize(plsnxpos),cSize(plsnxneg))
mshape1<-arrMean3(block1)
if(heatmap==T){
if(dim(plsnxpos)[2]<3){
if(!is.null(links1)){S1<-list2matrix(links1)}
myhxpos<-heat2d(mshape1,plsnxpos,tol=10,nadd=5000,graphics=F,constr=T,colors=heatcolors,linkss=links1,S=S1,zlim=zlim)
myhxneg<-heat2d(mshape1,plsnxneg,tol=10,nadd=5000,graphics=F,constr=T,colors=heatcolors,linkss=links1,S=S1,zlim=zlim)
}else{
if(is.null(triang1)){stop("You cannot want heatmap in 3d without triangulation for block1")}
myhxpos<-diffonmesh(mshape1,plsnxpos,t(triang1),from=from1,to=to1,rampcolors=heatcolors,alphas=c(alpha,0.7),graph=F)
myhxneg<-diffonmesh(mshape1,plsnxneg,t(triang1),from=from1,to=to1,rampcolors=heatcolors,alphas=c(alpha,0.7),graph=F)
}
}
}else{NULL}
if(is.matrix(block2)==F){
plsnypos<-theshapes$y[,,2]
plsnyneg<-theshapes$y[,,1]
css2<-c(cSize(plsnypos),cSize(plsnyneg))
mshape2<-arrMean3(block2)
if(heatmap==T){
if(dim(plsnypos)[2]<3){
if(!is.null(links2)){S2<-list2matrix(links2)}
myhypos<-heat2d(mshape2,plsnypos,tol=10,nadd=5000,graphics=F,constr=T,colors=heatcolors,linkss=links2,S=S2)
myhyneg<-heat2d(mshape2,plsnyneg,tol=10,nadd=5000,graphics=F,constr=T,colors=heatcolors,linkss=links2,S=S2)
}else{
if(is.null(triang2)){stop("You cannot want heatmap in 3d without triangulation for block2")}
myhypos<-diffonmesh(mshape2,plsnypos,t(triang2),from=from2,to=to2,rampcolors=heatcolors,alphas=c(alpha,0.7),graph=F)
myhyneg<-diffonmesh(mshape2,plsnyneg,t(triang2),from=from2,to=to2,rampcolors=heatcolors,alphas=c(alpha,0.7),graph=F)
}
}
}else{NULL}
###### forma matrice
if(length(dim(block1))>2&length(dim(block2))<3){
if(css1[1]<css1[2]){themax=plsnxneg}
if(css1[1]>css1[2]){themax=plsnxpos}
if(css1[1]==css1[2]){themax=plsnxpos}
if(dim(block1)[2]>2){
open3d(windowRect=c(100,100,1000,1000))
mat <- matrix(1:4, ncol=2)
layout3d(mat, height = rep(c(2,1), 2), model = "inherit")
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
if(heatmap==T){
shade3d(myhxpos$obm$colMesh,alpha=alpha)
if(is.null(links1)==F){lineplot(plsnxpos,links1,col=1)}
}else{
plot3d(plsnxpos,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links1)==F){lineplot(plsnxpos,links1,col=1)}}
next3d()
text3d(0,0,0, "Block1 positive")
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
if(heatmap==T){
shade3d(myhxneg$obm$colMesh,alpha=alpha)
if(is.null(links1)==F){lineplot(plsnxneg,links1,col=1)}
}else{
plot3d(plsnxneg,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links1)==F){lineplot(plsnxneg,links1,col=1)}}
next3d()
text3d(0,0,0, "Block1 negative")
}
if(dim(block1)[2]<3){
par(mfrow=c(1,2))
if(heatmap==T){
image.plot(xyz2img(cbind(myhxpos$interpcoords,myhxpos$pred),tolerance=myhxpos$tol),asp=1,xlim=range(themax[,1]),ylim=range(themax[,2]),col=myhxpos$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhxpos$mate,xlim=range(themax[,1]),ylim=range(themax[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links1)==F){lineplot(myhxpos$mate,links1)}
lines(myhxpos$tpsgrid$grid$ngrid,xlim=range(themax[,1]),ylim=range(themax[,2]))
lines(myhxpos$tpsgrid$grid$ngrid2,xlim=range(themax[,1]),ylim=range(themax[,2]))
par(new=T)
plot(myhxpos$mate2,xlim=range(themax[,1]),ylim=range(themax[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links1)==F){lineplot(myhxpos$mate2,links1,col=2,lwd=1)}
title("Block1 positive")
image.plot(xyz2img(cbind(myhxneg$interpcoords,myhxneg$pred),tolerance=myhxneg$tol),asp=1,xlim=range(themax[,1]),ylim=range(themax[,2]),col=myhxneg$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhxneg$mate,xlim=range(themax[,1]),ylim=range(themax[,2]),asp=1,pch=19,cex=0.5,col=2,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links1)==F){lineplot(myhxneg$mate,links1)}
lines(myhxneg$tpsgrid$grid$ngrid,xlim=range(themax[,1]),ylim=range(themax[,2]))
lines(myhxneg$tpsgrid$grid$ngrid2,xlim=range(themax[,1]),ylim=range(themax[,2]))
par(new=T)
plot(myhxneg$mate2,xlim=range(themax[,1]),ylim=range(themax[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links1)==F){lineplot(myhxneg$mate2,links1,col=2,lwd=1)}
title("Block1 negative")
}else{
plotmyarrays(plsnxpos,pch=19,links=links1,txt=F,xlim=range(themax[,1]),ylim=range(themax[,2]))
title("Block1 positive")
plotmyarrays(plsnxneg,pch=19,links=links1,txt=F,xlim=range(themax[,1]),ylim=range(themax[,2]))
title("Block1 negative")
}
}
}
######### matrice forma
if(length(dim(block1))<3&length(dim(block2))>2){
if(css2[1]<css2[2]){themax=plsnyneg}
if(css2[1]>css2[2]){themax=plsnypos}
if(css2[1]==css2[2]){themax=plsnypos}
if(dim(block2)[2]>2){
open3d(windowRect=c(100,100,1000,1000))
mat <- matrix(1:4, ncol=2)
layout3d(mat, height = rep(c(2,1), 2), model = "inherit")
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
if(heatmap==T){
shade3d(myhypos$obm$colMesh,alpha=alpha)
if(is.null(links2)==F){lineplot(plsnypos,links2,col=1)}
}else{
plot3d(plsnypos,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links2)==F){lineplot(plsnypos,links2,col=1)}}
next3d()
text3d(0,0,0, "Block2 positive")
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
if(heatmap==T){
shade3d(myhyneg$obm$colMesh,alpha=alpha)
if(is.null(links2)==F){lineplot(plsnyneg,links2,col=1)}
}else{
plot3d(plsnyneg,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links2)==F){lineplot(plsnypos,links2,col=1)}}
next3d()
text3d(0,0,0, "Block2 negative")
}
if(dim(block2)[2]<3){
par(mfrow=c(1,2))
if(heatmap==T){
image.plot(xyz2img(cbind(myhypos$interpcoords,myhypos$pred),tolerance=myhypos$tol),asp=1,xlim=range(themax[,1]),ylim=range(themax[,2]),col=myhypos$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhypos$mate,xlim=range(themax[,1]),ylim=range(themax[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links2)==F){lineplot(myhypos$mate,links2)}
lines(myhypos$tpsgrid$grid$ngrid,xlim=range(themax[,1]),ylim=range(themax[,2]))
lines(myhypos$tpsgrid$grid$ngrid2,xlim=range(themax[,1]),ylim=range(themax[,2]))
par(new=T)
plot(myhypos$mate2,xlim=range(themax[,1]),ylim=range(themax[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links2)==F){lineplot(myhypos$mate2,links2,col=2,lwd=2)}
title("Block2 positive")
image.plot(xyz2img(cbind(myhyneg$interpcoords,myhyneg$pred),tolerance=myhyneg$tol),asp=1,xlim=range(themax[,1]),ylim=range(themax[,2]),col=myhyneg$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhyneg$mate,xlim=range(themax[,1]),ylim=range(themax[,2]),asp=1,pch=19,cex=0.5,col=2,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links2)==F){lineplot(myhyneg$mate,links2)}
lines(myhyneg$tpsgrid$grid$ngrid,xlim=range(themax[,1]),ylim=range(themax[,2]))
lines(myhyneg$tpsgrid$grid$ngrid2,xlim=range(themax[,1]),ylim=range(themax[,2]))
par(new=T)
plot(myhyneg$mate2,xlim=range(themax[,1]),ylim=range(themax[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links2)==F){lineplot(myhyneg$mate2,links2,col=2,lwd=2)}
title("Block2 negative")
}else{
plotmyarrays(plsnypos,pch=19,links=links2,txt=F,xlim=range(themax[,1]),ylim=range(themax[,2]))
title("Block2 positive")
plotmyarrays(plsnyneg,pch=19,links=links2,txt=F,xlim=range(themax[,1]),ylim=range(themax[,2]))
title("Block2 negative")}
}
}
######## forma forma
if(length(dim(block1))>2&length(dim(block2))>2){
if(dim(block1)[2]>2&dim(block2)[2]>2){
allcss<-c(css1,css2)
themax<-list(plsnxpos,plsnxneg,plsnypos,plsnyneg)[which.max(allcss)][[1]]
themaxx<-list(plsnxpos,plsnxneg)[which.max(css1)][[1]]
themaxy<-list(plsnypos,plsnyneg)[which.max(css2)][[1]]
open3d(windowRect=c(100,100,1000,1000))
mat <- matrix(1:8, ncol=2)
layout3d(mat, height = rep(c(2,1), 2), model = "inherit")
if(commonref==T){plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)}else{
plot3d(themaxx*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
}
if(heatmap==T){
shade3d(myhxpos$obm$colMesh,alpha=alpha)
if(is.null(links1)==F){lineplot(plsnxpos,links1,col=1)}
}else{
plot3d(plsnxpos,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links1)==F){lineplot(plsnxpos,links1,col=1)}}
next3d()
text3d(0,0,0, "Block1 positive")
next3d()
if(commonref==T){plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)}else{
plot3d(themaxx*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
}
if(heatmap==T){
shade3d(myhxneg$obm$colMesh,alpha=alpha)
if(is.null(links1)==F){lineplot(plsnxneg,links1,col=1)}
}else{
plot3d(plsnxneg,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links1)==F){lineplot(plsnxneg,links1,col=1)}}
next3d()
text3d(0,0,0, "Block1 negative")
next3d()
if(commonref==T){plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)}else{
plot3d(themaxy*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
}
if(heatmap==T){
shade3d(myhypos$obm$colMesh,alpha=alpha)
if(is.null(links2)==F){lineplot(plsnypos,links2,col=1)}
}else{
plot3d(plsnypos,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links2)==F){lineplot(plsnypos,links2,col=1)}}
next3d()
text3d(0,0,0, "Block2 positive")
next3d()
if(commonref==T){plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)}else{
plot3d(themaxy*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
}
if(heatmap==T){
shade3d(myhyneg$obm$colMesh,alpha=alpha)
if(is.null(links2)==F){lineplot(plsnyneg,links2,col=1)}
}else{
plot3d(plsnyneg,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links2)==F){lineplot(plsnyneg,links2,col=1)}}
next3d()
text3d(0,0,0, "Block2 negative")
}
if(dim(block1)[2]>2&dim(block2)[2]<3){
open3d(windowRect=c(100,100,1000,1000))
themaxx<-list(plsnxpos,plsnxneg)[which.max(css1)][[1]]
themaxy<-list(plsnypos,plsnyneg)[which.max(css2)][[1]]
mat <- matrix(1:8, ncol=2)
layout3d(mat, height = rep(c(2,1), 2), model = "inherit")
plot3d(themaxx*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
if(heatmap==T){
shade3d(myhxpos$obm$colMesh,alpha=alpha)
if(is.null(links1)==F){lineplot(plsnxpos,links1,col=1)}
}else{
plot3d(plsnxpos,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links1)==F){lineplot(plsnxpos,links1,col=1)}}
next3d()
text3d(0,0,0, "Block1 positive")
next3d()
plot3d(themaxx*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
if(heatmap==T){
shade3d(myhxneg$obm$colMesh,alpha=alpha)
if(is.null(links1)==F){lineplot(plsnxneg,links1,col=1)}
}else{
plot3d(plsnxneg,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links1)==F){lineplot(plsnxneg,links1,col=1)}}
next3d()
text3d(0,0,0, "Block1 negative")
if(heatmap==T){
png(file = "myplot.png", bg = "transparent",width = 780, height = 780)
image.plot(xyz2img(cbind(myhypos$interpcoords,myhypos$pred),tolerance=myhypos$tol),asp=1,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),col=myhypos$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhypos$mate,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="",main="Block2 positive")
if(is.null(links2)==F){lineplot(myhypos$mate,links2)}
lines(myhypos$tpsgrid$grid$ngrid,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
lines(myhypos$tpsgrid$grid$ngrid2,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
par(new=T)
plot(myhypos$mate2,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links2)==F){lineplot(myhypos$mate2,links2,col=2,lwd=2)}
dev.off()
show2d(filename="myplot.png",ignoreExtent = F)
next3d()
text3d(0,0,0, "Block2 positive")
next3d()
png(file = "myplot.png", bg = "transparent",width = 780, height = 780)
image.plot(xyz2img(cbind(myhyneg$interpcoords,myhyneg$pred),tolerance=myhyneg$tol),asp=1,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),col=myhyneg$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhyneg$mate,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="",main="Block2 negative")
if(is.null(links2)==F){lineplot(myhyneg$mate,links2)}
lines(myhyneg$tpsgrid$grid$ngrid,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
lines(myhyneg$tpsgrid$grid$ngrid2,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
par(new=T)
plot(myhyneg$mate2,xlim=range(themax[,1]),ylim=range(themaxy[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links2)==F){lineplot(myhyneg$mate2,links2,col=2,lwd=2)}
dev.off()
show2d(filename="myplot.png",ignoreExtent = F)
next3d()
text3d(0,0,0, "Block2 negative")
}else{
next3d()
plot3d(cbind(themaxy,0)*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(cbind(plsnypos,0),bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links2)==F){lineplot(cbind(plsnypos,0),links2,col=1)}
next3d()
text3d(0,0,0, "Block2 positive")
next3d()
plot3d(cbind(themaxy,0)*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(cbind(plsnyneg,0),bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links2)==F){lineplot(cbind(plsnyneg,0),links2,col=1)}
next3d()
text3d(0,0,0, "Block2 negative")}
}
if(dim(block1)[2]<3&dim(block2)[2]>2){
open3d(windowRect=c(100,100,1000,1000))
themaxx<-list(plsnxpos,plsnxneg)[which.max(css1)][[1]]
themaxy<-list(plsnypos,plsnyneg)[which.max(css2)][[1]]
mat <- matrix(1:8, ncol=2)
layout3d(mat, height = rep(c(2,1), 2), model = "inherit")
if(heatmap==T){
png(file = "myplot.png", bg = "transparent",width = 780, height = 780)
image.plot(xyz2img(cbind(myhxpos$interpcoords,myhxpos$pred),tolerance=myhxpos$tol),asp=1,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),col=myhypos$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhxpos$mate,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="",main="Block1 positive")
if(is.null(links1)==F){lineplot(myhxpos$mate,links1)}
lines(myhxpos$tpsgrid$grid$ngrid,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]))
lines(myhxpos$tpsgrid$grid$ngrid2,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]))
par(new=T)
plot(myhxpos$mate2,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links1)==F){lineplot(myhxpos$mate2,links1,col=2,lwd=2)}
dev.off()
show2d(filename="myplot.png",ignoreExtent = F)
next3d()
text3d(0,0,0, "Block1 positive")
next3d()
png(file = "myplot.png", bg = "transparent",width = 780, height = 780)
image.plot(xyz2img(cbind(myhxneg$interpcoords,myhxneg$pred),tolerance=myhxneg$tol),asp=1,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),col=myhxneg$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhxneg$mate,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="",main="Block1 negative")
if(is.null(links1)==F){lineplot(myhxneg$mate,links1)}
lines(myhxneg$tpsgrid$grid$ngrid,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]))
lines(myhxneg$tpsgrid$grid$ngrid2,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]))
par(new=T)
plot(myhxneg$mate2,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links1)==F){lineplot(myhxneg$mate2,links1,col=2,lwd=2)}
dev.off()
show2d(filename="myplot.png",ignoreExtent = F)
next3d()
text3d(0,0,0, "Block1 negative")
}else{
plot3d(cbind(themaxx,0)*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(cbind(plsnxpos,0),bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links1)==F){lineplot(cbind(plsnxpos,0),links1,col=1)}
next3d()
text3d(0,0,0, "Block1 positive")
next3d()
plot3d(cbind(themaxx,0)*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(cbind(plsnxneg,0),bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links2)==F){lineplot(cbind(plsnxneg,0),links1,col=1)}
next3d()
text3d(0,0,0, "Block1 negative")}
next3d()
plot3d(themaxy*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
if(heatmap==T){
shade3d(myhypos$obm$colMesh,alpha=alpha)
if(is.null(links2)==F){lineplot(plsnypos,links2,col=1)}
}else{
plot3d(plsnypos,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links2)==F){lineplot(plsnypos,links2,col=1)}}
next3d()
text3d(0,0,0, "Block2 positive")
next3d()
plot3d(themaxy*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
if(heatmap==T){
shade3d(myhyneg$obm$colMesh,alpha=alpha)
if(is.null(links2)==F){lineplot(plsnyneg,links2,col=1)}
}else{
plot3d(plsnyneg,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links2)==F){lineplot(plsnyneg,links2,col=1)}}
next3d()
text3d(0,0,0, "Block2 negative")
}#### fine condizione 2d/3d
if(dim(block1)[2]<3&dim(block2)[2]<3){
themax<-list(plsnxpos,plsnxneg,plsnypos,plsnyneg)[which.max(c(css1,css2))][[1]]
if(which.max(css1)<2){themaxx<-plsnxpos}else{themaxx<-plsnxneg}
if(which.max(css2)<2){themaxy<-plsnypos}else{themaxy<-plsnyneg}
par(mfrow=c(2,2))
if(heatmap==F){
if(commonref==T){plotmyarrays(plsnxpos,links=links1,txt=F,pch=19,xlim=range(themax[,1]),ylim=range(themax[,2]))}else{
plotmyarrays(plsnxpos,links=links1,txt=F,pch=19,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]))
}
title("Block1 positive")
if(commonref==T){plotmyarrays(plsnxneg,links=links1,txt=F,pch=19,xlim=range(themax[,1]),ylim=range(themax[,2]))}else{
plotmyarrays(plsnxneg,links=links1,txt=F,pch=19,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]))
}
title("Block1 negative")
if(commonref==T){plotmyarrays(plsnypos,links=links1,txt=F,pch=19,xlim=range(themax[,1]),ylim=range(themax[,2]))}else{
plotmyarrays(plsnypos,links=links1,txt=F,pch=19,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
}
title("Block2 positive")
if(commonref==T){plotmyarrays(plsnyneg,links=links1,txt=F,pch=19,xlim=range(themax[,1]),ylim=range(themax[,2]))}else{
plotmyarrays(plsnyneg,links=links1,txt=F,pch=19,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
}
title("Block2 positive")}else{
image.plot(xyz2img(cbind(myhxpos$interpcoords,myhxpos$pred),tolerance=myhxpos$tol),asp=1,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),col=myhxpos$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhxpos$mate,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="",main="Block1 positive")
if(is.null(links1)==F){lineplot(myhxpos$mate,links1)}
lines(myhxpos$tpsgrid$grid$ngrid,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]))
lines(myhxpos$tpsgrid$grid$ngrid2,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]))
par(new=T)
plot(myhxpos$mate2,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links1)==F){lineplot(myhxpos$mate2,links1,col=2,lwd=2)}
image.plot(xyz2img(cbind(myhxneg$interpcoords,myhxneg$pred),tolerance=myhxneg$tol),asp=1,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),col=myhxneg$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhxneg$mate,xlim=range(themaxx[,1]),ylim=range(themaxx[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="",main="Block1 negative")
if(is.null(links1)==F){lineplot(myhxneg$mate,links1)}
lines(myhxneg$tpsgrid$grid$ngrid,xlim=range(themax[,1]),ylim=range(themax[,2]))
lines(myhxneg$tpsgrid$grid$ngrid2,xlim=range(themax[,1]),ylim=range(themax[,2]))
par(new=T)
plot(myhxneg$mate2,xlim=range(themax[,1]),ylim=range(themax[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links1)==F){lineplot(myhxneg$mate2,links1,col=2,lwd=2)}
image.plot(xyz2img(cbind(myhypos$interpcoords,myhypos$pred),tolerance=myhypos$tol),asp=1,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),col=myhypos$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhypos$mate,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="",main="Block2 positive")
if(is.null(links2)==F){lineplot(myhypos$mate,links2)}
lines(myhypos$tpsgrid$grid$ngrid,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
lines(myhypos$tpsgrid$grid$ngrid2,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
par(new=T)
plot(myhypos$mate2,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links2)==F){lineplot(myhypos$mate2,links2,col=2,lwd=2)}
image.plot(xyz2img(cbind(myhyneg$interpcoords,myhyneg$pred),tolerance=myhyneg$tol),asp=1,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),col=myhyneg$cols,xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
par(new=T)
plot(myhyneg$mate,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),asp=1,pch=19,cex=1,xaxt="n",yaxt="n",bty="n",xlab="",ylab="",main="Block2 negative")
if(is.null(links2)==F){lineplot(myhyneg$mate,links2)}
lines(myhyneg$tpsgrid$grid$ngrid,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
lines(myhyneg$tpsgrid$grid$ngrid2,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]))
par(new=T)
plot(myhyneg$mate2,xlim=range(themaxy[,1]),ylim=range(themaxy[,2]),asp=1,pch=19,cex=0.5,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(links2)==F){lineplot(myhyneg$mate2,links2,col=2,lwd=2)}
}
} ##fine 2d/2d
}### fine condizione forma-forma
out<-list(plsob=thepls,allxscores=XScores,allyscores=YScores,if(!is.null(group)){xscoresmeans=xscoresmeans}else{ck=2},if(!is.null(group)){yscoresmeans=yscoresmeans}else{ck=2})
if(length(out)>3){names(out)=c("pls","allxscores","allyscores","xscoresmeans","yscoresmeans")}else{NULL}
return(out)
}
#' export
plotptau5<-function(objptau,links=NULL,projorig=T,whichaxes=c(1,2),cexscale=round(max(centroid.size(objptau$arrayord)),digits=0),shapescale=10,mag=1,subplotdim=2,shiftnegy=1,shiftposy=1,shiftnegx=1,shiftposx=1,col=as.numeric(objptau$factorord),pch=19,triang=NULL,from=0,topcs=NULL,tore=NULL,plotsource=T){
library(TeachingDemos)
k<-dim(objptau$arrayord)[1]
m<-dim(objptau$arrayord)[2]
n<-dim(objptau$arrayord)[3]
transp<-read.inn(objptau$shifted,k,m)
origsize<-objptau$indepepure
if(projorig==T){
ordiwithshapes(objptau$space1mshape,objptau$space1$x,objptau$space1$rotation,procSym=F,whichaxes=whichaxes,addata=objptau$origproj[,whichaxes],asp=1,factraj=objptau$factorord,cex=origsize/cexscale,triang=triang,from=from,to=topcs,links=links,mag=mag,shiftnegy=1.5,shiftposy=2,col=col,pch=pch,subplotdim=subplotdim,plotsource=plotsource)
title("LS on predictions in PCA space and original data re-projected")}else{
ordiwithshapes(objptau$space1mshape,objptau$space1$x,objptau$space1$rotation,procSym=F,whichaxes=whichaxes,asp=1,factraj=objptau$factorord,cex=origsize/cexscale,triang=triang,from=from,to=topcs,links=links,mag=mag,shiftnegy=1.5,shiftposy=2,col=col,pch=pch,subplotdim=subplotdim,plotsource=plotsource)
title("LS on predictions in PCA space")}
ranges<-apply(rbind(objptau$space1$x,objptau$origproj),2,range)
ratesorig<-ratesbygroup(read.inn(objptau$predictpure2,k,m),objptau$factorord,objptau$indepepure)
plot(objptau$indepepure,ratesorig,pch=pch,col=col)
for(i in 1:nlevels(objptau$factorord)){
lines(objptau$indepepure[as.numeric(objptau$factorord)==i][-firstsfac(objptau$factorord)],ratesorig[as.numeric(objptau$factorord)==i][-firstsfac(objptau$factorord)],col=col[firstsfac(objptau$factorord)][i])
}
title("Rates of shape change among consecutive predictions per unit size in original data")
ratestrasp<-ratesbygroup(objptau$predictpure,objptau$factorord,objptau$indepepure)
plot(objptau$indepepure,ratestrasp,pch=pch,col=col)
for(i in 1:nlevels(objptau$factorord)){
lines(objptau$indepepure[as.numeric(objptau$factorord)==i][-firstsfac(objptau$factorord)],ratestrasp[as.numeric(objptau$factorord)==i][-firstsfac(objptau$factorord)],col=col[firstsfac(objptau$factorord)][i])
}
title("Rates of shape change among consecutive predictions per unit size in transported data")
plot(ratesorig,ratestrasp,col=col,pch=pch)
title("Original rates of shape change per unit size vs those of transported data")
adults<-NULL
adultsdaplot<-NULL
for(i in 1:nlevels(objptau$factorord)){
adulti<-array(showPC2(objptau$space1$x[lastsfac(objptau$factorord),1:3][i,],objptau$space1$rotation[,1:3],objptau$space1mshape),dim=c(k,m,1))
adultdaploti<-array(showPC2(objptau$space1$x[lastsfac(objptau$factorord),1:3][i,]*mag,objptau$space1$rotation[,1:3],objptau$space1mshape),dim=c(k,m,1))
adults<-abind::abind(adults,adulti)
adultsdaplot<-abind::abind(adultsdaplot,adultdaploti)
}
if(m<3){adultsdaplot<-abind::abind(adultsdaplot,array(rep(0,k*n),dim=c(k,1,nlevels(objptau$factorord))),along=2)}
init<-array(showPC2(objptau$space1$x[firstsfac(objptau$factorord),1:3][1,],objptau$space1$rotation[,1:3],objptau$space1mshape),dim=c(k,m,1))
initdaplot<-array(showPC2(objptau$space1$x[firstsfac(objptau$factorord),1:3][1,]*mag,objptau$space1$rotation[,1:3],objptau$space1mshape),dim=c(k,m,1))
if(m<3){initdaplot<-abind::abind(initdaplot,array(rep(0,k*n),dim=c(k,1,1)),along=2)}
if(is.null(triang)==F){
adultsdaplotvis<-NULL
for(i in 1:nlevels(objptau$factorord)){
adultsdaplotvisi<-meshDist(plotsurf(adultsdaplot[,,i],triang,plot=F),plotsurf(initdaplot[,,1],triang,plot=F),to=tore,from=from,plot=F)
daagg<-objptau$space1$x[1:n,1:3][lastsfac(objptau$factorord),][i,]
adultsdaplotvisi<-translate3d(scalemesh(adultsdaplotvisi$colMesh,1/shapescale,center="none"),daagg[1],daagg[2],daagg[3])
adultsdaplotvis<-c(adultsdaplotvis,list(adultsdaplotvisi))
}
}
open3d()
for(i in 1:nlevels(objptau$factorord)){
lines3d(objptau$space1$x[1:n,1:3][as.numeric(objptau$factorord)==i,],col=i,add=T)
}
if(is.null(triang)==T){
babedaagg<-rep.row(objptau$space1$x[firstsfac(objptau$factorord),1:3][1,],k)
for(i in 1:nlevels(objptau$factorord)){
daplottarei<-adultsdaplot[,,i]
daagg<-rep.row(objptau$space1$x[1:n,1:3][lastsfac(objptau$factorord),][i,],k)
plot3D((daplottarei/shapescale)+daagg,col=i,add=T,size=1,bbox=F)
lineplot((daplottarei/shapescale)+daagg,links,col=i)
}
plot3D((initdaplot[,,1]/shapescale)+babedaagg,bbox=F,add=T)
lineplot((initdaplot[,,1]/shapescale)+babedaagg,links)
}else{
for(i in 1:nlevels(objptau$factorord)){
shade3d(adultsdaplotvis[[i]],add=T)
}
babedaagg<-rep.row(objptau$space1$x[firstsfac(objptau$factorord),1:3][1,],k)
shade3d(plotsurf((initdaplot[,,1]/shapescale)+babedaagg,triang,plot=F),add=T,alpha=0.5)
}
title3d("LS data in the PCA; first three PC scores")
decorate3d()
out<-list(ratesorig=ratesorig,ratestrasp=ratestrasp)
}
#' export
benfrombygroup<-function(locs,array,factor,doopa=T){
resu<-NULL
for(j in 1:nlevels(factor)){
for(k in 1:table(factor)[j]){
resui<-jbe(locs[,,j],array[,,as.numeric(factor)==j][,,k],doopa=doopa)
resu<-append(resu,resui)
print(paste(j,k,sep="_"))
}
}
resu
}
#' @export
plotancova<-function(y,x,group=NULL,pch=NULL,col=1,confint=T,cex=0.5,legend=T,labels=NULL,plot=T,xlab=NULL,ylab=NULL,xlim=range(x),ylim=range(y)){
if(is.null(group)==T){group<-factor(c(rep(1,length(y))))}else{pch=pch}
if(is.null(pch)==T){pch=19}else{pch=pch}
dati<-data.frame(group,as.numeric(group),col,pch)
if(is.null(xlab)==T){xlab<-c("x")}else{xlab<-xlab}
if(is.null(ylab)==T){ylab<-c("y")}else{ylab<-ylab}
if(plot==T){plot(x,y,xlim=xlim,ylim=ylim,col=col,pch=pch,cex=cex,xlab=xlab,ylab=ylab)}
if(!is.null(labels)){textxy(x,y,labels)}
lmlist<-NULL
for(i in 1:nlevels(group)){
lmi<-lm(y[as.numeric(group)==i]~x[as.numeric(group)==i])
lmlist<-c(lmlist,list(lmi))
}
names(lmlist)<-levels(group)
datapredinflist<-NULL
for(i in 1:nlevels(group)){
datapredinfi<-cbind(x[as.numeric(group)==i], predict(lmlist[[i]], interval="confidence")[,2])
datapredinfi<-datapredinfi[order(datapredinfi[,2]),]
datapredinflist<-c(datapredinflist,list(datapredinfi))
}
names(datapredinflist)<-levels(group)
datapredsuplist<-NULL
for(i in 1:nlevels(group)){
datapredsupi<-cbind(x[as.numeric(group)==i], predict(lmlist[[i]], interval="confidence")[,3])
datapredsupi<-datapredsupi[order(datapredsupi[,2]),]
datapredsuplist<-c(datapredsuplist,list(datapredsupi))
}
names(datapredsuplist)<-levels(group)
if(plot==T){
for(i in 1: length(lmlist)){
abline(lmlist[[i]],col=dati[as.numeric(group)==i,][1,3],ylim=ylim,xlim=xlim)
} }
if(plot==T){
if(confint==T){
for(i in 1: length(lmlist)){
if(anova(lmlist[[i]])$Pr[1]<0.05){
lines(datapredinflist[[i]],cex=0.1,lty = 'dashed',col=dati[as.numeric(group)==i,][1,3],ylim=ylim,xlim=xlim)
}}
for(i in 1: length(lmlist)){
if(anova(lmlist[[i]])$Pr[1]<0.05){
lines(datapredsuplist[[i]],cex=0.1,lty = 'dashed',col=dati[as.numeric(group)==i,][1,3],ylim=ylim,xlim=xlim)
}}
}}
if(legend==T){
x11()
plot(x,y,col="white")
legend(min(x),max(y),unique(group), cex=1, col=unique(col), pch=unique(pch),box.col="white")}
summarylist<-NULL
for(i in 1:length(lmlist)){
summarylisti<-summary(lmlist[[i]])
summarylist<-c(summarylist,list(summarylisti))
}
names(summarylist)<-levels(group)
sint_results<-NULL
for(i in 1:length(summarylist)){
inti<-summarylist[[i]]$coefficients[1,1]
p_inti<-summarylist[[i]]$coefficients[1,4]
betai<-summarylist[[i]]$coefficients[2,1]
p_betai<-summarylist[[i]]$coefficients[2,4]
r_sqi<-summarylist[[i]]$r.squared
sinti<-c(inti,p_inti,betai,p_betai,r_sqi)
sint_results<-rbind(sint_results,sinti)
}
rownames(sint_results)<-levels(group)
colnames(sint_results)<-c("Intercept","p-value Intercept","Beta","p-value Beta","R squared")
print(sint_results)
df<-data.frame(y=y,x=x,group=group)
model<-lm(y~x*group)
library(phia)
slopint<-testInteractions(model, pairwise="group", slope="x") ##### TESTA SLOPE
slopintmat<- matrix(NA, nlevels(spe), nlevels(spe))
slopintmat[lower.tri(slopintmat) ] <-round( slopint[1:(nrow(slopint)-1),5], 5)
slopintmat<-t(slopintmat)
colnames(slopintmat)<-levels(spe)
rownames(slopintmat)<-levels(spe)
slopintmat[lower.tri(slopintmat)]<-slopintmat[upper.tri(slopintmat)]
elevint<-testInteractions(lm(y~x+group))
elevintmat<- matrix(NA, nlevels(group), nlevels(group))
elevintmat[lower.tri(elevintmat) ] <-round( elevint[1:(nrow(elevint)-1),5], 5)
elevintmat<-t(elevintmat)
colnames(elevintmat)<-levels(group)
rownames(elevintmat)<-levels(group)
elevintmat[lower.tri(elevintmat)]<-elevintmat[upper.tri(elevintmat)]
out<-list(datapredsuplist=datapredsuplist,datapredinflist=datapredinflist,summarylist=summarylist,sint_results=sint_results,slopepval=slopintmat,elevpval=elevintmat)
return(out)
}
#' @export
heat3d<-function(source,target,triang,iter=3,linkss=NULL,linkst=NULL,plotlands=F,legend=T,cols=1,colt=2,plotsource=T,plottarget=T,collinkss=1,lwds=2,collinkst=2,lwdt=2,cexs=0.5,cext=0.5,colors=c("blue4","cyan2","yellow","red4"),alpha=1,ngrid=0,mag=1,graphics=T,to=NULL,from=NULL,scaleramp=F,lines=T){
mate<-source
mate2<-target
mate2<-mate+(mate2-mate)*mag
library(fields)
tes<-tessell3d(triang,mate,iter)
class(tes) <- "mesh3d"
matr<-mate
M<-t(tes$vb)[,1:3][-c(1:nrow(matr)),]
tes2<-tessell3d(triang,mate2,iter)
class(tes2) <- "mesh3d"
M2<-t(tes2$vb)[,1:3][-c(1:nrow(matr)),]
tpsgrid<-tpsgridpaolo(mate,mate2,linksTT=linkss,linksYY=linkss,graphics=F,ngrid=22)
#
# veclist<-NULL
# for(j in 1:nrow(M)){
# vecj<-NULL
# for(i in 1:nrow(matr)){
# vec1ji<--2*sqrt(abs(M[j,1]-matr[i,1]))
# vec2ji<--2*sqrt(abs(M[j,2]-matr[i,2]))
# vec3ji<--2*sqrt(abs(M[j,3]-matr[i,3]))
# vecji<-c(vec1ji,vec2ji,vec3ji)
# vecj<-rbind(vecj,vecji)
# }
# veclist<-c(veclist,list(vecj))
# }
#
veclist<-NULL
for(j in 1:nrow(M)){
vecj<-NULL
for(i in 1:nrow(matr)){
vec1ji<-2*(M[j,1]-matr[i,1])+2*(M[j,1]-matr[i,1])*log((M[j,1]-matr[i,1])^2+(M[j,2]-matr[i,2])^2)
vec2ji<-2*(M[j,2]-matr[i,2])+2*(M[j,2]-matr[i,2])*log((M[j,1]-matr[i,1])^2+(M[j,2]-matr[i,2])^2)
vec3ji<-2*(M[j,3]-matr[i,3])+2*(M[j,3]-matr[i,3])*log((M[j,1]-matr[i,1])^2+(M[j,2]-matr[i,2])^2)
vecji<-c(vec1ji,vec2ji,vec3ji)
vecj<-rbind(vecj,vecji)
}
veclist<-c(veclist,list(vecj))
}
jac<-NULL
for(i in 1: length(veclist)){
jaci<-t(tpsgrid$B)+t(tpsgrid$W)%*%veclist[[i]]
jac<-c(jac,list(jaci))
}
jac2<-list2array(jac)
mean11<-mean(jac2[1,1,])
mean12<-mean(jac2[1,2,])
mean13<-mean(jac2[1,3,])
mean21<-mean(jac2[2,1,])
mean22<-mean(jac2[2,2,])
mean23<-mean(jac2[2,3,])
mean31<-mean(jac2[3,1,])
mean32<-mean(jac2[3,2,])
mean33<-mean(jac2[3,3,])
detmean<-det(matrix(c(mean11,mean21,mean31,mean12,mean22,mean32,mean31,mean32,mean33),ncol=3))
myj<-unlist(lapply(jac,det))
obs<-log2(myj/detmean)
fit<- Tps(M, obs)
obs2<-predict(fit,M2)
obs3<-c(obs2)
obs3[is.na(obs3)]<-mean(obs3,na.rm=T)
obm<-meshDist(plotsurf(rbind(mate2,M2),tes2$it,plot=F),distv=obs3,add=T,rampcolors =colors,to=to,from=from,scaleramp=scaleramp,plot=F,alpha=alpha)
if(graphics==T){
if(plotlands==T){deformGrid3d(mate,mate2,ngrid=ngrid,lines=lines,col1=cols,col2=colt)}
shade3d(obm$colMesh,alpha=alpha)
if(!is.null(linkst)){lineplot(mate2,linkst,col=collinkst,lwd=lwds)}
if(plotsource==T){
shade3d(plotsurf(source,t(triang),plot=F),alpha=0.5)
if(!is.null(linkss)){lineplot(mate,linkss,col=collinkss,lwd=lwdt)}}
}
out<-list(mate=mate,mate2=mate2,centros=M,jacs=jac,detjac=myj,detmean=detmean,obs=obs,obs2=obs2,obs3=obs3,fit=fit,cols=makeTransparent(colorRampPalette(colors)(n = length(obs3)),alpha=alpha),tes=tes,obm=obm,sourcem=plotsurf(source,t(triang),plot=F))
out
}
#' @export
plotsurf<-function(lmatrix,triang,col=1,alpha=0.5,plot=T){
thesurf_1=t(cbind(lmatrix,1))
triangolazioni=triang
thesurf=list(vb=thesurf_1,it=triangolazioni)
class(thesurf) <- "mesh3d"
if(plot==T){shade3d(thesurf,col=col,alpha=alpha)}
return(thesurf)
}
#' @export
tessell3d=function(tri,ver,iter){
tri_t=tri
ver_t=ver
for(j in 1:iter){
nrows=nrow(tri_t)
numb=range(tri_t)[2]
for(i in 1:nrows){
tri_i=ver_t[tri_t[i,],]
cen_i=colMeans(tri_i)
tri_1=c(tri_t[i,c(1,2)],numb+i)
tri_2=c(tri_t[i,1],numb+i,tri_t[i,3])
tri_3=c(tri_t[i,c(2,3)],numb+i)
tri_t=rbind(tri_t,tri_1,tri_2,tri_3)
ver_t=rbind(ver_t,cen_i)
}}
vertici_out=cbind(ver_t,1)
rownames(vertici_out)=NULL
triangoli_out=tri_t[(dim(tri)[1]+1):dim(tri_t)[1],]
rownames(triangoli_out)=NULL
mesh.out=list(vb=t(vertici_out),it=t(triangoli_out))
}
#' @export
plotdefo3d<-function(procsymobject,triang=NULL,links=NULL,collinks=1,lwd=1,axtit=NULL,mags=rep(1,3),heat=F,scaleramp=F,heateuc=F,sign=T,colors=c("blue4","cyan2","yellow","red4"),alpha=1,from=NULL,to=NULL,out=F,plot=T){
if(is.null(axtit)==T){axtit=c("PC1+","PC2+","PC3+","PC1-","PC2-","PC3-")}else{axtit=axtit}
texts<-axtit
if(!is.null(triang)==T&&ncol(triang)>3){stop("I want triangles matrix in the form nx3")}
mshape<-procsymobject$mshape
pc1pos<-showPC(max(procsymobject$PCscores[,1])*mags[1],procsymobject$PCs[,1],procsymobject$mshape)
pc1neg<-showPC(min(procsymobject$PCscores[,1])*mags[1],procsymobject$PCs[,1],procsymobject$mshape)
pc2pos<-showPC(max(procsymobject$PCscores[,2])*mags[2],procsymobject$PCs[,2],procsymobject$mshape)
pc2neg<-showPC(min(procsymobject$PCscores[,2])*mags[2],procsymobject$PCs[,2],procsymobject$mshape)
pc3pos<-showPC(max(procsymobject$PCscores[,3])*mags[3],procsymobject$PCs[,3],procsymobject$mshape)
pc3neg<-showPC(min(procsymobject$PCscores[,3])*mags[3],procsymobject$PCs[,3],procsymobject$mshape)
if(heat==F&heateuc==F){
allshapes<-rbind(pc1pos,pc1neg,pc2pos,pc2neg,pc3pos,pc3neg)
allshapes<-matrix2arrayasis(allshapes,nrow(pc1pos))
css<-apply(allshapes,3,cSize)
themax<-allshapes[,,which.max(css)]
if(plot==T){
open3d(windowRect=c(100,100,1000,1000))
mat <- matrix(1:12, ncol=2)
layout3d(mat, height = rep(c(3,1), 3), model = "inherit")
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(pc1pos,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links)==F){lineplot(pc1pos,links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[1])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(pc2pos,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links)==F){lineplot(pc2pos,links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[2])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(pc3pos,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links)==F){lineplot(pc3pos,links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[3])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(pc1neg,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links)==F){lineplot(pc1neg,links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[4])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(pc2neg,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links)==F){lineplot(pc2neg,links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[5])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
plot3d(pc3neg,bbox=F,type="s",asp=F,axes=F,box=F,size=0.6,xlab = "", ylab = "", zlab = "",add=T)
if(is.null(links)==F){lineplot(pc3neg,links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[6])}
}
if (heat==T){
myh1pos<-heat3d(pc1pos,mshape,triang,lines=F,linkss=links,graphics=F,from=from,to=to,colors=colors,alpha=alpha,scaleramp=scaleramp)
myh1neg<-heat3d(pc1neg,mshape,triang,lines=F,linkss=links,graphics=F,from=from,to=to,colors=colors,alpha=alpha,scaleramp=scaleramp)
myh2pos<-heat3d(pc2pos,mshape,triang,lines=F,linkss=links,graphics=F,from=from,to=to,colors=colors,alpha=alpha,scaleramp=scaleramp)
myh2neg<-heat3d(pc2neg,mshape,triang,lines=F,linkss=links,graphics=F,from=from,to=to,colors=colors,alpha=alpha,scaleramp=scaleramp)
myh3pos<-heat3d(pc3pos,mshape,triang,lines=F,linkss=links,graphics=F,from=from,to=to,colors=colors,alpha=alpha,scaleramp=scaleramp)
myh3neg<-heat3d(pc3neg,mshape,triang,lines=F,linkss=links,graphics=F,from=from,to=to,colors=colors,alpha=alpha,scaleramp=scaleramp)
}
if (heateuc==T){
myh1pos<-diffonmesh(mshape,pc1pos,t(triang),graph=F,from=from,to=to,rampcolors=colors,alphas=c(alpha,0.7),sign=sign)
myh1neg<-diffonmesh(mshape,pc1neg,t(triang),graph=F,from=from,to=to,rampcolors=colors,alphas=c(alpha,0.7),sign=sign)
myh2pos<-diffonmesh(mshape,pc2pos,t(triang),graph=F,from=from,to=to,rampcolors=colors,alphas=c(alpha,0.7),sign=sign)
myh2neg<-diffonmesh(mshape,pc2neg,t(triang),graph=F,from=from,to=to,rampcolors=colors,alphas=c(alpha,0.7),sign=sign)
myh3pos<-diffonmesh(mshape,pc3pos,t(triang),graph=F,from=from,to=to,rampcolors=colors,alphas=c(alpha,0.7),sign=sign)
myh3neg<-diffonmesh(mshape,pc3neg,t(triang),graph=F,from=from,to=to,rampcolors=colors,alphas=c(alpha,0.7),sign=sign)
}
allshapes<-rbind(t(myh1pos$obm$colMesh$vb[-4,]),t(myh1neg$obm$colMesh$vb[-4,]),t(myh2pos$obm$colMesh$vb[-4,]),t(myh2neg$obm$colMesh$vb[-4,]),t(myh3pos$obm$colMesh$vb[-4,]),t(myh3neg$obm$colMesh$vb[-4,]))
allshapes<-matrix2arrayasis(allshapes,nrow(t(myh1pos$obm$colMesh$vb[-4,])))
css<-apply(allshapes,3,cSize)
themax<-allshapes[,,which.max(css)]
if(heat==T|heateuc==T){
if(plot==T){
open3d(windowRect=c(100,100,1000,1000))
mat <- matrix(1:12, ncol=2)
layout3d(mat, height = rep(c(3,1), 3), model = "inherit")
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
shade3d(myh1pos$obm$colMesh,alpha=alpha)
if(is.null(links)==F){lineplot(t(myh1pos$obm$colMesh$vb[-4,]),links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[1])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
shade3d(myh2pos$obm$colMesh,alpha=alpha)
if(is.null(links)==F){lineplot(t(myh2pos$obm$colMesh$vb[-4,]),links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[2])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
shade3d(myh3pos$obm$colMesh,alpha=alpha)
if(is.null(links)==F){lineplot(t(myh3pos$obm$colMesh$vb[-4,]),links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[3])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
shade3d(myh1neg$obm$colMesh,alpha=alpha)
if(is.null(links)==F){lineplot(t(myh1neg$obm$colMesh$vb[-4,]),links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[4])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
shade3d(myh2neg$obm$colMesh,alpha=alpha)
if(is.null(links)==F){lineplot(t(myh2neg$obm$colMesh$vb[-4,]),links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[5])
next3d()
plot3d(themax*1.2,box=F,axes=F,col="white",xlab="",ylab="",zlab="",type="s",size=0,aspect=F)
shade3d(myh3neg$obm$colMesh,alpha=alpha)
if(is.null(links)==F){lineplot(t(myh3neg$obm$colMesh$vb[-4,]),links,col=collinks,lwd=lwd)}
next3d()
text3d(0,0,0, texts[6])}
}
dimnames(allshapes)[[3]]<-c("pc1pos","pc1neg","pc2pos","pc2neg","pc3pos","pc3neg")
if(out==T){
if(heat==T){outp<-list(pc1pos=myh1pos$obm$colMesh,pc1neg=myh1neg$obm$colMesh,pc2pos=myh2pos$obm$colMesh,pc2neg=myh2neg$obm$colMesh,pc3pos=myh3pos$obm$colMesh,pc3neg=myh3neg$obm$colMesh)}else{outp<-allshapes}
}else{outp<-NULL}
outp
}
#' @export
conslinks<-function(number,open=T){
k=seq(1:(number-1))
aw=NULL
for(i in k){
b=list(c(i,i+1))
aw<-c(aw,b)
}
if(open==T){return(aw)}else{
aw<-c(aw,list(c(1,number)))
}
aw
}
#' @export
list2array<-function(mylist){
require(abind)
final<-NULL
for(i in 1:length(mylist)){
temp<-array(mylist[[i]],dim=c(nrow(mylist[[i]]),ncol(mylist[[i]]),1))
final<-abind::abind(final,temp)
}
return(final)
}
#' @export
serpred<-function(dep,indep,polyn=1,length.out=10){
sizes<-seq(min(indep),max(indep),length.out=length.out)
sizesvetts<-NULL
thelm<-lm(dep~poly(indep,degree=polyn,raw=TRUE))
for(i in 1:length(sizes)){
if(polyn==1){sizesvettsi<-c(1,sizes[i])}else{sizesvettsi<-c(1,poly(c(sizes[i]),degree=polyn,raw=T))}
sizesvetts<-rbind(sizesvetts,sizesvettsi)}
thepredicts<-NULL
for(j in 1:nrow(sizesvetts)){
thepredictsj<-c(crossprod(coef(thelm),sizesvetts[j,]))
thepredicts<-rbind(thepredicts,thepredictsj)
}
thepredicts
}
#' @export
plot2dhull<-function(matrix,group,scalevariable=1,asp=1,extl=F,legend=T,xl=NULL,yl=NULL,posl=c("topright"),labels=NULL,clabel=0,pch=19,lwd=0.5,colhull=NULL,col=as.numeric(group),xlab=NULL,ylab=NULL,grey=F,xlimi=range(matrix[,1])*1.3,ylimi=range(matrix[,2])*1.3,reorder=T,alpha=rep(0,nlevels(group))){
library(MASS)
library(compositions)
library(spatstat)
library(gdata)
library(TeachingDemos)
library(ade4)
library(calibrate)
if (!is.factor(group)) stop("'group' must be a factor")
makeTransparent = function(..., alpha=0.5) {
if(alpha<0 | alpha>1) stop("alpha must be between 0 and 1")
alpha = floor(255*alpha)
newColor = col2rgb(col=unlist(list(...)), alpha=FALSE)
.makeTransparent = function(col, alpha) {
rgb(red=col[1], green=col[2], blue=col[3], alpha=alpha, maxColorValue=255)
}
newColor = apply(newColor, 2, .makeTransparent, alpha=alpha)
return(newColor)
}
x<-matrix[,1]
y<-matrix[,2]
if(reorder==T){group<-factor(group,levels=unique(group))}
species<-as.numeric(group)
col=col
if(grey==T){col=col2grey(col)}
coli<-data.frame(group,as.numeric(group),col,pch)
if(is.null(colhull)){colhull=aggregate(coli[,-1],by=list(coli[,1]),mean)[,-3][,2]}else{colhull=colhull}
colim<-cbind(aggregate(coli[,-1],by=list(coli[,1]),mean)[,-c(3,4)],colhull)
plot(x,y,type="p",cex=scalevariable,col=as.character(coli[,3]),pch=pch,xlim=xlimi,ylim=ylimi,xlab=xlab,ylab=ylab,asp=asp)
if(!is.null(labels)){textxy(x,y,labels)}else{NULL}
for(i in 1:(max(species)))
{
abline(h=0,v=0)
if(length(x[species==i])<3){NULL}else{
hulli<-convexhull.xy(subset(cbind(x,y),species==i))
par(new=T)
plot(hulli,col=makeTransparent(colim[,3][i], 1,alpha=alpha[i]),lwd=lwd,lty=i,add=T,asp=asp)
par(new=T)
daplotx<-c(hulli$bdry[[1]][[1]][length(hulli$bdry[[1]][[1]])],hulli$bdry[[1]][[1]])
daploty<-c(hulli$bdry[[1]][[2]][length(hulli$bdry[[1]][[2]])],hulli$bdry[[1]][[2]])
par(new=T)
plot(daplotx,daploty,lwd=lwd,type="l",lty=i,col=colim[,3][i],xlim=xlimi,ylim=ylimi,axes=F,xlab="",ylab="",asp=asp)
}
}
opar <- par(mar = par("mar"))
par(mar = c(0.1, 0.1, 0.1, 0.1))
on.exit(par(opar))
meansx<-aggregate(matrix[,1],by=list(group),FUN=mean)
meansy<-aggregate(matrix[,2],by=list(group),FUN=mean)
if (clabel > 0)
for(i in 1:nlevels(group)){ scatterutil.eti(meansx[i,-1],meansy[i,-1], meansx[,1][i], clabel,coul=1)}
if(legend==T){
if(extl==T){
x11()
plot(x,y,col="white")
legend(min(x),max(y),unique(coli[,1]), cex=1, col=unique(coli[,3]), pch=unique(coli[,4]),box.col="white")
}else{
if(is.null(xl)==T&is.null(yl)==T){
legend(posl,legend=unique(coli[,1]), col=unique(coli[,3]), pch=unique(coli[,4]),bty='n')}else{
legend(xl,yl,unique(coli[,1]),col=unique(coli[,3]),pch=unique(coli[,4]),bty='n')}
}
}
}
#' @export
reparray<-function(array,n,type=c("sequ","block")){
if(is.null(dimnames(array)[3])){dimnames(array)[3]<-list(c(1:dim(array)[3]))}else{dimnames(array)[3]<-dimnames(array)[3]}
require(abind)
myarray2<-NULL
steps<-n
if(type=="sequ"){
for(i in 1:dim(array)[3]){
temp1<-rep(list(array(array[,,i],dim=c(dim(array)[1],dim(array)[2],1))),steps)
temp2<-list2array(temp1)
myarray2<-abind::abind(myarray2,temp2)
}
return(myarray2)}else{NULL}
if(type=="block"){
temp1<-list2matrix(rep(array2list(array),n))
temp2<-matrix2arrayasis(temp1,dim(array)[1])
return(temp2)
}else{NULL}
}
#' @export
pt2dvaruno<-function(mua,mub,va,doopa=T,sss=T,tol=0.001){
library(shapes)
library(matrixcalc)
if(doopa==T){
theopamuamub<-procOPA(mub,mua,scale=F,reflect=F)
mua<-theopamuamub$Bhat
rotmua<-theopamuamub$R
if(rotmua[1,1]+1<tol){mua<--mua}
if(sss==F){
va<-va-((matrix.trace(t(mua)%*%va)/matrix.trace(t(mua)%*%mua))*mua)
}
theopavamua<-procOPA(mua,va,scale=F)
va<-theopavamua$Bhat
rotva<-theopavamua$R
if(rotva[1,1]+1<tol){va<--va}
}else{
if(sss==F){
va<-va-((matrix.trace(t(mua)%*%va)/matrix.trace(t(mua)%*%mua))*mua)
}
rotmua<-NULL
rotva<-NULL
}
muaz <- complex(real = mua[,1], imaginary = mua[,2])
mubz <- complex(real = mub[,1], imaginary = mub[,2])
vaz <- complex(real = va[,1], imaginary = va[,2])
muazbarra<-muaz/(sqrt(muaz%*%(Conj(muaz))))
mubzbarra<-mubz/(sqrt(mubz%*%(Conj(mubz))))
if(sss==T){
vbz<-vaz-1i*((Im(Conj(mubzbarra)%*%vaz))/(1+Conj(muazbarra)%*%mubzbarra))*(muazbarra+mubzbarra)}else{
vbz<-vaz-1i*((Im(Conj(mubzbarra)%*%vaz))/(1+Conj(muazbarra)%*%mubzbarra))*(muazbarra+mubzbarra)-((Re(Conj(mubzbarra)%*%vaz))/(1+Conj(muazbarra)%*%mubzbarra))*(muazbarra+mubzbarra)}
vazbarra<-vaz/(sqrt(vaz%*%(Conj(vaz))))
eps<-Re(sqrt(2*Im(Conj(mubzbarra)%*%vazbarra)^2/(1+Conj(muazbarra)%*%mubzbarra)))
eps2<-Re(sqrt(2*Mod(Conj(mubzbarra)%*%vazbarra)^2/(1+Conj(muazbarra)%*%mubzbarra)))
vb<-cbind(Re(vbz),Im(vbz))
out<-list(vb=vb,rotmua=rotmua,rotva=rotva,eps=eps,eps2=eps2)
return(out)
}
#' @export
opaloop<-function(GM,array,scale=F,reflect=F){
library(abind)
k<-dim(array)[1]
m<-dim(array)[2]
n<-dim(array)[3]
looped<-NULL
rots<-NULL
for(i in 1:n){
opai<-procOPA(GM,array[,,i],scale=scale,reflect=reflect)
loopedi<-array(opai$Bhat,dim=c(k,m,1))
looped<-abind::abind(looped,loopedi)
rotsi<-opai$R
rots<-c(rots,list(rotsi))
}
out<-list(looped=looped,rots=rots)
out
}
#' @export
diffonmesh<-function(lmsource,lmtarget,triang,colsource=1,alphas=c(0.7,0.3),grid=F,aff=F,nonaff=F,distscale=1, scaleramp=F,from = NULL,to = NULL,tol=NULL,sign=F,title=T,displace = FALSE,plotsource=T, steps = 20,rampcolors = colorRamps::blue2green2red(steps - 1),graph=T){
for ( i in c("Morpho","Rvcg","rgl")) {
if (!require(i,character.only = TRUE))
stop(paste0("please install package ",i))
}
lmsource <- rotonto(lmtarget,lmsource)$yrot
thetarget <- t(cbind(lmtarget,1))
thesource <- t(cbind(lmsource,1))
getPlotNr <- length(which(c(aff,nonaff,grid) == TRUE))+1
layout(matrix(1:getPlotNr,1,getPlotNr,byrow = T))
triangolazioni <- triang
thetarget_mesh <- list(vb=thetarget,it=triangolazioni)
class(thetarget_mesh) <- "mesh3d"
class(thetarget_mesh) <- "mesh3d"
thesource_mesh<-list(vb=thesource,it=triangolazioni)
class(thesource_mesh) <- "mesh3d"
class(thesource_mesh) <- "mesh3d"
if(grid==T){
shade3d(thetarget_mesh)
###between pointclouds
distvec <- sqrt(rowSums((lmsource-lmtarget)^2))/distscale
if(graph==T){
them<-meshDist(lmtarget,distvec = distvec,from=from,to=to,tol=tol,sign=sign,steps = 20,rampcolors =rampcolors,scaleramp=scaleramp)
}else{
them<-meshDist(lmtarget,distvec = distvec,from=from,to=to,tol=tol,sign=sign,steps = 20,rampcolors =rampcolors,shade=F,scaleramp=scaleramp)
}
##if you want add a deformed cube
if(graph==T){
deformGrid3d(lmsource,lmtarget,type="p",size=10,ngrid = 5,add=T)
title("Distance between point-clouds")}
}
### between surfaces
thetarget_warped <- tps3d(thesource_mesh,lmsource,lmtarget,lambda = 1e-8)
distvec2 <- sqrt(rowSums((vert2points(thesource_mesh)-vert2points(thetarget_warped))^2))/distscale
if(graph==T){
if(plotsource==T){shade3d(thesource_mesh,col=colsource,alpha=alphas[2])}
them<-meshDist(thetarget_mesh,thesource_mesh,distvec=distvec2,alpha=alphas[1],add=T,from=from,to=to,tol=tol,scaleramp=scaleramp,sign=sign,displace=displace,steps = 20,rampcolors =rampcolors)
if(title==T){title3d("total")
title("total")}
}else{
them<-meshDist(thetarget_mesh,distvec=distvec2,alpha=alphas[1],add=T,from=from,to=to,tol=tol,scaleramp=scaleramp,sign=sign,displace=displace,steps = 20,rampcolors =rampcolors,shade=F)
}
if (nonaff || aff) {
affinetrafo <- computeTransform(vert2points(thetarget_mesh),vert2points(thesource_mesh),type="a")
affineshort <- applyTransform(thesource_mesh,affinetrafo)
if(nonaff) {### visualize non-affine deform between surfaces
##create affine transfrom to longnose.mesh to remove affine differences and calculate distance from affine transform to target
distvec3 <- sqrt(rowSums((vert2points(affineshort)-vert2points(thetarget_warped))^2))/distscale
if(graph==T){
open3d()
shade3d(thetarget_mesh,col=1,alpha=alphas[2])
themna<-meshDist(thesource_mesh,distvec=distvec3,add=T,from=from,to=to,tol=tol,scaleramp=scaleramp,sign=sign,displace=displace,steps = 20,rampcolors =rampcolors)
if(title==T){title3d("non affine")
title("non-affine")}
}else{
themna<-meshDist(thesource_mesh,distvec=distvec3,add=T,from=from,to=to,tol=tol,scaleramp=scaleramp,sign=sign,displace=displace,steps = 20,rampcolors =rampcolors,shade=F)
}
}
if(aff) {### the affine transform looks like that:
distaffnonaffon4<-sqrt(rowSums((vert2points(affineshort)-vert2points(thesource_mesh))^2))/distscale
if(graph==T){
open3d()
shade3d(thetarget_mesh,col=1,alpha=alphas[2])
thema<-meshDist(thesource_mesh,distvec=distaffnonaffon4,add=T,from=from,to=to,tol=tol,scaleramp=scaleramp,sign=sign,displace=displace,steps = 20,rampcolors =rampcolors)
if(title==T){title3d("affine")
title("affine")}
}else{
thema<-meshDist(thesource_mesh,distvec=distaffnonaffon4,add=T,from=from,to=to,tol=tol,scaleramp=scaleramp,sign=sign,displace=displace,steps = 20,rampcolors =rampcolors,shade=F)
}
}
}else{themna<-NULL
thema<-NULL
}
out<-list(obm=them,themna=themna,thema=thema)
}
#' @export
mycca<-function(x,y,pch=19,col=1,group=NULL,labels=NULL,extl=F,legend=T,xl=NULL,yl=NULL,posl=c("topright"),cex=1,xlab=NULL,ylab=NULL,asp=NULL){
require(CCA)
require(vegan)
require(calibrate)
myrda<-vegan::rda(y~x)
rsqadj<-RsquareAdj(myrda)
print(rsqadj)
anovarda<-anova(myrda,step=2000)
print(anovarda)
if(is.null(xlab)==T){xlab="Independent"}else{xlab=xlab}
if(is.null(ylab)==T){ylab="Dependent"}else{ylab=ylab}
if (!is.null(group)){
col=col
species<-as.numeric(group)
coli<-data.frame(group,as.numeric(group),col,pch)
colim<-aggregate(coli[,-1],by=list(coli[,1]),mean)}else{
coli<-data.frame(1,1,col,pch)
colim<-aggregate(coli[,-1],by=list(coli[,1]),mean)
}
thecca<-rcc(as.matrix(x),as.matrix(y),0.1,0.1)
if(is.null(group)==T){plot(x,rcc(as.matrix(x),as.matrix(y),0.1,0.1)$scores$yscores[,1],col=col,pch=pch,cex=cex,xlab=xlab,ylab=ylab)}
if (!is.null(group)){
plot2dhull(cbind(x,thecca$scores$yscores[,1]),group,scalevariable=cex,pch=pch,col=col,colhull=colim[,3],clabel=0,legend=F,reorder=F,xlimi=range(x),ylimi=range(thecca$scores$yscores[,1]),asp=asp,xlab=xlab,ylab=ylab)
}
if (!is.null(labels)){textxy(x,thecca$scores$yscores,labels)}
if(legend==T){
if(extl==T){
x11()
plot(x,y,col="white")
legend(min(x),max(y),colim[,1], cex=1, col=colim[,3], pch=colim[,4],box.col="white")
}else{
if(is.null(xl)==T&is.null(yl)==T){
legend(posl,legend=colim[,1], cex=1, col=colim[,3], pch=colim[,4],bty='n')}else{
legend(xl,yl,colim[,1], cex=1, col=colim[,3], pch=colim[,4],bty='n')}
}
}
if (!is.null(group)){
if(dim(as.matrix(y))[2]>1){bygroup<-manymultgr(y,x,group)}else{
bygroup<-plotancova(y,x,group,legend=F,plot=F)$sint_results}
}else{bygroup=c("no group structure")}
out<-list(xscores=thecca$scores$xscores,yscores=thecca$scores$yscores,AdjRsq=rsqadj,anovarda=anovarda,bygroup=bygroup)
return(out)
}
#' @export
posfac<-function(factor){
positions<-NULL
for(k in 1:max(as.numeric(factor))){
factor<-factor(factor,levels=unique(factor))
positioni<-which(as.numeric(factor)==k)
positions<-c(positions,list(positioni))
}
names(positions)<-levels(factor)
sequ<-NULL
for(i in 1:max(length(positions))){
seqi<-c(1:length(positions[[i]]))
sequ<-c(sequ,list(seqi))
}
pure<-rep(NA,length(unlist(positions)))
for(j in 1:max(length(positions))){
pure<-replace(pure,positions[[j]],c(sequ[[j]]))
}
pure}
#' @export
areasip<-function(matrix,links=NULL,PB=NA,PA=NA,S=NA,SB=NA,H=NA,V=3,a=NULL,q=NULL,Y=FALSE,j=FALSE,D=FALSE,St=Inf,Q=TRUE,graph=T,extpol=F){
if(!is.null(links)){warning("Links **must** identify, among other structures, a closed contour")}
library(geometry)
library(tripack)
library(geoR)
library(gstat)
library(sp)
library(fields)
library(RTriangle)
mate<-matrix
if(!is.null(links)&is.na(S)==T){S<-list2matrix(links)}
if(extpol==T){
step1<-pslg(mate,S=S,PB=PA,PA=PA,SB=SB,H=NA)
posimpnoh<-RTriangle::triangulate(step1,V=V,a=NULL,S=St,q=q,Y=Y,j=j,D=D,Q=Q)
step2<-matrix[unique(posimpnoh$E[ posimpnoh$EB%in%c(1)]),]
maulinks<-posimpnoh$E[posimpnoh$EB%in%c(1),]
newmaulinks<-maulinks
newmaulinks[,1]<-c(1:nrow(maulinks))
newmaulinks[,2]<-match(maulinks[,2],maulinks[,1])
cycles2 <- function(links) {
require(ggm)
if (any(is.na(links))) stop("missing value/s in links")
mat <- matrix(0L, max(links), max(links))
mat[links] <- 1
lapply(ggm::fundCycles(mat), function(xa) rev(xa[ , 1L]))
}
mypol<-step2[cycles2(newmaulinks)[[1]],]}else{mypol<-c("you do not want external polygon")}
p<-pslg(mate,PB=PB,PA=PA,S=S,SB=SB,H=H)
au<-RTriangle::triangulate(p,V=1,a=a,q=q,Y=Y,j=j,D=D,S=St,Q=Q)
if(graph==T){
plot(au,asp=1)
lineplot(mate,links,col=3)
points(au$P,pch=19)
points(mate,pch=21,cex=2)
}
centros<-NULL
areas<-NULL
for(i in 1:nrow(au$T)){
centrosi<-apply(au$P[au$T[i,],],2,mean)
centros<-rbind(centros,centrosi)
areasi<-convhulln(au$P[au$T[i,],],option="FA")$vol
areas<-c(areas,areasi)
}
if(graph==T){points(centros,col=2)}
M<-centros
thecentr<-centroids(mate)
dasomm<-NULL
for(i in 1:nrow(M)){
dasommi<-dist(rbind(thecentr,M[i,]))^2*areas[i]
dasomm<-c(dasomm,dasommi)
}
ip<-sum(dasomm)
are<-sum(areas)
deltri<-au$T
ptri<-au$P
origcentros<-rbind(mate,M)
out<-list(area=are,areas=areas,ip=ip,centros=centros,deltri=deltri,ptri=ptri,origcentros=origcentros,triangob=au,ext=mypol)
out
}
#' @export
array2list<-function(array){
thelist<-NULL
for(i in 1:dim(array)[3]){
eli<-array[,,i]
thelist<-c(thelist,list(eli))
}
if(is.null(dimnames(array)[[3]])==F){names(thelist)<-dimnames(array)[[3]]}
return(thelist)
}
#' @export
array2mat<-function(array,inds,vars){
if(class(array)=="matrix"){array<-array(array,dim=c(nrow(array),ncol(array),1))}
X1 <-aperm(array,c(3,2,1))
dim(X1)<- c(inds, vars)
if(!is.null(dimnames(array)[3])){rownames(X1)<-unlist(dimnames(array)[3])}else{rownames(X1)<-c(1:nrow(X1))}
return(X1)
}
#' @export
biharm.new<-function(vec1,vec2){
dim<-length(vec1)
n <- sqrt(sum((vec1-vec2)^2))
if(dim<3){
n^2*log(n^2)}else{
-n
}
}
#' @export
centershapes<-function(array){
if(is.matrix(array)==T){array<-array(array,dim=c(nrow(array),ncol(array),1))}
centros<-centroids(array)
k<-dim(array)[1]
m<-dim(array)[2]
n<-dim(array)[3]
prov<-array(rep(t(centros),each=k),dim=c(k,m,n))
array2<-array-prov
return(array2)
}
#' @export
centroids<-function(array){
meanmat<-function(mat){
mean<-apply(mat,2,mean)
mean
}
if(class(array)=="matrix"){array<-array(array,dim=c(dim(array)[1],dim(array)[2],1))}
centroidi<-t(apply(array,3,meanmat))
return(centroidi)
}
#' @export
firstsfac<-function(group){
firstsres<-NULL
for (i in levels(group)){
firstresi<-min(which(group==i))
firstsres<-rbind(firstsres,firstresi)
}
return(firstsres)
}
#' @export
heat2d<-function(init,fin,invc=F,constr=T,sen=F,logsen=T,nadd=5000,linkss=NULL,zlim=NULL,legend=T,plottarget=T,ext=0.1,collinkss=1,lwds=2,collinkst=2,lwdt=2,pchs=19,pcht=19,cexs=0.5,cext=0.5,colors=c("blue4","cyan2","yellow","red4"),alpha=1,ngrid=30,oma=c(5,5,5,5),mai=c(3,3,3,3),mar=c(3,3,3,3),mag=1,tol=0.1,graphics=T,PB=NA,PA=NA,S=NA,SB=NA,H=NA,V=3,a=NULL,q=NULL,Y=FALSE,j=FALSE,D=FALSE,St=Inf,Q=TRUE,pholes=NA){
library(shapes)
library(Morpho)
library(matrixcalc)
library(geometry)
library(tripack)
library(geoR)
library(gstat)
library(sp)
library(fields)
library(RTriangle)
library(sp)
library(alphahull)
library(ggm)
if(!is.na(H)&is.na(pholes)==T){stop("If you specify 'H' you need to specify 'pholes' also")}
if(!is.na(pholes)&is.null(linkss)==T){stop("If you specify 'H' and 'pholes' you need to specify 'linkss' also")}
mate<-fin
mate2<-init
fin<-init+(fin-init)*mag
if(!is.null(linkss)&is.na(S)==T){S<-list2matrix(linkss)}
posimpfin<-areasip(fin,S=S,PB=PA,PA=PA,SB=SB,H=H,V=V,a=NULL,q=q,Y=Y,j=j,D=D,St=St,Q=Q,graph=F,extpol=F)
posimp<-areasip(init,S=S,PB=PA,PA=PA,SB=SB,H=H,V=V,a=NULL,q=q,Y=Y,j=j,D=D,St=St,Q=Q,graph=F,extpol=F)
pofin<-areasip(fin,S=S,PB=PA,PA=PA,SB=SB,H=H,V=V,a=a,q=q,Y=Y,j=j,D=D,St=St,Q=Q,graph=F,extpol=F)
po<-areasip(init,S=S,PB=PA,PA=PA,SB=SB,H=H,V=V,a=a,q=q,Y=Y,j=j,D=D,St=St,Q=Q,graph=F,extpol=F)
posimpnohfin<-areasip(fin,S=S,PB=PA,PA=PA,SB=SB,H=NA,V=V,a=NULL,q=q,Y=Y,j=j,D=D,St=St,Q=Q,graph=F,extpol=F)
posimpnoh<-areasip(init,S=S,PB=PA,PA=PA,SB=SB,H=NA,V=V,a=NULL,q=q,Y=Y,j=j,D=D,St=St,Q=Q,graph=F,extpol=F)
matr<-init
M<-po$centros
areas<-po$areas
tpsgrid<-tpsgridpaolo(init,fin,linksTT=linkss,linksYY=linkss,axes2d=T,ext=ext,graphics=F,ngrid=ngrid)
veclist<-NULL
for(j in 1:nrow(M)){
vecj<-NULL
for(i in 1:nrow(matr)){
vec1ji<-2*(M[j,1]-matr[i,1])+2*(M[j,1]-matr[i,1])*log((M[j,1]-matr[i,1])^2+(M[j,2]-matr[i,2])^2)
vec2ji<-2*(M[j,2]-matr[i,2])+2*(M[j,2]-matr[i,2])*log((M[j,1]-matr[i,1])^2+(M[j,2]-matr[i,2])^2)
vecji<-c(vec1ji,vec2ji)
vecj<-rbind(vecj,vecji)
}
veclist<-c(veclist,list(vecj))
}
jac<-NULL
for(i in 1: length(veclist)){
jaci<-t(tpsgrid$B)+t(tpsgrid$W)%*%veclist[[i]]
jac<-c(jac,list(jaci))
}
deltus<-NULL
dpl<-NULL
sens<-NULL
for(i in 1:length(jac)){
deltusi<-jac[[i]]-diag(nrow(jac[[i]]))
dpli<-0.5*(deltusi+t(deltusi))
seni<-0.5*matrix.trace(t(dpli)%*%dpli)
deltus<-c(deltus,list(deltusi))
dpl<-c(dpl,list(dpli))
sens<-c(sens,seni)
}
lsens<-log2(sens)
sens2<-sens*areas
jac2<-list2array(jac)
mean11<-mean(jac2[1,1,])
mean12<-mean(jac2[1,2,])
mean21<-mean(jac2[2,1,])
mean22<-mean(jac2[2,2,])
detmean<-det(matrix(c(mean11,mean21,mean12,mean22),ncol=2))
myj<-unlist(lapply(jac,det))
if(sen==F){obs<-log2(myj/detmean)}else{
if(logsen==T){obs=lsens}else{obs=sens}
}
fit<- Tps(M, obs)
summary(fit)
if(constr==F){
hull <- chull(fin)
indx=hull
if(invc==F){points <- fin[indx,]}else{points <- init[indx,]}
points <- rbind(points,points[1,])
sfe1<-spsample(Polygon(points),nadd,type="regular")
sr1<-sfe1@coords}else{
if(invc==F){mau<-fin[unique(posimpnoh$triangob$E[posimpnoh$triangob$EB%in%c(1)]),]}else{mau<-init[unique(posimpnoh$triangob$E[posimpnoh$triangob$EB%in%c(1)]),]}
matepro<-fin
matepro[1:nrow(fin)%in%unique(posimpnoh$triangob$E[posimpnoh$triangob$EB%in%c(1)])==F,]<-NA
faclinks<-as.factor(is.na(matepro[,1]))
newindlinks<-posfac(faclinks)
maulinks<-posimpnoh$triangob$E[posimpnoh$triangob$EB%in%c(1),]
#plotmyarrays(mate,links=array2list(matrix2arrayasis(maulinks,1)))
newmaulinks<-maulinks
newmaulinks[,1]<-c(1:nrow(maulinks))
newmaulinks[,2]<-match(maulinks[,2],maulinks[,1])
#plotmyarrays(mau,links=array2list(matrix2arrayasis(newmaulinks,1)),xlim=c(25,70))
cycles2 <- function(links) {
require(ggm)
if (any(is.na(links))) stop("missing value/s in links")
mat <- matrix(0L, max(links), max(links))
mat[links] <- 1
lapply(ggm::fundCycles(mat), function(xa) rev(xa[ , 1L]))
}
#plotmyarrays(mau[cycles2(newmaulinks)[[1]],],links=conslinks(nrow(mau),open=F))
sfe1<-spsample(Polygon(rbind(mau[cycles2(newmaulinks)[[1]],],mau[cycles2(newmaulinks)[[1]],][1,])),nadd,type="regular")
sr1<-sfe1@coords
}
#points(sr1)
pred<-predict(fit,sr1)
if(is.null(zlim)==T){zlim<-range(pred)}else{zlim<-zlim}
if(graphics==T){
par(oma=oma,mai=mai,mar=mar)
if(legend==F){ima<-image(xyz2img(cbind(sr1,pred),tolerance=tol),asp=1,xlim=tpsgrid$grid$xlim,ylim=tpsgrid$grid$ylim,col=makeTransparent(colorRampPalette(colors)(n = length(obs)),alpha=alpha),xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="",zlim=zlim)}else{
ima<-image.plot(xyz2img(cbind(sr1,pred),tolerance=tol),asp=1,xlim=tpsgrid$grid$xlim,ylim=tpsgrid$grid$ylim,col=makeTransparent(colorRampPalette(colors)(n = length(obs)),alpha=alpha),xaxs="r",yaxs="r",xaxt="n",yaxt="n",bty="n",xlab="",ylab="",zlim=zlim)
}
par(new=T)
plot(fin,xlim=tpsgrid$grid$xlim,ylim=tpsgrid$grid$ylim,asp=1,pch=pchs,cex=cexs,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
if(is.null(linkss)==F){lineplot(fin,linkss,col=collinkss,lwd=lwds)}
lines(tpsgrid$grid$ngrid,xlim=tpsgrid$grid$xlim,ylim=tpsgrid$grid$ylim)
lines(tpsgrid$grid$ngrid2,xlim=tpsgrid$grid$xlim,ylim=tpsgrid$grid$ylim)
if(plottarget==T){
par(new=T)
plot(init,xlim=tpsgrid$grid$xlim,ylim=tpsgrid$grid$ylim,asp=1,pch=pcht,cex=cext,xaxt="n",yaxt="n",bty="n",xlab="",ylab="")
lineplot(init,linkss,col=collinkst,lwd=lwdt)
}
}
pols<-NULL
pols2<-NULL
if(!is.na(pholes)){
for(i in 1:length(pholes)){
myindex<-which(apply(matrix(list2matrix(linkss)%in%pholes[[i]],ncol=2),1,sum)>1)
matili<-list2matrix(linkss)[myindex,]
holi<-init[unique(sort(c(unique(matili[,1]),unique(matili[,2])))),]
hol2i<-fin[unique(sort(c(unique(matili[,1]),unique(matili[,2])))),]
si<-matrix(as.numeric(ordered(matili)),ncol=2)
holtriangi<-RTriangle::triangulate(pslg(holi,S=si))
holtriang2i<-RTriangle::triangulate(pslg(hol2i,S=si))
holui<-holi[unique(holtriangi$E[ holtriangi$EB%in%c(1)]),]
holu2i<-hol2i[unique( holtriang2i$E[ holtriang2i$EB%in%c(1)]),]
holiproi<-holi
holiproi[1:nrow(holi)%in%unique(holtriangi$E[holtriangi$EB%in%c(1)])==F,]<-NA
faclinkshi<-as.factor(is.na(holiproi[,1]))
newindlinkshi<-posfac(faclinkshi)
hlinks<-holtriangi$E[holtriangi$EB%in%c(1),]
newhlinks<-hlinks
newhlinks[,1]<-c(1:nrow(hlinks))
newhlinks[,2]<-match(hlinks[,2],hlinks[,1])
pols<-c(pols,list(holui[cycles2(newhlinks)[[1]],]))
pols2<-c(pols2,list(holu2i[cycles2(newhlinks)[[1]],]))
if(graphics==T){
polygon(holui[cycles2(newhlinks)[[1]],],col="white",border=collinkss)
polygon(holu2i[cycles2(newhlinks)[[1]],],col="white",border=collinkst)}
}}
out<-list(mate=fin,mate2=init,centros=M,interpcoords=sr1,jacs=jac,detjac=myj,detmean=detmean,obs=obs,fit=fit,pred=pred,xlim=tpsgrid$grid$xlim,ylim=tpsgrid$grid$ylim,tol=tol,cols=makeTransparent(colorRampPalette(colors)(n = length(obs)),alpha=alpha),tpsgrid=tpsgrid,sumse=sum(sens2),pols=pols,pols2=pols2,areasipob=po)
out
}
#' @export
helmert<-function(p)
{H<-matrix(0, p, p)
diag(H)<--(0:(p-1)) * (-((0:(p-1))*((0:(p-1))+1))^(-0.5))
for (i in 2:p){H[i,1:(i-1)]<- -((i-1)*(i))^(-0.5)}
H[1,]<-1/sqrt(p)
H}
#' @export
lastsfac<-function(group){
lastsres<-NULL
for (i in levels(group)){
lastresi<-max(which(group==i))
lastsres<-rbind(lastsres,lastresi)
}
return(lastsres)
}
#' @export
list2matrix<-function(mylist){
final<-NULL
for(i in 1:length(mylist)){
temp<-mylist[[i]]
final<-rbind(final,temp)
}
#if(is.null(names(mylist))==F){rownames(final)<-names(mylist)}
return(final)
}
#' @export
makeTransparent = function(..., alpha=0.5) {
if(alpha<0 | alpha>1) stop("alpha must be between 0 and 1")
alpha = floor(255*alpha)
newColor = col2rgb(col=unlist(list(...)), alpha=FALSE)
.makeTransparent = function(col, alpha) {
rgb(red=col[1], green=col[2], blue=col[3], alpha=alpha, maxColorValue=255)
}
newColor = apply(newColor, 2, .makeTransparent, alpha=alpha)
return(newColor)
}
#' @export
manymultgr<-function(y,x,group,steps=5000){
res<-NULL
rsq<-NULL
adjrsq<-NULL
pval<-NULL
for(i in 1:max(as.numeric((group)))){
rsqi<-RsquareAdj(vegan::rda(y[as.numeric(group)==i,],x[as.numeric(group)==i]))$r.squared
adjrsqi<-RsquareAdj(vegan::rda(y[as.numeric(group)==i,],x[as.numeric(group)==i]))$adj.r.squared
pvali<-anova(vegan::rda(y[as.numeric(group)==i,],x[as.numeric(group)==i]),step=steps)$Pr[1]
rsq<-append(rsq,rsqi)
adjrsq<-append(adjrsq,adjrsqi)
pval<-append(pval,pvali)
}
Sig<-ifelse(pval<0.05,c("*"),c(""))
res<-data.frame(round(cbind(rsq,adjrsq,pval),digits=5),Sig)
rownames(res)<-levels(group)
return(res)
}
#' @export
mopa<-function(tt,yy,rot=c("mopa","opa"),CSinit = FALSE,volinit=FALSE,center=TRUE){
warning("the SECOND input matrix will be rotated on the FIRST one")
if(is.matrix(tt)==T){
k<-nrow(tt)
m<-ncol(tt)
ttar<-array(tt,dim=c(k,m,1))
yyar<-array(yy,dim=c(k,m,1))}else {
ttar=tt
yyar=yy
k<-dim(tt)[1]
m<-dim(tt)[2]
}
if(center==T){ttcs<-centershapes(ttar)[,,1]
yycs<-centershapes(yyar)[,,1]}
if(CSinit==T){
yycs<-scaleshapes(yycs)
ttcs<-scaleshapes(ttcs)
}else{yycs<-yycs;ttcs<-ttcs}
if(volinit==T){
at<-tpsdry2(ttcs,yycs,meth="mor",g11=F)$at
detat<-det(at)
if(ncol(yycs)>2){yycs<-yycs/(detat^(1/3))}else{yycs<-yycs/(detat^(1/2))}
}
if(rot=="opa"){rotprocstep1<-svd(t(ttcs)%*%yycs)}
stef<-CreateL(ttcs)
W<-(stef$Lsubk%*%yycs)
appo<-stef$Linv[(k+1):(k+(m+1)),1:k]%*%yycs
cT<-appo[1,]
At<-appo[-1,]
if(rot=="mopa"){
rotprocstep1<-svd(At)}
rotprocstep2<-rotprocstep1$v%*%t(rotprocstep1$u)
opizzata1<-yycs%*%rotprocstep2
opizzata2<-array(opizzata1,dim=c(k,m,1))[,,1,drop=F]####centershapes(array(opizzata1,dim=c(k,m,1)))[,,1,drop=F]
Wafter<-stef$Lsubk%*%opizzata2[,,1]
appoafter<-stef$Linv[(k+1):(k+(m+1)),1:k]%*%opizzata2[,,1]
cTafter<-appoafter[1,]
Atafter<-appoafter[-1,]
out=list(opizzata=opizzata2,W=W,cT=cT,At=At,Wafter=Wafter,cTafter=cTafter,Atafter=Atafter)
return(out)
}
#' @export
newmb<-function(source,target){
k<-nrow(source)
m<-ncol(source)
h<-1*(helmert(k)[-1,])
cm<-t(h)%*%h
source<-cm%*%source
target<-cm%*%target
s1<-sigm.new(source)
source<-h%*%source
target<-h%*%target
s<-h%*%s1%*%t(h)
S<-s
Q<-source
Gam_11=solve(S)-solve(S)%*%Q%*%solve(t(Q)%*%solve(S)%*%Q)%*%t(Q)%*%solve(S)
Gam_21=solve(t(Q)%*%solve(S)%*%Q)%*%t(Q)%*%solve(S)
Gam_22=-solve(t(Q)%*%solve(S)%*%Q)
W=Gam_11%*%target
At=Gam_21%*%target
out<-list(gamma11=Gam_11,gamma21=Gam_21,gamma22=Gam_22,W=W,At=At,sold=s1,snew=s,h=h)
return(out)
}
#' @export
opaloop2<-function(GM,array,scale=F,reflect=F){
library(abind)
library(Morpho)
k<-dim(array)[1]
m<-dim(array)[2]
n<-dim(array)[3]
looped<-NULL
rots<-NULL
for(i in 1:n){
print(i)
opai<-rotonto(GM,array[,,i],scale=scale,reflection=reflect,signref=T)
loopedi<-array(opai$yrot,dim=c(k,m,1))
looped<-abind::abind(looped,loopedi)
rotsi<-opai$gamm
rots<-c(rots,list(rotsi))
}
out<-list(looped=looped,rots=rots)
out
}
#' @export
ordiwithshapes<-function(mshape,scores,rotation,whichaxes=c(1,2),addata=NULL,asp=1,xlab="PC1",ylab="PC2",triang=NULL,factraj=NULL,coltraj=NULL,distscale=1,scaleramp=F,from=0,to=NULL,mag=1,procSym=T,subplotdim=2,legendgroup=NULL,shiftposx=1.5,shiftnegx=1.5,shiftposy=1.5,shiftnegy=1.5,links=NULL,collinks=1,grouphull=NULL,colhull=NULL,labels=NULL,labelscex=1,pch=19,col=1,cex=1,mult=0.5,tit3d=T,plotsource=T,xlim=extendrange(extendrange(range(scores[,whichaxes[1]]),f=mult)),ylim=extendrange(extendrange(range(scores[,whichaxes[2]]),f=mult))){
library(Morpho)
library(spatstat)
library(calibrate)
if(procSym==T){
pc1pos<-showPC(max(scores[,whichaxes[1]])*mag,rotation[,whichaxes[1]],mshape)
pc1neg<-showPC(min(scores[,whichaxes[1]])*mag,rotation[,whichaxes[1]],mshape)
pc2pos<-showPC(max(scores[,whichaxes[2]])*mag,rotation[,whichaxes[2]],mshape)
pc2neg<-showPC(min(scores[,whichaxes[2]])*mag,rotation[,whichaxes[2]],mshape)}else{
pc1pos<-showPC2(max(scores[,whichaxes[1]])*mag,rotation[,whichaxes[1]],mshape)
pc1neg<-showPC2(min(scores[,whichaxes[1]])*mag,rotation[,whichaxes[1]],mshape)
pc2pos<-showPC2(max(scores[,whichaxes[2]])*mag,rotation[,whichaxes[2]],mshape)
pc2neg<-showPC2(min(scores[,whichaxes[2]])*mag,rotation[,whichaxes[2]],mshape)
}
if(dim(mshape)[2]<3){
library(TeachingDemos)
library(Morpho)
library(calibrate)
library(spatstat)
library(shapes)
plot(scores[,whichaxes[1]],scores[,whichaxes[2]],axes=F,xlim=xlim,ylim=ylim,pch=pch,col=col,cex=cex,asp=asp,xlab=xlab,ylab=ylab)
axis(1,pos=0,at=round(seq(from=min(scores[,whichaxes[1]]),to=max(scores[,whichaxes[1]]),length.out=10),2))
axis(2,pos=0,at=round(seq(from=min(scores[,whichaxes[2]]),to=max(scores[,whichaxes[2]]),length.out=10),2))
if(!is.null(addata)){
par(new=T)
plot(addata,asp=asp,xlim=xlim,ylim=ylim,pch=pch,col=col,cex=cex,axes=F,xlab="",ylab="")}
if(!is.null(factraj)){
if(is.null(coltraj)){coltraj=rep(1,nlevels(factraj))}else{coltraj=coltraj}
for (i in 1 :nlevels(factraj)){
lines(scores[,whichaxes[1]][as.numeric(factraj)==i],scores[,whichaxes[2]][as.numeric(factraj)==i],xlim=xlim,ylim=ylim,col=coltraj[i])
par(new=T)
}
}
if(!is.null(labels)==T){textxy(scores[,whichaxes[1]],scores[,whichaxes[2]],labs=labels,cex=labelscex)}
if(!is.null(grouphull)==T){
if(is.null(colhull)==T){colhull<-c(1:nlevels(grouphull))}else{colhull<-colhull}
for(i in 1:(max(as.numeric(grouphull))))
{if(length(scores[,1][as.numeric(grouphull)==i])<3){NULL}
else{
hulli<-convexhull.xy(subset(cbind(scores[,whichaxes[1]],scores[,whichaxes[2]]),as.numeric(grouphull)==i))
par(new=T)
daplotx<-c(hulli$bdry[[1]][[1]][length(hulli$bdry[[1]][[1]])],hulli$bdry[[1]][[1]])
daploty<-c(hulli$bdry[[1]][[2]][length(hulli$bdry[[1]][[2]])],hulli$bdry[[1]][[2]])
plot(daplotx,daploty,lwd=2,type="l",lty=i,col=colhull[i],xlim=xlim,ylim=ylim,axes=F,asp=asp,xlab="",ylab="")
}
}}
subplot(tpsgridpaolo(mshape,pc1pos,linksYY=links,collinksYY=collinks,axes2d=F,displ=F,collinksTT=makeTransparent("white",alpha=0)),max(scores[,whichaxes[1]])*shiftposx,0,size=c(subplotdim,subplotdim))
subplot(tpsgridpaolo(mshape,pc1neg,linksYY=links,collinksYY=collinks,axes2d=F,displ=F,collinksTT=makeTransparent("white",alpha=0)),min(scores[,whichaxes[1]])*shiftnegx,0,size=c(subplotdim,subplotdim))
subplot(tpsgridpaolo(mshape,pc2pos,linksYY=links,collinksYY=collinks,axes2d=F,displ=F,collinksTT=makeTransparent("white",alpha=0)),0,max(scores[,whichaxes[2]])*shiftposy,size=c(subplotdim,subplotdim))
subplot(tpsgridpaolo(mshape,pc2neg,linksYY=links,collinksYY=collinks,axes2d=F,displ=F,collinksTT=makeTransparent("white",alpha=0)),0,min(scores[,whichaxes[2]])*shiftnegy,size=c(subplotdim,subplotdim))
}else{
if(is.null(triang)==F&is.null(links)==T){
open3d(windowRect=c(100,100,1000,1000))
mat <- matrix(1:8, ncol=2)
layout3d(mat, height = rep(c(2,1), 2), model = "inherit")
diffonmesh(mshape,pc1pos,triang,title=F,distscale=distscale,from=from,to=to,plotsource=plotsource,scaleramp=scaleramp)
next3d()
text3d(0,0,0,paste("Scores",whichaxes[1],"pos"))
next3d()
diffonmesh(mshape,pc2pos,triang,title=F,distscale=distscale,from=from,to=to,plotsource=plotsource,scaleramp=scaleramp)
next3d()
text3d(0,0,0,paste("Scores",whichaxes[2],"pos"))
next3d()
diffonmesh(mshape,pc1neg,triang,title=F,distscale=distscale,from=from,to=to,plotsource=plotsource,scaleramp=scaleramp)
next3d();text3d(0,0,0,paste("Scores",whichaxes[1],"neg"))
next3d()
diffonmesh(mshape,pc2neg,triang,title=F,distscale=distscale,from=from,to=to,plotsource=plotsource,scaleramp=scaleramp)
next3d();text3d(0,0,0,paste("Scores",whichaxes[2],"neg"))
}
if(is.null(links)==F){
open3d(windowRect=c(100,100,1000,1000))
mat <- matrix(1:8, ncol=2)
layout3d(mat, height = rep(c(2,1), 2), model = "inherit")
plot3D(pc1pos,add=T,bbox=F)
lineplot(pc1pos,links)
if(tit3d==T){next3d();text3d(0,0,0,paste("Scores",whichaxes[1],"pos"))}
next3d()
plot3D(pc2pos,add=T,bbox=F)
lineplot(pc2pos,links)
if(tit3d==T){next3d();text3d(0,0,0,paste("Scores",whichaxes[2],"pos"))}
next3d()
plot3D(pc1neg,add=T,bbox=F)
lineplot(pc1neg,links)
if(tit3d==T){next3d();text3d(0,0,0,paste("Scores",whichaxes[1],"neg"))}
next3d()
plot3D(pc2neg,add=T,bbox=F)
lineplot(pc2neg,links)
if(tit3d==T){next3d();text3d(0,0,0,paste("Scores",whichaxes[2],"neg"))}}
plot(scores[,whichaxes[1]],scores[,whichaxes[2]],axes=F,xlim=xlim,ylim=ylim,pch=pch,col=col,cex=cex,asp=asp,xlab=xlab,ylab=ylab)
axis(1,pos=0,at=round(seq(from=min(scores[,whichaxes[1]]),to=max(scores[,whichaxes[1]]),length.out=10),2))
axis(2,pos=0,at=round(seq(from=min(scores[,whichaxes[2]]),to=max(scores[,whichaxes[1]]),length.out=10),2))
if(!is.null(addata)){
par(new=T)
plot(addata,xlim=xlim,ylim=ylim,pch=pch,col=col,cex=cex,axes=F,asp=asp,xlab="",ylab="")}
if(!is.null(factraj)){
if(is.null(coltraj)){coltraj=rep(1,nlevels(factraj))}else{coltraj=coltraj}
for (i in 1 :nlevels(factraj)){
lines(scores[,whichaxes[1]][as.numeric(factraj)==i],scores[,whichaxes[2]][as.numeric(factraj)==i],xlim=xlim,ylim=ylim,col=coltraj[i])
par(new=T)
}
}
if(!is.null(labels)==T){textxy(scores[,whichaxes[1]],scores[,whichaxes[2]],labs=labels)}
if(!is.null(grouphull)==T){
if(is.null(colhull)==T){colhull<-c(1:nlevels(grouphull))}else{colhull<-colhull}
for(i in 1:(max(as.numeric(grouphull))))
{if(length(scores[,1][as.numeric(grouphull)==i])<3){NULL}
else{
hulli<-convexhull.xy(subset(cbind(scores[,whichaxes[1]],scores[,whichaxes[2]]),as.numeric(grouphull)==i))
par(new=T)
daplotx<-c(hulli$bdry[[1]][[1]][length(hulli$bdry[[1]][[1]])],hulli$bdry[[1]][[1]])
daploty<-c(hulli$bdry[[1]][[2]][length(hulli$bdry[[1]][[2]])],hulli$bdry[[1]][[2]])
plot(daplotx,daploty,lwd=2,type="l",lty=i,col=colhull[i],xlim=xlim,ylim=ylim,axes=F,asp=asp)
}
}}}
if(is.null(legendgroup)==F){
x11()
plot(scores[,1],scores[,2],col="white")
legend(min(scores[,1]),max(scores[,2]),unique(legendgroup), cex=1, col=unique(col), pch=unique(pch),box.col="white")}
}
#' @export
plotptau5<-function(objptau,links=NULL,projorig=T,whichaxes=c(1,2),cexscale=round(max(centroid.size(objptau$arrayord)),digits=0),shapescale=10,mag=1,subplotdim=2,shiftnegy=1,shiftposy=1,shiftnegx=1,shiftposx=1,col=as.numeric(objptau$factorord),pch=19,triang=NULL,from=0,topcs=NULL,tore=NULL,plotsource=T){
library(TeachingDemos)
k<-dim(objptau$arrayord)[1]
m<-dim(objptau$arrayord)[2]
n<-dim(objptau$arrayord)[3]
transp<-read.inn(objptau$shifted,k,m)
origsize<-objptau$indepepure
if(projorig==T){
ordiwithshapes(objptau$space1mshape,objptau$space1$x,objptau$space1$rotation,procSym=F,whichaxes=whichaxes,addata=objptau$origproj[,whichaxes],asp=1,factraj=objptau$factorord,cex=origsize/cexscale,triang=triang,from=from,to=topcs,links=links,mag=mag,shiftnegy=1.5,shiftposy=2,col=col,pch=pch,subplotdim=subplotdim,plotsource=plotsource)
title("LS on predictions on Shape Space and original data re-projected")}else{
ordiwithshapes(objptau$space1mshape,objptau$space1$x,objptau$space1$rotation,procSym=F,whichaxes=whichaxes,asp=1,factraj=objptau$factorord,cex=origsize/cexscale,triang=triang,from=from,to=topcs,links=links,mag=mag,shiftnegy=1.5,shiftposy=2,col=col,pch=pch,subplotdim=subplotdim,plotsource=plotsource)
title("LS on predictions on Shape Space")}
ranges<-apply(rbind(objptau$space1$x,objptau$origproj),2,range)
ratesorig<-ratesbygroup(read.inn(objptau$predictpure2,k,m),objptau$factorord,objptau$indepepure)
plot(objptau$indepepure,ratesorig,pch=pch,col=col)
for(i in 1:nlevels(objptau$factorord)){
lines(objptau$indepepure[as.numeric(objptau$factorord)==i][-firstsfac(objptau$factorord)],ratesorig[as.numeric(objptau$factorord)==i][-firstsfac(objptau$factorord)],col=col[firstsfac(objptau$factorord)][i])
}
title("Rates of shape change among consecutive predictions per unit size in original data")
ratestrasp<-ratesbygroup(objptau$predictpure,objptau$factorord,objptau$indepepure)
plot(objptau$indepepure,ratestrasp,pch=pch,col=col)
for(i in 1:nlevels(objptau$factorord)){
lines(objptau$indepepure[as.numeric(objptau$factorord)==i][-firstsfac(objptau$factorord)],ratestrasp[as.numeric(objptau$factorord)==i][-firstsfac(objptau$factorord)],col=col[firstsfac(objptau$factorord)][i])
}
title("Rates of shape change among consecutive predictions per unit size in transported data")
plot(ratesorig,ratestrasp,col=col,pch=pch)
title("Original rates of shape change per unit size vs those of transported data")
adults<-NULL
adultsdaplot<-NULL
for(i in 1:nlevels(objptau$factorord)){
adulti<-array(showPC2(objptau$space1$x[lastsfac(objptau$factorord),1:3][i,],objptau$space1$rotation[,1:3],objptau$space1mshape),dim=c(k,m,1))
adultdaploti<-array(showPC2(objptau$space1$x[lastsfac(objptau$factorord),1:3][i,]*mag,objptau$space1$rotation[,1:3],objptau$space1mshape),dim=c(k,m,1))
adults<-abind::abind(adults,adulti)
adultsdaplot<-abind::abind(adultsdaplot,adultdaploti)
}
if(m<3){adultsdaplot<-abind::abind(adultsdaplot,array(rep(0,k*n),dim=c(k,1,nlevels(objptau$factorord))),along=2)}
init<-array(showPC2(objptau$space1$x[firstsfac(objptau$factorord),1:3][1,],objptau$space1$rotation[,1:3],objptau$space1mshape),dim=c(k,m,1))
initdaplot<-array(showPC2(objptau$space1$x[firstsfac(objptau$factorord),1:3][1,]*mag,objptau$space1$rotation[,1:3],objptau$space1mshape),dim=c(k,m,1))
if(m<3){initdaplot<-abind::abind(initdaplot,array(rep(0,k*n),dim=c(k,1,1)),along=2)}
if(is.null(triang)==F){
adultsdaplotvis<-NULL
for(i in 1:nlevels(objptau$factorord)){
adultsdaplotvisi<-meshDist(plotsurf(adultsdaplot[,,i],triang,plot=F),plotsurf(initdaplot[,,1],triang,plot=F),to=tore,from=from,plot=F)
daagg<-objptau$space1$x[1:n,1:3][lastsfac(objptau$factorord),][i,]
adultsdaplotvisi<-translate3d(scalemesh(adultsdaplotvisi$colMesh,1/shapescale,center="none"),daagg[1],daagg[2],daagg[3])
adultsdaplotvis<-c(adultsdaplotvis,list(adultsdaplotvisi))
}
}
open3d()
for(i in 1:nlevels(objptau$factorord)){
lines3d(objptau$space1$x[1:n,1:3][as.numeric(objptau$factorord)==i,],col=i,add=T)
}
if(is.null(triang)==T){
babedaagg<-rep.row(objptau$space1$x[firstsfac(objptau$factorord),1:3][1,],k)
for(i in 1:nlevels(objptau$factorord)){
daplottarei<-adultsdaplot[,,i]
daagg<-rep.row(objptau$space1$x[1:n,1:3][lastsfac(objptau$factorord),][i,],k)
plot3D((daplottarei/shapescale)+daagg,col=i,add=T,size=1,bbox=F)
lineplot((daplottarei/shapescale)+daagg,links,col=i)
}
plot3D((initdaplot[,,1]/shapescale)+babedaagg,bbox=F,add=T)
lineplot((initdaplot[,,1]/shapescale)+babedaagg,links)
}else{
for(i in 1:nlevels(objptau$factorord)){
shade3d(adultsdaplotvis[[i]],add=T)
}
babedaagg<-rep.row(objptau$space1$x[firstsfac(objptau$factorord),1:3][1,],k)
shade3d(plotsurf((initdaplot[,,1]/shapescale)+babedaagg,triang,plot=F),add=T,alpha=0.5)
}
title3d("LS data in the Shape Space; first three PC scores")
decorate3d()
out<-list(ratesorig=ratesorig,ratestrasp=ratestrasp)
}
#' @export
pwpermancova<-function(y, pred1,pred2,nperm=999){
library(vegan)
if(is.factor(pred1)==TRUE){pred1<-factor(pred1,levels=unique(pred1))}else{NULL}
if(is.factor(pred2)==TRUE){pred2<-factor(pred2,levels=unique(pred2))}else{NULL}
if(is.factor(pred1)==TRUE){species<-as.numeric(pred1)}else{NULL}
if(is.factor(pred2)==TRUE){species<-as.numeric(pred2)}else{NULL}
if(is.factor(pred1)==TRUE){group<-pred1}else{NULL}
if(is.factor(pred2)==TRUE){group<-pred2}else{NULL}
fat_species<-group
r_adonis_pred1<-matrix(0,nrow=max(species),ncol=max(species))
p_adonis_pred1<-matrix(0,nrow=max(species),ncol=max(species))
r_adonis_pred2<-matrix(0,nrow=max(species),ncol=max(species))
p_adonis_pred2<-matrix(0,nrow=max(species),ncol=max(species))
r_adonis_pred1_pred2<-matrix(0,nrow=max(species),ncol=max(species))
p_adonis_pred1_pred2<-matrix(0,nrow=max(species),ncol=max(species))
for(i in 1:(max(species)-1))
{
for(j in (i+1):max(species)){
if(ncol(as.matrix(pred1))>1){
ado<-adonis(y[species==i|species==j,]~pred1[species==i|species==j,]*pred2[species==i|species==j],permutations=nperm,method="euclidean")
}else{NULL}
if(ncol(as.matrix(pred2))>1){
ado<-adonis(y[species==i|species==j,]~pred1[species==i|species==j]*pred2[species==i|species==j,],permutations=nperm,method="euclidean")
}else{NULL}
if(ncol(as.matrix(pred1))<2&ncol(as.matrix(pred2))<2){
ado<-adonis(y[species==i|species==j,]~pred1[species==i|species==j]*pred2[species==i|species==j],permutations=nperm,method="euclidean")
}else{NULL}
r_adonis_pred1[i,j]<-ado$aov.tab$R2[1]
p_adonis_pred1[i,j]<-ado$aov.tab$Pr[1]
r_adonis_pred2[i,j]<-ado$aov.tab$R2[2]
p_adonis_pred2[i,j]<-ado$aov.tab$Pr[2]
r_adonis_pred1_pred2[i,j]<-ado$aov.tab$R2[3]
p_adonis_pred1_pred2[i,j]<-ado$aov.tab$Pr[3]
}
}
rownames(r_adonis_pred1)=colnames(r_adonis_pred1)<-levels(group)
rownames(p_adonis_pred1)=colnames(p_adonis_pred1)<-levels(group)
rownames(r_adonis_pred2)=colnames(r_adonis_pred2)<-levels(group)
rownames(p_adonis_pred2)=colnames(p_adonis_pred2)<-levels(group)
rownames(r_adonis_pred1_pred2)=colnames(r_adonis_pred1_pred2)<-levels(group)
rownames(p_adonis_pred1_pred2)=colnames(p_adonis_pred1_pred2)<-levels(group)
out<-list(r_adonis_pred1=r_adonis_pred1,p_adonis_pred1=p_adonis_pred1,r_adonis_pred2=r_adonis_pred2,p_adonis_pred2=p_adonis_pred2,r_adonis_pred1_pred2=r_adonis_pred1_pred2,p_adonis_pred1_pred2=p_adonis_pred1_pred2)
return(out)
}
#' @export
ratesbygroup<-function(predictions,factor,indep,sss=F){
prova3<-seqrate(predictions,factor,vector=indep,sss=sss)
prova4<-NULL
for(i in 1:nlevels(factor)){
prova4i<-c(rep(0,nlevels(factor))[i],prova3$rate[as.numeric(factor[-firstsfac(factor)])==i])
prova4<-append(prova4,prova4i)}
prova5<-prova4
plot(indep,prova5,col=as.numeric(factor),ylim=c(0,max(prova5)),xlim=range(indep))
for(i in 1:nlevels(factor)){
lines(indep[as.numeric(factor)==i][-firstsfac(factor)],prova4[as.numeric(factor)==i][-firstsfac(factor)],col=i)
}
return(prova5)
}
#' @export
rep.row<-function(x,n){
matrix(rep(x,each=n),nrow=n)
}
#' @export
scaleshapes<-function(array){
k<-dim(array)[1]
m<-dim(array)[2]
n<-dim(array)[3]
library(abind)
library(shapes)
library(Morpho)
divmat<-function(mat){
mat2<-mat/cSize(mat)
mat2
}
if(is.matrix(array)==T){array<-array(array,dim=c(nrow(array),ncol(array),1))}
scaled<-vecx(t(apply(array,3,divmat)),revert=T,lmdim=m)
return(scaled)
}
#' @export
seqrate<-function(preds,factor,vector=centroid.size(preds),sss=F){
mytable<-table(factor)
chrate<-NULL
sizes<-NULL
seqdist<-NULL
for(i in 1: nlevels(factor)){
for(j in 2:mytable[i]){
sizei<-(vector[as.numeric(factor)==i][j])-(vector[as.numeric(factor)==i][j-1])
if(sss==T){
seqdisti<-ssriemdist2(preds[,,as.numeric(factor)==i][,,j],preds[,,as.numeric(factor)==i][,,j-1])}else{
seqdisti<-kendalldist(preds[,,as.numeric(factor)==i][,,j],preds[,,as.numeric(factor)==i][,,j-1])
}
chratei<-seqdisti/(sizei)
sizes<-append(sizes,sizei)
chrate<-append(chrate,chratei)
seqdist<-append(seqdist,seqdisti)
}
}
out<-list(rate=chrate,sizes=sizes,seqdist=seqdist)
return(out)
}
#' @export
showPC2<-function(x,rotation,mshape) {
k<-dim(mshape)[1]
m<-dim(mshape)[2]
mshape2<-array2mat(array(mshape,dim=c(k,m,1)),1,k*m)
dims <- dim(mshape)
if (length(x) > 1){predPC<-c(rotation %*% x)}else{predPC<-rotation*x}
modell <- read.inn(mshape2+predPC,k,m)[,,1]
return(modell)
}
#' @export
sigm.new<-function(mat1,mat2=NULL){
tt<-mat1
if(is.null(mat2)){yy<-mat1}else{yy<-mat2}
SGMr <- apply(tt,1,function(t)apply(yy,1,biharm.new,t))
replace(SGMr,which(SGMr=="NaN",arr.ind=T),0)
}
#' @export
tpsgridpaolo<-function (TT, YY, xbegin = -999, ybegin = -999, xlim=NULL,ylim=NULL,xwidth = -999, opt = 1, ext = 0.0, asp=1,ngrid = 22, cex = 1, pch = 20,colshift=1,zslice = 0, graphics=T,mag = 1, axes3 = FALSE,linksTT=NULL,linksYY=NULL,collinksTT=1,collinksYY=2,lwdtt=2,lwdyy=2,colgrid=1,axes2d=T,collandsTT=collinksTT,collandsYY=collinksYY,displ=T,coldispl=4){
######### some SMALL changes from Ian Dryden's function from package "shapes"
k <- dim(TT)[1]
m <- dim(TT)[2]
YY <- TT + (YY - TT) * mag
bb <- array(TT, c(dim(TT), 1))
aa <- defplotsize2(bb)
if (xwidth == -999) {
xwidth <- aa$width
}
if (xbegin == -999) {
xbegin <- aa$xl
}
if (ybegin == -999) {
ybegin <- aa$yl
}
if (m == 3) {
zup <- max(TT[, 3])
zlo <- min(TT[, 3])
zpos <- zslice
for (ii in 1:length(zslice)) {
zpos[ii] <- (zup + zlo)/2 + (zup - zlo)/2 * zslice[ii]
}
}
xstart <- xbegin
ystart <- ybegin
ngrid <- trunc(ngrid/2) * 2
kx <- ngrid
ky <- ngrid - 1
l <- kx * ky
step <- xwidth/(kx - 1)
r <- 0
X <- rep(0, times = kx)
Y2 <- rep(0, times = ky)
for (p in 1:kx) {
ystart <- ybegin
xstart <- xstart + step
for (q in 1:ky) {
ystart <- ystart + step
r <- r + 1
X[r] <- xstart
Y2[r] <- ystart
}
}
TPS <- bendingenergy(TT)
gamma11 <- TPS$gamma11
gamma21 <- TPS$gamma21
gamma31 <- TPS$gamma31
W <- gamma11 %*% YY
ta <- t(gamma21 %*% YY)
B <- gamma31 %*% YY
WtY <- t(W) %*% YY
trace <- c(0)
for (i in 1:m) {
trace <- trace + WtY[i, i]
}
if(m==2){benergy <- (16 * pi) * trace}else{benergy <- (8 * pi) * trace}
l <- kx * ky
phi <- matrix(0, l, m)
s <- matrix(0, k, 1)
for (islice in 1:length(zslice)) {
if (m == 3) {
refc <- matrix(c(X, Y2, rep(zpos[islice], times = kx *
ky)), kx * ky, m)
}
if (m == 2) {
refc <- matrix(c(X, Y2), kx * ky, m)
}
for (i in 1:l) {
s <- matrix(0, k, 1)
for (im in 1:k) {
s[im, ] <- shapes::sigma(refc[i, ] - TT[im, ])
}
phi[i, ] <- ta + t(B) %*% refc[i, ] + t(W) %*% s
}
if(graphics==T){
if (m == 3) {
if (opt == 2) {
shapes3d(TT, color = 2, axes3 = axes3, rglopen = FALSE)
shapes3d(YY, color = 4, rglopen = FALSE)
for (i in 1:k) {
lines3d(rbind(TT[i, ], YY[i, ]), col = 1)
}
for (j in 1:kx) {
lines3d(refc[((j - 1) * ky + 1):(ky * j), ],
color = 6)
}
for (j in 1:ky) {
lines3d(refc[(0:(kx - 1) * ky) + j, ], color = 6)
}
}
shapes3d(TT, color = collandsTT, axes3 = axes3, rglopen = FALSE)
shapes3d(YY, color = collandsYY, rglopen = FALSE)
for (i in 1:k) {
lines3d(rbind(TT[i, ], YY[i, ]), col = colshift)
}
for (j in 1:kx) {
lines3d(phi[((j - 1) * ky + 1):(ky * j), ], color = colgrid)
}
for (j in 1:ky) {
lines3d(phi[(0:(kx - 1) * ky) + j, ], color = colgrid)
}
}
}
}
if (m == 2) {
par(pty = "s")
if (opt == 2) {
par(mfrow = c(1, 2))
order <- linegrid(refc, kx, ky)
if(is.null(xlim)==T){xlim = c(xbegin -xwidth * ext, xbegin + xwidth * (1 + ext))}else{xlim=xlim}
if(is.null(ylim)==T){ylim = c(ybegin - (xwidth * ky)/kx * ext, ybegin + (xwidth * ky)/kx * (1 + ext))}else{ylim=ylim}
if(graphics==T){
plot(order[1:l, 1], order[1:l, 2], type = "l", xlim = xlim, ylim = ylim, xlab = " ", ylab = " ",asp=asp,,axes=axes2d)
lines(order[(l + 1):(2 * l), 1], order[(l + 1):(2 * l), 2], type = "l",col=colgrid,xlim = xlim, ylim = ylim,asp=asp)
points(TT, cex = cex, pch = pch, col = collandsTT)
}}
if(is.null(xlim)==T){xlim = c(xbegin -xwidth * ext, xbegin + xwidth * (1 + ext))}else{xlim=xlim}
if(is.null(ylim)==T){ylim = c(ybegin - (xwidth * ky)/kx * ext, ybegin + (xwidth * ky)/kx * (1 + ext))}else{ylim=ylim}
order <- linegrid(phi, kx, ky)
if(graphics==T){plot(order[1:l, 1], order[1:l, 2], type = "l", xlim = xlim, ylim = ylim, xlab = " ", ylab = " ",col=colgrid,asp=asp,axes=axes2d)
lines(order[(l + 1):(2 * l), 1], order[(l + 1):(2 * l), 2], type = "l",col=colgrid,xlim = xlim, ylim = ylim,asp=asp)}
if(graphics==T){points(YY, cex = cex, pch = pch, col = collandsYY)}
if(graphics==T){points(TT, cex = cex, pch = pch, col = collandsTT)}
if(graphics==T){
if(displ==T){
for (i in 1:(k)) {
arrows(TT[i, 1], TT[i, 2], YY[i, 1], YY[i, 2], col = coldispl, length = 0.1, angle = 20)
}
}}
firstcol<-order[1:l,][1:kx,][-kx,]
firstrow<-order[(l + 1):(2 * l),][((kx*ky-1)-ky):(kx*ky-1),][-c(1:2),]
lastcol<-order[1:l,][((kx*ky)-ky):(kx*ky),][-1,]
lastrow<-order[(l + 1):(2 * l),][2:ky,][order((ky:2)),]
bound = rbind(firstcol,firstrow,lastcol,lastrow)
them<-nrow(order[1:l,])/ngrid
}
if(m==2){grid<-list(ngrid=order[1:l,],ngrid2=order,m=them,n=ngrid,bound=bound,l=l,xlim=xlim,ylim=ylim,TT=TT,YY=YY)}else{
grid<-list(n=ngrid,l=l,TT=TT,YY=YY)
}
out<-list(YY=YY,gamma11=gamma11,gamma21=gamma21,gamma31=gamma31,W=W,ta=ta,B=B,WtY=WtY,trace=trace,benergy=benergy,grid=grid,kx=kx,ky=ky)
if(graphics==T){if(!is.null(linksTT)){lineplot(TT,linksTT,lwd=lwdtt,col=collinksTT)}}
if(graphics==T){if(!is.null(linksYY)){lineplot(YY,linksYY,lwd=lwdyy,col=collinksYY)}}
return(out)
}
#' @export
|
10057b62679fb07f590922fb9421225ed561d236
|
0f71eeb60ff8502daccd2e6b145363c7d540e36b
|
/R-code/antonio/svm-no-caret.R
|
d1181a385732749eaaa7cbe357d474ec2f36d968
|
[] |
no_license
|
analytics-ufcg/recogme
|
47e16f54b9a2792f33722ceb50a546bb6749a68d
|
e3e7dd1de1b94cb8fd8d03214d85e9d108220de5
|
refs/heads/master
| 2021-01-12T21:10:32.836690
| 2015-12-16T18:18:16
| 2015-12-16T18:18:16
| 43,513,165
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 733
|
r
|
svm-no-caret.R
|
library( 'e1071' )
dados.train <- read.delim("~/Documents/recogme/recogme-R-antonio/dados-train.psv")
dados.train <- dados.train[complete.cases(dados.train),]
dados.train <- dados.train %>% filter(V1.x != "arthur.senaufcg@gmail.com", V1.x != "orion.lima@ccc.ufcg.edu.br") %>% droplevels()
levels(dados.train$V1.x)
str(dados.train)
summary(dados.train)
model <- svm( dados.train$V1.x~., dados.train)
dados.teste <- read.delim("~/Documents/recogme/recogme-R-antonio/dados-teste.psv")
dados.teste <- droplevels(dados.teste[complete.cases(dados.teste),])
levels(dados.teste$V1.x)
test <- select(dados.teste, -V1.x)
prediction <- predict(model, test)
resp <- table(prediction, dados.teste$V1.x)
View(resp)
confusionMatrix(resp)
|
ebc783a2ee2bb679929c2a4a487c2d4f39275cd8
|
4b68fab7e23c59ffafe18ec2018c5362033aa7e2
|
/man/p1.given.p0.Rd
|
dbbe108626cae8fd196b6265b9bc3554abf00b13
|
[] |
no_license
|
cran/MChtest
|
def7ef61bd0b6bf7833d57a9622b9be46ba822db
|
4b1c22dee02a6a6cb47e62ba67d5c6e548c2b034
|
refs/heads/master
| 2020-05-18T00:28:50.363675
| 2019-05-16T12:10:03
| 2019-05-16T12:10:03
| 17,680,561
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,410
|
rd
|
p1.given.p0.Rd
|
\name{p1.given.p0}
\alias{p1.given.p0}
\alias{p0.given.p1}
\title{Find p0 (or p1) associated with p1 (or p0) that gives minimax tsprt}
\description{ Consider the SPRT for testing Ho:p=p0 vs H1:p=p1 where p1\eqn{<} Alpha \eqn{<} p0.
For Monte Carlo tests, we want to reject and conclude that p\eqn{<}Alpha. In terms of the
resampling risk at p (i.e., the probability of reaching a wrong decision at p) the minimax
SPRT has a particular relationship between p0 and p1. Here we calculate p1 given p0 or vise versa
to obtain that relationship.
}
\usage{
p1.given.p0(p0, Alpha = 0.05, TOL = 10^-9)
p0.given.p1(p1, Alpha = 0.05, TOL = 10^-9)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{p0}{null such that p0\eqn{>}Alpha}
\item{p1}{alternative such that p1\eqn{<}Alpha}
\item{Alpha}{want tsprt associated with testing p=Alpha or not}
\item{TOL}{tolerance level input into call to \code{\link{uniroot}}}
}
%\details{}
\value{
either p0 or p1}
\references{
Fay, M.P., Kim, H-J. and Hachey, M. (2007). Using truncated sequential probability ratio test boundaries
for Monte Carlo implementation of hypothesis tests. Journal of Computational and Graphical
Statistics. 16(4):946-967.
}
\author{Michael P. Fay}
\examples{
p1.given.p0(.04)
}
\keyword{misc}% at least one, from doc/KEYWORDS
%\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
|
d2c090d09b4acf8f37eb9590a36885a8742f3b23
|
5bb2c8ca2457acd0c22775175a2722c3857a8a16
|
/tests/testthat/test-zelig.R
|
1219c5b3244a8546d7af5890cbfc19e8cd1969e9
|
[] |
no_license
|
IQSS/Zelig
|
d65dc2a72329e472df3ca255c503b2e1df737d79
|
4774793b54b61b30cc6cfc94a7548879a78700b2
|
refs/heads/master
| 2023-02-07T10:39:43.638288
| 2023-01-25T20:41:12
| 2023-01-25T20:41:12
| 14,958,190
| 115
| 52
| null | 2023-01-25T20:41:13
| 2013-12-05T15:57:10
|
R
|
UTF-8
|
R
| false
| false
| 11,702
|
r
|
test-zelig.R
|
#### Integration tests for the Zelig estimate, set, sim, plot workflow ####
# FAIL TEST sim workflow -------------------------------------------------------
test_that('FAIL TEST sim method warning if insufficient inputs', {
z5 <- zls$new()
expect_output(z5$zelig(Fertility ~ Education, model="ls", data = swiss),
'Argument model is only valid for the Zelig wrapper, but not the Zelig method, and will be ignored.')
expect_warning(z5$sim(),
'No simulations drawn, likely due to insufficient inputs.')
expect_error(z5$graph(), 'No simulated quantities of interest found.')
})
# FAIL TEST ci.plot range > length = 1 -----------------------------------------
test_that('FAIL TEST ci.plot range > length = 1', {
z <- zls$new()
z$zelig(Fertility ~ Education, data = swiss)
expect_warning(z$setrange(Education = 5),
'Only one fitted observation provided to setrange.\nConsider using setx instead.')
z$sim()
expect_error(z$graph(),
'Simulations for more than one fitted observation are required.')
expect_warning(z$setrange1(Education = 5),
'Only one fitted observation provided to setrange.\nConsider using setx instead.')
expect_error(z$graph(),
'Simulations for more than one fitted observation are required.')
})
# REQUIRE TEST for by estimation workflow --------------------------------------
test_that('REQUIRE TEST for by estimation workflow', {
# Majority Catholic dummy
swiss$maj_catholic <- cut(swiss$Catholic, breaks = c(0, 51, 100))
z5 <- zls$new()
z5$zelig(Fertility ~ Education, data = swiss, by = 'maj_catholic')
z5$setrange(Education = 5:15)
z5$sim()
expect_error(z5$graph(), NA)
})
# FAIL TEST for get_qi when applied to an object with no simulations ------------
test_that('FAIL TEST for get_qi when applied to an object with no simulations', {
z <- zls$new()
z$zelig(Fertility ~ Education, data = swiss)
expect_error(z$get_qi(), 'No simulated quantities of interest found.')
})
# FAIL TEST for get_qi when unsupported qi supplied ----------------------------
test_that('FAIL TEST for get_qi when unsupported qi supplied', {
z5 <- zls$new()
z5$zelig(Fertility ~ Education, data = swiss)
z5$setrange(Education = 5:15)
z5$sim()
expect_error(z5$get_qi(qi = "fa", xvalue = "range"), 'qi must be ev or pv.')
})
# FAIL TEST for estimation model failure ---------------------------------------
test_that('FAIL TEST for estimation model failure', {
no_vary_df <- data.frame(y = rep(1, 10), x = rep(2, 10))
z <- zarima$new()
expect_error(z$zelig(y ~ x, data = no_vary_df),
'Dependent variable does not vary for at least one of the cases.')
expect_error(summary(z), 'Zelig model has not been estimated.')
})
# REQUIRE TEST for sim num argument --------------------------------------------
test_that('REQUIRE TEST for sim num argument', {
z5 <- zls$new()
z5$zelig(Fertility ~ Education, data = swiss)
z5$setx(Education = 5)
z5$sim()
expect_equal(length(z5$get_qi()), 1000)
z5$sim(num = 10) # Look into unexpected behaviour if sim order is reversed
expect_equal(length(z5$get_qi()), 10)
})
# REQUIRE TEST from_zelig_model returns expected fitted model object -----------------
test_that('REQUIRE TEST from_zelig_model returns expected fitted model object', {
z5 <- zls$new()
z5$zelig(Fertility ~ Education, data = swiss)
model_object <- z5$from_zelig_model()
expect_is(model_object, class = 'lm')
expect_equal(as.character(model_object$call[1]), 'lm')
})
# REQUIRE TEST from_zelig_model returns each fitted model object from mi -------------
test_that('REQUIRE TEST from_zelig_model returns each fitted model object from mi', {
set.seed(123)
n <- 100
x1 <- runif(n)
x2 <- runif(n)
y <- rnorm(n)
data.1 <- data.frame(y = y, x = x1)
data.2 <- data.frame(y = y, x = x2)
mi.out <- to_zelig_mi(data.1, data.2)
z.out <- zelig(y ~ x, model = "ls", data = mi.out)
model_list <- z.out$from_zelig_model()
expect_is(model_list, class = 'list')
expect_equal(as.character(model_list[[2]]$call[1]), 'lm')
})
# REQUIRE TEST functioning simparam with by and ATT ----------------------------
test_that('REQUIRE TEST functioning simparam with by and ATT', {
set.seed(123)
n <- 100
xx <- rbinom(n = n, size = 1, prob = 0.3)
zz <- runif(n)
ss <- runif(n)
rr <- rbinom(n, size = 1, prob = 0.5)
mypi <- 1/(1 + exp(-xx -3*zz -0.5))
yb <- rbinom(n, size = 1, prob = mypi)
data <- data.frame(rr, ss, xx, zz, yb)
zb.out <- zlogit$new()
zb.out$zelig(yb ~ xx + zz, data = data, by = "rr")
zb.out$ATT(treatment = "xx")
out <- zb.out$get_qi(qi = "ATT", xvalue = "TE")
expect_equal(length(out), 1000)
})
# REQUIRE TEST getters values and dimensions and plot does not fail-------------
test_that("REQUIRE TEST getters values and dimensions and plot does not fail",
{
set.seed(123)
n <- 1000
myseq <- 1:n
x <- myseq/n
y <- x + (-1)^(myseq) * 0.1
mydata <- data.frame(y = y, x = x)
mydata2 <- data.frame(y = y, x = x + 2)
z.out <- zelig(y ~ x, model = "ls", data = mydata)
expect_equivalent(round(as.numeric(z.out$get_coef()[[1]]), 2), c(0, 1))
expect_equivalent(length(z.out$get_predict()[[1]]), n)
expect_equivalent(length(z.out$get_fitted()[[1]]), n)
expect_equivalent(dim(z.out$get_vcov()[[1]]), c(2, 2))
z.out$setx(x = 0)
z.out$setx1(x = 1)
show.setx <- summary(z.out)
z.out$sim()
show.sim <- summary(z.out)
expect_equivalent(length(z.out$get_qi(qi = "ev", xvalue = "x")), n)
expect_equivalent(round(mean(z.out$get_qi(qi = "ev", xvalue = "x")),
2), 0)
expect_equivalent(length(z.out$get_qi(qi = "ev", xvalue = "x1")),
n)
expect_equivalent(round(mean(z.out$get_qi(qi = "ev", xvalue = "x1")),
2), 1)
expect_equivalent(length(z.out$get_qi(qi = "pv", xvalue = "x")), n)
expect_equivalent(round(mean(z.out$get_qi(qi = "pv", xvalue = "x")),
2), 0)
expect_equivalent(length(z.out$get_qi(qi = "pv", xvalue = "x1")),
n)
expect_equivalent(round(mean(z.out$get_qi(qi = "pv", xvalue = "x1")),
2), 1)
expect_equivalent(length(z.out$get_qi(qi = "fd", xvalue = "x1")),
n)
expect_equivalent(round(mean(z.out$get_qi(qi = "fd", xvalue = "x1")), 2), 1)
expect_false(show.setx[[1]])
expect_false(show.sim[[1]])
expect_true(is.null(plot(z.out)))
xseq <- seq(from = 0, to = 1, length = 10)
z.out$setrange(x = xseq)
z.out$sim()
expect_true(is.null(plot(z.out)))
myref <- capture.output(z.out$references())
expect_equivalent(substr(myref[1], 1, 11), "R Core Team")
set.seed(123)
boot.out <- zelig(y ~ x, model = "ls", bootstrap = 20, data = mydata)
expect_equivalent(round(as.numeric(boot.out$get_coef()[[1]]), 2),
c(0, 1))
show.boot <- summary(boot.out, bagging = TRUE)
expect_false(show.boot[[1]])
show.boot <- summary(boot.out, subset=2:3)
expect_false(show.boot[[1]])
set.seed(123)
mi.out <- zelig(y ~ x, model = "ls", data = mi(mydata, mydata2))
expect_equivalent(round(as.numeric(mi.out$get_coef()[[1]]), 2), c(0,
1))
expect_equivalent(round(as.numeric(mi.out$get_coef()[[2]]), 2), c(-2,
1))
expect_equivalent(length(mi.out$toJSON()), 1)
show.mi <- summary(mi.out)
expect_false(show.mi[[1]])
show.mi.subset <- summary(mi.out, subset = 1)
expect_false(show.mi.subset[[1]])
})
# REQUIRE TEST Binary QI's and ATT effects and BY argument-------------
test_that('REQUIRE TEST Binary QIs and ATT effects and BY argument', {
set.seed(123)
# Simulate data
n <- 100
xx <- rbinom(n = n, size = 1, prob = 0.5)
zz <- runif(n)
ss <- runif(n)
rr <- rbinom(n, size = 1, prob = 0.5)
mypi <- 1/ (1+exp(-xx -3*zz -0.5))
yb <- rbinom(n, size = 1, prob = mypi)
data <- data.frame(rr, ss, xx, zz, yb)
# Estimate Zelig Logit models
zb.out <- zlogit$new()
zb.out$zelig(yb ~ xx + zz, data=data, by="rr")
show.logit <- summary(zb.out)
expect_false(show.logit[[1]])
zb2.out <- zlogit$new()
zb2.out$zelig(yb ~ xx, data=data)
zb3.out <- zlogit$new()
zb3.out$zelig(yb ~ xx + zz, data=data)
x.high <- setx(zb.out, xx = quantile(data$xx, prob = 0.75))
x.low <- setx(zb.out, xx = quantile(data$xx, prob = 0.25))
s.out <- sim(zb.out, x = x.high, x1 = x.low)
show.logit <- summary(s.out)
expect_false(show.logit[[1]])
expect_true(is.null(plot(s.out)))
# Method to calculate ATT
zb.out$ATT(treatment = "xx")
# Getter to extract ATT
out <- zb.out$get_qi(qi="ATT", xvalue="TE")
expect_equal(length(out), 1000)
# Plot ROC
expect_true(is.null(rocplot(zb2.out, zb3.out)))
})
# REQUIRE TEST for get_names method----------------------------------------------
test_that('REQUIRE TEST for names field', {
z <- zls$new()
z$zelig(Fertility ~ Education, data = swiss)
expect_is(z$get_names(), class = 'character')
expect_false(is.null(names(z)))
})
# REQUIRE TEST for get_residuals method -----------------------------------------
test_that('REQUIRE TEST for get_residuals method', {
z <- zls$new()
z$zelig(Fertility ~ Education, data = swiss)
expect_is(z$get_residuals(), class = 'list')
expect_false(is.null(residuals(z)))
})
# REQUIRE TEST for get_df_residual method -----------------------------------------
test_that('REQUIRE TEST for get_df_residual method', {
z <- zls$new()
z$zelig(Fertility ~ Education, data = swiss)
expect_equal(length(z$get_df_residual()), 1)
expect_equal(length(df.residual(z)), 1)
})
# REQUIRE TEST for get_model_data method ---------------------------------------
test_that('REQUIRE TEST for get_model_data method', {
z <- zls$new()
z$zelig(Fertility ~ Education, data = swiss)
expect_is(z$get_model_data(), class = 'data.frame')
})
# REQUIRE TEST for get_pvalue method ---------------------------------------
test_that('REQUIRE TEST for get_pvalue', {
z <- zls$new()
z$zelig(Fertility ~ Education, data = swiss)
expect_is(z$get_pvalue()[[1]], class = 'numeric')
expect_equal(z$get_pvalue()[[1]], get_pvalue(z)[[1]])
})
# REQUIRE TEST for get_se method ---------------------------------------
test_that('REQUIRE TEST for get_se', {
z <- zls$new()
z$zelig(Fertility ~ Education, data = swiss)
expect_is(z$get_se()[[1]], class = 'numeric')
expect_equal(z$get_se()[[1]], get_se(z)[[1]])
})
# REQUIRE TEST setx with logical covariates ------------------------------------
test_that('REQUIRE TEST setx with logical covariates', {
swiss$maj_catholic <- cut(swiss$Catholic, breaks = c(0, 51, 100))
swiss$maj_catholic_logical <- FALSE
swiss$maj_catholic_logical[swiss$maj_catholic == '(51,100]'] <- TRUE
z5l <- zls$new()
z5l$zelig(Fertility ~ Education + maj_catholic_logical, data = swiss)
z5l$setx(maj_catholic_logical = TRUE)
expect_is(z5l$setx.out$x, class = c("rowwise_df", "tbl_df", "tbl",
"data.frame"))
})
# REQUIRE TESTS for standard R methods with zelig models -----------------------
test_that('REQUIRE TESTS for standard R methods with zelig models', {
z5 <- zls$new()
z5$zelig(Fertility ~ Education, data = swiss)
expect_equal(length(coefficients(z5)), length(coef(z5)), 2)
expect_equal(nrow(vcov(z5)[[1]]), 2)
expect_equal(length(fitted(z5)[[1]]), 47)
expect_equal(length(predict(z5)[[1]]), 47)
})
|
1d0ea848a7196da5b2ec953baf8190dfbac720ae
|
609ea58450b0f00105e7fcb81e9c336ababbe041
|
/Belgium_done.R
|
6e8156235b43c3294a3fd91329cf4992c2a843da
|
[] |
no_license
|
pabbarros/TheImpactOfDemocratisationEpisodesOnEconomicGrowth
|
865ed59554b30f240e725960f63e82739386d223
|
083b5cd8fd67b00ee8828d915c73ef7238a3d516
|
refs/heads/main
| 2023-08-26T14:10:45.926162
| 2021-09-22T10:18:16
| 2021-09-22T10:18:16
| 408,583,660
| 0
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 36,842
|
r
|
Belgium_done.R
|
rm(list = ls())
#### DATA - ALL DATABASES ######
library(readr)
library(readxl)
library(tidyverse)
library(dplyr)
library(SciViews)
library(reshape2)
library(Synth)
library(data.table)
library(xtable)
ERT <- read.csv("ERT.csv")
dem <- read_excel("dem.xlsx")
ep_study <- read_excel("ep_study.xlsx")
colnames(dem)[2]<-"country_name"
db <- read_excel("db.xlsx")
db$year <- as.integer(db$year)
db1 <- read_excel("db1.xlsx")
countrycode <- (unique(db1[,"countrycode"]))
countrycode <- data.frame(countrycode)
countrycode[,"codenum"] <- 1:141
db1 <- merge(db1, countrycode, by="countrycode")
db1$year <- as.integer(db1$year)
db1$primary_barro <- as.integer(db1$primary_barro)
db1$secondary_barro <- as.integer(db1$secondary_barro)
##### CONTROLS #####
#Belgium in Europe
source("controls_w.R")
belgium <- controls(dem, ep_study, c="BEL")
belgium_ <- data.frame(Reduce(rbind, belgium))
belgium_ <- belgium_[!(is.na(belgium_$country_text_id)),]
belgium_c <- unique(belgium_$country_name)
belgium_in <- belgium_[belgium_$Continent_Name=="Europe",]
belgium_in <- belgium_in[!(is.na(belgium_in$country_text_id)),]
belgium_in_c <- unique(belgium_in$country_name)
belgium_in_c <- c(belgium_in_c, "Belgium")
belgium_c <- c(belgium_c, "Belgium")
#####IN EUROPE ####
db <- db1[which(db1$country %in% belgium_in_c),]
db <- db[db$year>1933 & db$year<1955,]
table(db$codenum)
db <- db[which((db$codenum %in% c(11,49,104,107))),]
dataprep.out <- dataprep(
foo = db,
predictors = c("child_mort", "popg") ,
predictors.op = c("mean"),
time.predictors.prior = 1934:1943 ,
special.predictors = list(
list("averagegdppc", seq(1935, 1940,5), "mean"),
#list("primary_barro", seq(1935, 1940,5), "mean"),
list("ggdp", 1938:1943, "mean")
),
dependent = "ggdp",
unit.variable = "codenum",
unit.names.variable = "countrycode",
time.variable = "year",
treatment.identifier = 11,
controls.identifier = c(49,104,107),
time.optimize.ssr = 1934:1943,
time.plot = 1934:1954)
# Inspeção das matrizes X1 e Z1, ou seja, da matriz das caracterÃÂ?sitcas da observação tratada e da
# matriz das observações da variável de resultado da tratada no perÃÂ?odo pré-tratamento, repectivamente.
dataprep.out$X1
dataprep.out$Z1
# Correr a função synth() (que optimiza a função de perda encadeada para os pesos W e V)
synth.out <- synth(dataprep.out)
# Extração dos resultados da optimização feita pela função synth(). Replicação parcial da Tabela 3.
synth.tables <- synth.tab(dataprep.res = dataprep.out, synth.res = synth.out)
synth.tables$tab.w
synth.tables$tab.pred
# Replicação da Figura 1
Y1 <- dataprep.out$Y1
Y1synth <- dataprep.out$Y0 %*% synth.out$solution.w
plot(1934:1954, Y1, ylim=c(-25,25), type="l", xlab = "Year", ylab = "Finland GDP per capita growth rate")
lines(1934:1954, Y1synth, type="l", lty=2)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_IN.png")
path.plot(synth.res = synth.out, dataprep.res = dataprep.out,
Ylab = "Real GDP per capita Growth Rate", Xlab = "Year",
Ylim = c(-26, 102), Legend = c("Belgium",
"Synthetic Belgium"), Legend.position = "bottomright")
abline(v=c(1944), col=c("black"), lwd=c(2))
dev.off()
xtable(synth.tables$tab.w)
xtable(synth.tables$tab.pred)
###PLACEBOS
dataprep.out.plac <- dataprep(
foo = db,
predictors = c("child_mort", "popg") ,
predictors.op = c("mean"),
time.predictors.prior = 1934:1943 ,
special.predictors = list(
list("averagegdppc", seq(1935, 1940,5), "mean"),
#list("primary_barro", seq(1935, 1940,5), "mean"),
list("ggdp", 1938:1943, "mean")
),
dependent = "ggdp",
unit.variable = "codenum",
unit.names.variable = "countrycode",
time.variable = "year",
treatment.identifier = 49,
controls.identifier = c(104,107),
time.optimize.ssr = 1934:1943,
time.plot = 1934:1954)
# Inspeção das matrizes X1 e Z1, ou seja, da matriz das caracterÃÂ?sitcas da observação tratada e da
# matriz das observações da variável de resultado da tratada no perÃÂ?odo pré-tratamento, repectivamente.
dataprep.out.plac$X1
dataprep.out.plac$Z1
# Correr a função synth() (que optimiza a função de perda encadeada para os pesos W e V)
synth.out.plac <- synth(dataprep.out.plac)
# Extração dos resultados da optimização feita pela função synth(). Replicação parcial da Tabela 3.
synth.tables.plac <- synth.tab(dataprep.res = dataprep.out.plac, synth.res = synth.out.plac)
synth.tables.plac$tab.w
synth.tables.plac$tab.pred
# Replicação da Figura 1
Y1plac <- dataprep.out.plac$Y1
Y1synthplac <- dataprep.out.plac$Y0 %*% synth.out.plac$solution.w
plot(1934:1954, Y1plac, ylim=c(-25,45), type="l", xlab = "Year", ylab = "Italy GDP per capita growth rate")
lines(1934:1954, Y1synthplac, type="l", lty=2)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_IN_PLC1.png")
path.plot(synth.res = synth.out.plac, dataprep.res = dataprep.out.plac,
Ylab = "Real GDP per capita Growth Rate", Xlab = "Year",
Ylim = c(-20, 60), Legend = c("Greece",
"Synthetic Greece"), Legend.position = "bottomright")
dev.off()
dataprep.out.plac2 <- dataprep(
foo = db,
predictors = c("child_mort", "popg") ,
predictors.op = c("mean"),
time.predictors.prior = 1934:1943 ,
special.predictors = list(
list("averagegdppc", seq(1935, 1940,5), "mean"),
#list("primary_barro", seq(1935, 1940,5), "mean"),
list("ggdp", 1938:1943, "mean")
),
dependent = "ggdp",
unit.variable = "codenum",
unit.names.variable = "countrycode",
time.variable = "year",
treatment.identifier = 107,
controls.identifier = c(49,104),
time.optimize.ssr = 1934:1943,
time.plot = 1934:1954)
# Inspeção das matrizes X1 e Z1, ou seja, da matriz das caracterÃÂ?sitcas da observação tratada e da
# matriz das observações da variável de resultado da tratada no perÃÂ?odo pré-tratamento, repectivamente.
dataprep.out.plac2$X1
dataprep.out.plac2$Z1
# Correr a função synth() (que optimiza a função de perda encadeada para os pesos W e V)
synth.out.plac2 <- synth(dataprep.out.plac2)
# Extração dos resultados da optimização feita pela função synth(). Replicação parcial da Tabela 3.
synth.tables.plac2 <- synth.tab(dataprep.res = dataprep.out.plac2, synth.res = synth.out.plac2)
synth.tables.plac2$tab.w
synth.tables.plac2$tab.pred
# Replicação da Figura 1
Y12 <- dataprep.out.plac2$Y1
Y1synth2 <- dataprep.out.plac2$Y0 %*% synth.out.plac2$solution.w
plot(1934:1954, Y12, ylim=c(-40,160), type="l", xlab = "Year", ylab = "ESP GDP per capita growth rate")
lines(1934:1954, Y1synth2, type="l", lty=2)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_IN_PLC2.png")
path.plot(synth.res = synth.out.plac2, dataprep.res = dataprep.out.plac2,
Ylab = "Real GDP per capita Growth Rate", Xlab = "Year",
Ylim = c(-40, 170), Legend = c("Romania",
"Synthetic Romania"), Legend.position = "topleft")
dev.off()
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_IN_ALL.png")
plot(1934:1954, Y1, ylim=c(-30,50), type="l", xlab = "Year", ylab = "Real GDP per capita Growth Rate", col="red", lwd=c(2))
lines(1934:1954, Y1plac, type="l", lty=2, col="blue")
lines(1934:1954, Y12, type="l", lty=2, col="blue4")
#lines(1934:1954, Y13, type="l", lty=2, col="blue3")
legend("topleft", legend = c("Belgium", "Greece", "Romania"),
col = c("red", "blue", "blue4"), lty = c(1,2,2), cex = 0.8)
abline(v=c(1944), col=c("black"), lwd=c(2))
dev.off()
#####DENSITY####
effects<- as.data.frame(Y1 - Y1synth)
effects <- cbind(newColName = rownames(effects), effects)
colnames(effects)<-c("year", "country")
effects[,'years']<-1:21
effects['placebo1'] <- (Y1plac - Y1synthplac)
effects['placebo2'] <- (Y12 - Y1synth2)
#effects['placebo3'] <- (Y13 - Y1synth3)
std <- as.data.frame(effects[effects$years>11, "year"])
colnames(std) <- "year"
std['years']<- 12:21
mean_country <- sum(effects[effects$years>11,'country'])/10
mean_p1 <- sum(effects[effects$years>11,'placebo1'])/10
mean_p2 <- sum(effects[effects$years>11,'placebo2'])/10
#mean_p3 <- sum(effects[effects$years>11,'placebo3'])/10
for (i in 1:10){
std[i,'country'] <- (effects[effects$year==std[i,'year'],'country']-mean_country)^2
std[i,'placebo1'] <- (effects[effects$year==std[i,'year'],'placebo1']-mean_p1)^2
std[i,'placebo2'] <- (effects[effects$year==std[i,'year'],'placebo2']-mean_p2)^2
#std[i,'placebo3'] <- (effects[effects$year==std[i,'year'],'placebo3']-mean_p3)^2
}
std[11,'year']<- 'std_10'
std[11,'years']<- 'std_10'
std[11,'country'] <- sqrt(sum(na.omit(std$country))/(nrow(std)-2))
std[11,'placebo1'] <- sqrt(sum(na.omit(std$placebo1))/(nrow(std)-2))
std[11,'placebo2'] <- sqrt(sum(na.omit(std$placebo2))/(nrow(std)-2))
#std[11,'placebo3'] <- sqrt(sum(na.omit(std$placebo3))/(nrow(std)-2))
std[12,'year']<- 'std_2'
std[12,'years']<- 'std_2'
std[12,'country'] <- sqrt(sum(std[std$years<=13,'country'])/(13-11-1))
std[12,'placebo1'] <- sqrt(sum(std[std$years<=13,'placebo1'])/(13-11-1))
std[12,'placebo2'] <- sqrt(sum(std[std$years<=13,'placebo2'])/(13-11-1))
#std[12,'placebo3'] <- sqrt(sum(std[std$years<=13,'placebo3'])/(13-11-1))
std[13,'year']<- 'std_3'
std[13,'years']<- 'std_3'
std[13,'country'] <- sqrt(sum(std[std$years<=14,'country'])/(14-11-1))
std[13,'placebo1'] <- sqrt(sum(std[std$years<=14,'placebo1'])/(14-11-1))
std[13,'placebo2'] <- sqrt(sum(std[std$years<=14,'placebo2'])/(14-11-1))
#std[13,'placebo3'] <- sqrt(sum(std[std$years<=14,'placebo3'])/(14-11-1))
std[14,'year']<- 'std_4'
std[14,'years']<- 'std_4'
std[14,'country'] <- sqrt(sum(std[std$years<=15,'country'])/(15-11-1))
std[14,'placebo1'] <- sqrt(sum(std[std$years<=15,'placebo1'])/(15-11-1))
std[14,'placebo2'] <- sqrt(sum(std[std$years<=15,'placebo2'])/(15-11-1))
#std[14,'placebo3'] <- sqrt(sum(std[std$years<=15,'placebo3'])/(15-11-1))
std[15,'year']<- 'std_5'
std[15,'years']<- 'std_5'
std[15,'country'] <- sqrt(sum(std[std$years<=16,'country'])/(16-11-1))
std[15,'placebo1'] <- sqrt(sum(std[std$years<=16,'placebo1'])/(16-11-1))
std[15,'placebo2'] <- sqrt(sum(std[std$years<=16,'placebo2'])/(16-11-1))
#std[15,'placebo3'] <- sqrt(sum(std[std$years<=16,'placebo3'])/(16-11-1))
density <- as.data.frame(c("1year", "2year", "3year", "4year", "5year", "10year"))
colnames(density) <- "effect"
density[density$effect=="1year", "ATE_country"]<- effects[effects$years==12,"country"]
density[density$effect=="2year", "ATE_country"]<- sum(effects[effects$years==12 | effects$yearss==13,"country"])/2
density[density$effect=="3year", "ATE_country"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14,"country"])/3
density[density$effect=="4year", "ATE_country"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15,"country"])/4
density[density$effect=="5year", "ATE_country"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15 | effects$years==1911,"country"])/5
density[density$effect=="10year", "ATE_country"]<- sum(effects[effects$years>11,"country"])/(21-11)
density[density$effect=="1year", "ATE_placebo1"]<- effects[effects$years==12,"placebo1"]
density[density$effect=="2year", "ATE_placebo1"]<- sum(effects[effects$years==12 | effects$years==13,"placebo1"])/2
density[density$effect=="3year", "ATE_placebo1"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14,"placebo1"])/3
density[density$effect=="4year", "ATE_placebo1"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15,"placebo1"])/4
density[density$effect=="5year", "ATE_placebo1"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15 | effects$years==1911,"placebo1"])/5
density[density$effect=="10year", "ATE_placebo1"]<- sum(effects[effects$years>11,"placebo1"])/(21-11)
density[density$effect=="1year", "ATE_placebo2"]<- effects[effects$years==12,"placebo2"]
density[density$effect=="2year", "ATE_placebo2"]<- sum(effects[effects$years==12 | effects$years==13,"placebo2"])/2
density[density$effect=="3year", "ATE_placebo2"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14,"placebo2"])/3
density[density$effect=="4year", "ATE_placebo2"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15,"placebo2"])/4
density[density$effect=="5year", "ATE_placebo2"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15 | effects$years==1911,"placebo2"])/5
density[density$effect=="10year", "ATE_placebo2"]<- sum(effects[effects$years>11,"placebo2"])/(21-11)
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='10year','ATE_country'],
sd = std[std$years=='std_10', 'country']
)
norm_datap1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='10year','ATE_placebo1'],
sd = std[std$year=='std_10', 'placebo1']
)
norm_datap2 <-
rnorm(
n = 1000000,
mean = density[density$effect=='10year','ATE_placebo2'],
sd = std[std$year=='std_10', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_IN_DEN_10Y.png")
plot(density(norm_data),main = '10-years ATE Density ', col="red", xlim=c(-100,100), ylim=c(0, 0.015), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Greece ", "Romania "),
col = c("red", "blue", "green"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='5year','ATE_country'],
sd = std[std$year=='std_5', 'country']
)
norm_datap1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='5year','ATE_placebo1'],
sd = std[std$year=='std_5', 'placebo1']
)
norm_datap2 <-
rnorm(
n = 1000000,
mean = density[density$effect=='5year','ATE_placebo2'],
sd = std[std$year=='std_5', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_IN_DEN_5Y.png")
plot(density(norm_data),main = '5-years ATE Density ', col="red", xlim=c(-150,150), ylim=c(0, 0.015), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Greece ", "Romania "),
col = c("red", "blue", "green"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='4year','ATE_country'],
sd = std[std$year=='std_4', 'country']
)
norm_datap1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='4year','ATE_placebo1'],
sd = std[std$year=='std_4', 'placebo1']
)
norm_datap2 <-
rnorm(
n = 1000000,
mean = density[density$effect=='4year','ATE_placebo2'],
sd = std[std$year=='std_4', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_IN_DEN_4Y.png")
plot(density(norm_data),main = '4-years ATE Density ', col="red", xlim=c(-200,200), ylim=c(0, 0.01), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Greece ", "Romania "),
col = c("red", "blue", "green", "pink"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='3year','ATE_country'],
sd = std[std$year=='std_3', 'country']
)
norm_datap1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='3year','ATE_placebo1'],
sd = std[std$year=='std_3', 'placebo1']
)
norm_datap2 <-
rnorm(
n = 10000000,
mean = density[density$effect=='3year','ATE_placebo2'],
sd = std[std$year=='std_3', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_IN_DEN_3Y.png")
plot(density(norm_data),main = '3-years ATE Density ', col="red", xlim=c(-200,200), ylim=c(0, 0.015), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Greece ", "Romania "),
col = c("red", "blue", "green", "pink"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='2year','ATE_country'],
sd = std[std$year=='std_2', 'country']
)
norm_datap1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='2year','ATE_placebo1'],
sd = std[std$year=='std_2', 'placebo1']
)
norm_datap2 <-
rnorm(
n = 1000000,
mean = density[density$effect=='2year','ATE_placebo2'],
sd = std[std$year=='std_2', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_IN_DEN_2Y.png")
plot(density(norm_data),main = '2-years ATE Density ', col="red", xlim=c(-200,200), ylim=c(0, 0.01), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Greece ", "Romania "),
col = c("red", "blue", "green", "pink"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
##### IN WORLD ####
dbw <- db1[which(db1$country %in% belgium_c),]
dbw <- dbw[dbw$year>1933 & dbw$year<1955,]
table <- as.data.frame(table(dbw$codenum))
table <- table[table$Freq==21,]
c <- as.vector(table$Var1)
c <- as.numeric(c)
dbw <- dbw[which((dbw$codenum %in% c)),]
dataprep.outw <- dataprep(
foo = dbw,
predictors = c("child_mort", "popg") ,
predictors.op = c("mean"),
time.predictors.prior = 1934:1943 ,
special.predictors = list(
list("averagegdppc", seq(1935, 1940,5), "mean"),
#list("primary_barro", seq(1935, 1940,5), "mean"),
list("ggdp", 1938:1943, "mean")
),
dependent = "ggdp",
unit.variable = "codenum",
unit.names.variable = "countrycode",
time.variable = "year",
treatment.identifier = 11,
controls.identifier = c(5, 13, 16, 26, 28, 32, 38, 40, 49, 50, 54, 81, 90, 99,
101, 104, 107, 119, 137),
time.optimize.ssr = 1934:1943,
time.plot = 1934:1954)
# Inspeção das matrizes X1 e Z1, ou seja, da matriz das caracterÃÂ?sitcas da observação tratada e da
# matriz das observações da variável de resultado da tratada no perÃÂ?odo pré-tratamento, repectivamente.
dataprep.outw$X1
dataprep.outw$Z1
# Correr a função synth() (que optimiza a função de perda encadeada para os pesos W e V)
synth.outw <- synth(dataprep.outw)
# Extração dos resultados da optimização feita pela função synth(). Replicação parcial da Tabela 3.
synth.tablesw <- synth.tab(dataprep.res = dataprep.outw, synth.res = synth.outw)
synth.tablesw$tab.w
synth.tablesw$tab.pred
# Replicação da Figura 1
Y1w <- dataprep.outw$Y1
Y1synthw <- dataprep.outw$Y0 %*% synth.outw$solution.w
plot(1934:1954, Y1w, ylim=c(-20,25), type="l", xlab = "Year", ylab = "Finland GDP per capita growth rate")
lines(1934:1954, Y1synthw, type="l", lty=2)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL.png")
path.plot(synth.res = synth.outw, dataprep.res = dataprep.outw,
Ylab = "Real GDP per capita Growth Rate", Xlab = "Year",
Ylim = c(-15, 25), Legend = c("Belgium",
"Synthetic Belgium"), Legend.position = "bottomright")
abline(v=c(1944), col=c("black"), lwd=c(2))
dev.off()
xtable(synth.tablesw$tab.w)
xtable(synth.tablesw$tab.pred)
###PLACEBOS
dataprep.out.placw <- dataprep(
foo = dbw,
predictors = c("child_mort", "popg") ,
predictors.op = c("mean"),
time.predictors.prior = 1934:1943 ,
special.predictors = list(
list("averagegdppc", seq(1935, 1940,5), "mean"),
#list("primary_barro", seq(1935, 1940,5), "mean"),
list("ggdp", 1938:1943, "mean")
),
dependent = "ggdp",
unit.variable = "codenum",
unit.names.variable = "countrycode",
time.variable = "year",
treatment.identifier = 5,
controls.identifier = c(13, 16, 26, 28, 32, 38, 40, 49, 50, 54, 81, 90, 99,
101, 104, 107, 119, 137),
time.optimize.ssr = 1934:1943,
time.plot = 1934:1954)
# Inspeção das matrizes X1 e Z1, ou seja, da matriz das caracterÃÂ?sitcas da observação tratada e da
# matriz das observações da variável de resultado da tratada no perÃÂ?odo pré-tratamento, repectivamente.
dataprep.out.placw$X1
dataprep.out.placw$Z1
# Correr a função synth() (que optimiza a função de perda encadeada para os pesos W e V)
synth.out.placw <- synth(dataprep.out.placw)
# Extração dos resultados da optimização feita pela função synth(). Replicação parcial da Tabela 3.
synth.tables.placw <- synth.tab(dataprep.res = dataprep.out.placw, synth.res = synth.out.placw)
synth.tables.placw$tab.w
synth.tables.placw$tab.pred
# Replicação da Figura 1
Y1placw <- dataprep.out.placw$Y1
Y1synthplacw <- dataprep.out.placw$Y0 %*% synth.out.placw$solution.w
plot( 1934:1954, Y1placw, ylim=c(-10,10), type="l", xlab = "Year", ylab = "Italy GDP per capita growth rate")
lines( 1934:1954, Y1synthplacw, type="l", lty=2)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_PLC1.png")
path.plot(synth.res = synth.out.placw, dataprep.res = dataprep.out.placw,
Ylab = "Real GDP per capita Growth Rate", Xlab = "Year",
Ylim = c(-10, 15), Legend = c("Argentina",
"Synthetic Argentina"), Legend.position = "bottomleft")
dev.off()
dataprep.out.plac2w <- dataprep(
foo = dbw,
predictors = c("child_mort", "popg") ,
predictors.op = c("mean"),
time.predictors.prior = 1934:1943 ,
special.predictors = list(
list("averagegdppc", seq(1935, 1940,5), "mean"),
#list("primary_barro", seq(1935, 1940,5), "mean"),
list("ggdp", 1938:1943, "mean")
),
dependent = "ggdp",
unit.variable = "codenum",
unit.names.variable = "countrycode",
time.variable = "year",
treatment.identifier = 49,
controls.identifier = c(5, 13, 16, 26, 28, 32, 38, 40, 50, 54, 81, 90, 99,
101, 104, 107, 119, 137),
time.optimize.ssr = 1934:1943,
time.plot = 1934:1954)
# Inspeção das matrizes X1 e Z1, ou seja, da matriz das caracterÃÂ?sitcas da observação tratada e da
# matriz das observações da variável de resultado da tratada no perÃÂ?odo pré-tratamento, repectivamente.
dataprep.out.plac2w$X1
dataprep.out.plac2w$Z1
# Correr a função synth() (que optimiza a função de perda encadeada para os pesos W e V)
synth.out.plac2w <- synth(dataprep.out.plac2w)
# Extração dos resultados da optimização feita pela função synth(). Replicação parcial da Tabela 3.
synth.tables.plac2w <- synth.tab(dataprep.res = dataprep.out.plac2w, synth.res = synth.out.plac2w)
synth.tables.plac2w$tab.w
synth.tables.plac2w$tab.pred
# Replicação da Figura 1
Y12w <- dataprep.out.plac2w$Y1
Y1synth2w <- dataprep.out.plac2w$Y0 %*% synth.out.plac2w$solution.w
plot(1934:1954, Y12w, ylim=c(-15,35), type="l", xlab = "Year", ylab = "PTR GDP per capita growth rate")
lines(1934:1954, Y1synth2w, type="l", lty=2)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_PLC2.png")
path.plot(synth.res = synth.out.plac2w, dataprep.res = dataprep.out.plac2w,
Ylab = "Real GDP per capita Growth Rate", Xlab = "Year",
Ylim = c(-20, 50), Legend = c(" Greece",
"Synthetic Greece"), Legend.position = "topleft")
dev.off()
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_ALL.png")
plot(1934:1954, Y1w, ylim=c(-20,50), type="l", xlab = "Year", ylab = "GDP per capita growth rate", col="red", lwd=c(2))
lines(1934:1954, Y1placw, type="l", lty=2, col="blue")
lines(1934:1954, Y12w, type="l", lty=2, col="blue4")
legend("topleft", legend = c("Belgium", "Argentina", " Greece"),
col = c("red", "blue", "blue4"), lty = c(1,2,2), cex = 0.8)
abline(v=c(1944), col=c("black"), lwd=c(2))
dev.off()
#####DENSITY####
effects<- as.data.frame(Y1w - Y1synthw)
effects <- cbind(newColName = rownames(effects), effects)
colnames(effects)<-c("year", "country")
effects[,'years']<-1:21
effects['placebo1'] <- (Y1placw - Y1synthplacw)
effects['placebo2'] <- (Y12w - Y1synth2w)
#effects['placebo3'] <- (Y13w - Y1synth3w)
std <- as.data.frame(effects[effects$years>11, "year"])
colnames(std) <- "year"
std['years']<- 12:21
mean_country <- sum(effects[effects$years>11,'country'])/10
mean_p1 <- sum(effects[effects$years>11,'placebo1'])/10
mean_p2 <- sum(effects[effects$years>11,'placebo2'])/10
mean_p3 <- sum(effects[effects$years>11,'placebo3'])/10
for (i in 1:10){
std[i,'country'] <- (effects[effects$year==std[i,'year'],'country']-mean_country)^2
std[i,'placebo1'] <- (effects[effects$year==std[i,'year'],'placebo1']-mean_p1)^2
std[i,'placebo2'] <- (effects[effects$year==std[i,'year'],'placebo2']-mean_p2)^2
#std[i,'placebo3'] <- (effects[effects$year==std[i,'year'],'placebo3']-mean_p3)^2
}
std[11,'year']<- 'std_10'
std[11,'years']<- 'std_10'
std[11,'country'] <- sqrt(sum(na.omit(std$country))/(nrow(std)-2))
std[11,'placebo1'] <- sqrt(sum(na.omit(std$placebo1))/(nrow(std)-2))
std[11,'placebo2'] <- sqrt(sum(na.omit(std$placebo2))/(nrow(std)-2))
#std[11,'placebo3'] <- sqrt(sum(na.omit(std$placebo3))/(nrow(std)-2))
std[12,'year']<- 'std_2'
std[12,'years']<- 'std_2'
std[12,'country'] <- sqrt(sum(std[std$years<=13,'country'])/(13-11-1))
std[12,'placebo1'] <- sqrt(sum(std[std$years<=13,'placebo1'])/(13-11-1))
std[12,'placebo2'] <- sqrt(sum(std[std$years<=13,'placebo2'])/(13-11-1))
#std[12,'placebo3'] <- sqrt(sum(std[std$years<=13,'placebo3'])/(13-11-1))
std[13,'year']<- 'std_3'
std[13,'years']<- 'std_3'
std[13,'country'] <- sqrt(sum(std[std$years<=14,'country'])/(14-11-1))
std[13,'placebo1'] <- sqrt(sum(std[std$years<=14,'placebo1'])/(14-11-1))
std[13,'placebo2'] <- sqrt(sum(std[std$years<=14,'placebo2'])/(14-11-1))
#std[13,'placebo3'] <- sqrt(sum(std[std$years<=14,'placebo3'])/(14-11-1))
std[14,'year']<- 'std_4'
std[14,'years']<- 'std_4'
std[14,'country'] <- sqrt(sum(std[std$years<=15,'country'])/(15-11-1))
std[14,'placebo1'] <- sqrt(sum(std[std$years<=15,'placebo1'])/(15-11-1))
std[14,'placebo2'] <- sqrt(sum(std[std$years<=15,'placebo2'])/(15-11-1))
#std[14,'placebo3'] <- sqrt(sum(std[std$years<=15,'placebo3'])/(15-11-1))
std[15,'year']<- 'std_5'
std[15,'years']<- 'std_5'
std[15,'country'] <- sqrt(sum(std[std$years<=16,'country'])/(16-11-1))
std[15,'placebo1'] <- sqrt(sum(std[std$years<=16,'placebo1'])/(16-11-1))
std[15,'placebo2'] <- sqrt(sum(std[std$years<=16,'placebo2'])/(16-11-1))
#std[15,'placebo3'] <- sqrt(sum(std[std$years<=16,'placebo3'])/(16-11-1))
density <- as.data.frame(c("1year", "2year", "3year", "4year", "5year", "10year"))
colnames(density) <- "effect"
density[density$effect=="1year", "ATE_country"]<- effects[effects$years==12,"country"]
density[density$effect=="2year", "ATE_country"]<- sum(effects[effects$years==12 | effects$yearss==13,"country"])/2
density[density$effect=="3year", "ATE_country"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14,"country"])/3
density[density$effect=="4year", "ATE_country"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15,"country"])/4
density[density$effect=="5year", "ATE_country"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15 | effects$years==1911,"country"])/5
density[density$effect=="10year", "ATE_country"]<- sum(effects[effects$years>11,"country"])/(21-11)
density[density$effect=="1year", "ATE_placebo1"]<- effects[effects$years==12,"placebo1"]
density[density$effect=="2year", "ATE_placebo1"]<- sum(effects[effects$years==12 | effects$years==13,"placebo1"])/2
density[density$effect=="3year", "ATE_placebo1"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14,"placebo1"])/3
density[density$effect=="4year", "ATE_placebo1"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15,"placebo1"])/4
density[density$effect=="5year", "ATE_placebo1"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15 | effects$years==1911,"placebo1"])/5
density[density$effect=="10year", "ATE_placebo1"]<- sum(effects[effects$years>11,"placebo1"])/(21-11)
density[density$effect=="1year", "ATE_placebo2"]<- effects[effects$years==12,"placebo2"]
density[density$effect=="2year", "ATE_placebo2"]<- sum(effects[effects$years==12 | effects$years==13,"placebo2"])/2
density[density$effect=="3year", "ATE_placebo2"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14,"placebo2"])/3
density[density$effect=="4year", "ATE_placebo2"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15,"placebo2"])/4
density[density$effect=="5year", "ATE_placebo2"]<- sum(effects[effects$years==12 | effects$years==13| effects$years==14 | effects$years==15 | effects$years==1911,"placebo2"])/5
density[density$effect=="10year", "ATE_placebo2"]<- sum(effects[effects$years>11,"placebo2"])/(21-11)
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='10year','ATE_country'],
sd = std[std$years=='std_10', 'country']
)
norm_datap1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='10year','ATE_placebo1'],
sd = std[std$year=='std_10', 'placebo1']
)
norm_datap2 <-
rnorm(
n = 1000000,
mean = density[density$effect=='10year','ATE_placebo2'],
sd = std[std$year=='std_10', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_DEN_10Y.png")
plot(density(norm_data),main = '10-years ATE Density ', col="red", xlim=c(-40,40), ylim=c(0, 0.05), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Argentina", " Greece"),
col = c("red", "blue", "lightblue"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='5year','ATE_country'],
sd = std[std$year=='std_5', 'country']
)
norm_datap1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='5year','ATE_placebo1'],
sd = std[std$year=='std_5', 'placebo1']
)
norm_datap2 <-
rnorm(
n = 1000000,
mean = density[density$effect=='5year','ATE_placebo2'],
sd = std[std$year=='std_5', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_DEN_5Y.png")
plot(density(norm_data),main = '5-years ATE Density ', col="red", xlim=c(-50,50), ylim=c(0, 0.04), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Argentina", " Greece"),
col = c("red", "blue", "green"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='4year','ATE_country'],
sd = std[std$year=='std_4', 'country']
)
norm_data1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='4year','ATE_placebo1'],
sd = std[std$year=='std_4', 'placebo1']
)
norm_data2 <-
rnorm(
n = 1000000,
mean = density[density$effect=='4year','ATE_placebo2'],
sd = std[std$year=='std_4', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_DEN_4Y.png")
plot(density(norm_data),main = '4-years ATE Density ', col="red", xlim=c(-60,60), ylim=c(0, 0.03), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Argentina", " Greece"),
col = c("red", "blue", "green", "pink"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='3year','ATE_country'],
sd = std[std$year=='std_3', 'country']
)
norm_data1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='3year','ATE_placebo1'],
sd = std[std$year=='std_3', 'placebo1']
)
norm_data2 <-
rnorm(
n = 1000000,
mean = density[density$effect=='3year','ATE_placebo2'],
sd = std[std$year=='std_3', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_DEN_3Y.png")
plot(density(norm_data),main = '3-years ATE Density ', col="red", xlim=c(-60,60), ylim=c(0, 0.025), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Argentina", " Greece"),
col = c("red", "blue", "green", "pink"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
norm_data <-
rnorm(
n = 1000000,
mean = density[density$effect=='2year','ATE_country'],
sd = std[std$year=='std_2', 'country']
)
norm_datap1 <-
rnorm(
n = 1000000,
mean = density[density$effect=='2year','ATE_placebo1'],
sd = std[std$year=='std_2', 'placebo1']
)
norm_datap2 <-
rnorm(
n = 1000000,
mean = density[density$effect=='2year','ATE_placebo2'],
sd = std[std$year=='std_2', 'placebo2']
)
png(filename="C:/Users/paben/OneDrive/Ambiente de Trabalho/Tese/Final Data/Thesis/SCM-Countries/Tese/Img/BEL_DEN_2Y.png")
plot(density(norm_data),main = '2-years ATE Density ', col="red", xlim=c(-60,60), ylim=c(0, 0.025), lwd=c(2))
lines(density(norm_datap1), col='blue', lty=2)
lines(density(norm_datap2), col='green', lty=2)
#lines(density(norm_datap3), col='pink', lty=2)
legend("topleft", legend = c("Belgium", "Argentina", " Greece"),
col = c("red", "blue", "green"), lty = c(1,2,2,2), cex = 0.8)
abline(v=c(0), col=c("black"), lwd=c(2))
dev.off()
|
14cd11e9a7c8dd54eef1bc5047a8a61bf36b571a
|
a5d5f059a2cf7e8a1512f77ab518b467eba21fa6
|
/sup/OpenMORDM Supplemental Material Rev2/OpenMORDM/man/nsample.Rd
|
c13f097990e420f4090028047ef64435f8ad2c79
|
[] |
no_license
|
pedroliman/ie-mordm
|
450c6c77e4a40f47fb42d5490bbdd8bcb04877d2
|
2c66696a3d6b4353ad7d58e7f4a4b4e364c64250
|
refs/heads/master
| 2020-04-13T12:39:36.198755
| 2018-12-27T18:52:04
| 2018-12-27T18:52:04
| 163,208,793
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 547
|
rd
|
nsample.Rd
|
% Generated by roxygen2 (4.0.2): do not edit by hand
\name{nsample}
\alias{nsample}
\title{Generate normally distributed random inputs.}
\usage{
nsample(mean, sd, nsamples, problem)
}
\arguments{
\item{mean}{scalar or vector specifying the mean value for each decision
variable}
\item{sd}{scalar or vector specifying the standard deviation for each
decision variable}
\item{nsamples}{the number of samples to generate}
\item{problem}{the problem definition}
}
\description{
Generate normally distributed random inputs.
}
|
9833c216399c6080b2d10e8d372607c98a55aba3
|
d3ed21ee5797fbf7e00629e4a9490add83556484
|
/man/lambda-package.Rd
|
fc8278fc4b7b4ac6d5185b9a0b8d3f0b12e66b0e
|
[] |
no_license
|
isglobal-brge/lambda
|
b01f19feb69f750c63aecd35a2fea3ff231a42f6
|
37c2a3796ae771a9e0e7b6ed9c353599133eb292
|
refs/heads/master
| 2021-09-17T18:28:13.340573
| 2018-07-04T09:56:29
| 2018-07-04T09:56:29
| 86,354,557
| 1
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 712
|
rd
|
lambda-package.Rd
|
\name{lambda-package}
\alias{lambda-package}
\alias{lambda}
\docType{package}
\title{
Ageement measure lambda
~~ package title ~~
}
\description{
Computes the agreement measure between two experiments across numerous conditions
}
\details{
\tabular{ll}{
Package: \tab lambda\cr
Type: \tab Package\cr
Version: \tab 1.0\cr
Date: \tab 2018-03-07\cr
License: \tab What license is it under?\cr
}
The package is an implementation of the function:
lambda.agreement
}
\author{
A Caceres
Maintainer: A Caceres <alejandro.caceres@isglobal.org>
}
\references{
Caceres, A and Gonzalez JR, A measure of agreement across numerous conditions: Assessing when changes in network
connectivities across tissues are functional
}
|
68a17ef8a7a64b427d069fffb701e755aab1148c
|
8f0e229a51c03cb0c1c8a43f6f3ef8c863872376
|
/cachematrix.R
|
b9a442636dc6ee15dcd669e7269bf9f098125e10
|
[] |
no_license
|
patriciacrain/ProgrammingAssignment2
|
42d8dbba7edf6d77365ea004b89e1fdc67d7fa52
|
2798ec35776092bca68b0ebdc6ab1a8c8e52fa14
|
refs/heads/master
| 2021-01-17T04:52:25.233730
| 2014-04-25T17:27:03
| 2014-04-25T17:27:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,293
|
r
|
cachematrix.R
|
## These functions create a special kind of matrix which can be
## used to cache the inverse of a matrix rather than calculating it repeatedly.
## The makeCacheMatrix function creates a list of functions which cache the inverse of the matrix.
makeCacheMatrix <- function(x = matrix()) {
## Creates the inverse, initialized to NULL
inv <- NULL
##Creating the functions to get and set both the matrix and its inverse
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinverse <- function(inverse) inv <<- inverse
getinverse <- function() inv
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## The cacheSolve function computes the inverse of a matrix, unless the inverse of
## the matrix is already in the cache, in which case it returns the inverse from the cache.
cacheSolve <- function(x, ...) {
## Check to see if the inverse is already cached
inv <- x$getinverse()
## Return the cached inverse if it is there
if(!is.null(inv)) {
message("getting cached inverse")
return(inv)
}
## Since the inverse is not cached, calculate the inverse and cache it
data <- x$get()
inv <- solve(data, ...)
x$setinverse(inv)
## Return the newly calculated inverse
inv
}
|
45d7a617fd2f4d351f39a0c189ed77537466a98d
|
bb453317a3e4aae6f20ddfdcf3fd4b691bc12198
|
/man/plot_FV_post_norm_kmom.Rd
|
5f6640e1327dd73787e8c6be29e81762f3ce869c
|
[] |
no_license
|
fabriziomaturo/AnnuityRIR
|
252a81f85a1011dbb63e06b639c0d04798772082
|
6c15c17a2b9aabeb9a233cc7325a45b7d26b4f75
|
refs/heads/master
| 2021-08-14T19:05:01.087113
| 2017-11-16T14:49:05
| 2017-11-16T14:49:05
| 110,983,531
| 1
| 0
| null | null | null | null |
ISO-8859-1
|
R
| false
| false
| 1,141
|
rd
|
plot_FV_post_norm_kmom.Rd
|
\name{plot_FV_post_norm_kmom}
\encoding{WINDOWS-1252}
\alias{plot_FV_post_norm_kmom}
\title{Plot the final expected
value of an \eqn{n}-payment annuity, with payments of 1 unit each made
at the end of every year (annuity-immediate), valued at the rate
\eqn{X},
using the estimated moments of the normal distribution.
}
\usage{
plot_FV_post_norm_kmom(data,years,lwd,lty)
}
\arguments{\item{data}{ A vector of interest rates. }
\item{years}{ The number of years of the income. Default is 10 years. }
\item{lwd}{The width of the curve. Default is 1.5. }
\item{lty}{The style of the curve. Default is 1. }
}
\description{
Plot the final expected
value of an \eqn{n}-payment annuity, with payments of 1 unit each made
at the end of every year (annuity-immediate), valued at the rate
\eqn{X},
using the estimated moments of the normal distribution.
}
\author{
Salvador Cruz Rambaud, Fabrizio Maturo, Ana María Sánchez Pérez
}
\examples{
# example 1
data<-rnorm(n=30,m=0.03,sd=0.01)
plot_FV_post_norm_kmom(data,8)
# example 2
data<-rnorm(n=200,m=0.075,sd=0.2)
plot_FV_post_norm_kmom(data,8)
}
|
480de8efea5370498f859ff65446e6ade080b863
|
c66c6c157b77a75465d66f7fcf4451e298f18089
|
/tests/testthat/test_format.R
|
6f79d55828b01414a0a91230f75f1f00d64181ad
|
[
"MIT"
] |
permissive
|
ebenmichael/augsynth
|
0bad8bddc88b4004eab717006906cbaf797b849d
|
0db0db2fbbda899e1a8b729b85af76fb4cb148ae
|
refs/heads/master
| 2023-08-17T03:32:47.387205
| 2023-08-02T16:00:12
| 2023-08-02T16:00:12
| 155,753,448
| 109
| 53
|
MIT
| 2023-08-25T01:27:06
| 2018-11-01T17:45:11
|
R
|
UTF-8
|
R
| false
| false
| 3,110
|
r
|
test_format.R
|
context("Test data formatting")
library(Synth)
data(basque)
basque <- basque %>% mutate(trt = case_when(year < 1975 ~ 0,
regionno != 17 ~0,
regionno == 17 ~ 1)) %>%
filter(regionno != 1)
test_that("format_data creates matrices with the right dimensions", {
dat <- format_data(quo(gdpcap), quo(trt), quo(regionno), quo(year),1975, basque)
test_dim <- function(obj, d) {
expect_equivalent(dim(obj), d)
}
test_dim(dat$X, c(17, 20))
expect_equivalent(length(dat$trt), 17)
test_dim(dat$y, c(17, 23))
}
)
test_that("format_synth creates matrices with the right dimensions", {
dat <- format_data(quo(gdpcap), quo(trt), quo(regionno), quo(year),1975, basque)
syn_dat <- format_synth(dat$X, dat$trt, dat$y)
test_dim <- function(obj, d) {
expect_equivalent(dim(obj), d)
}
test_dim(syn_dat$Z0, c(20, 16))
test_dim(syn_dat$Z1, c(20, 1))
test_dim(syn_dat$Y0plot, c(43, 16))
test_dim(syn_dat$Y1plot, c(43, 1))
expect_equivalent(syn_dat$Z1, syn_dat$X1)
expect_equivalent(syn_dat$Z0, syn_dat$X0)
}
)
test_that("multisynth throws errors when there aren't enough pre-treatment times",
{
basque2 <- basque %>%
mutate(trt = case_when(
regionno == 16 ~ 1,
year >= 1975 & regionno == 17 ~ 1,
TRUE ~ 0)
) %>%
filter(regionno != 1)
# error from always treated unit
expect_warning(
expect_error(
multisynth(gdpcap ~ trt, regionno, year, basque2)
)
)
basque2 <- basque %>%
mutate(trt = case_when(
regionno == 16 & year >= 1956 ~ 1,
year >= 1975 & regionno == 17 ~ 1,
TRUE ~ 0)
) %>%
filter(regionno != 1)
# error from one pre-treatment outcome and fixedeff = T
expect_warning(
expect_error(multisynth(gdpcap ~ trt, regionno, year, basque2))
)
# no error from one pre-treatment outcome and fixedeff = F, just warning
expect_warning(multisynth(gdpcap ~ trt, regionno, year, basque2, fixedeff = F))
})
test_that("formatting for staggered adoption doesn't care about order of time in data",
{
basque2 <- basque %>%
# slice(sample(1:n())) %>%
mutate(trt = case_when((regionno == 17) & (year >= 1975) ~ 1,
(regionno == 16) & (year >= 1980) ~ 1,
TRUE ~ 0))
dat <- format_data_stag(quo(gdpcap), quo(trt), quo(regionno), quo(year), basque2)
# true treatment times
true_trt <- c(1975, 1980) - min(basque$year)
expect_equal(true_trt, sort(dat$trt[is.finite(dat$trt)]))
basque2 <- basque %>%
slice(sample(1:n())) %>%
mutate(trt = case_when((regionno == 17) & (year >= 1975) ~ 1,
(regionno == 16) & (year >= 1980) ~ 1,
TRUE ~ 0))
dat <- format_data_stag(quo(gdpcap), quo(trt), quo(regionno), quo(year), basque2)
expect_equal(true_trt, sort(dat$trt[is.finite(dat$trt)]))
})
|
3679195f2f769ce7ae006b9d39a98369f5a190d5
|
f46b9e716ea5f2a47a4759e7f0116bc9c88129de
|
/R/methylation_scores.R
|
8d5e4fd51fad70f04e24b5d879d52a2f18abde6a
|
[
"Unlicense"
] |
permissive
|
hhhh5/ewastools
|
e18c59ee1a9678f1a87ee3101f555e0aab601e1b
|
f7646cacd73266708479b3fea5d625054d179f95
|
refs/heads/master
| 2023-09-01T13:03:01.281328
| 2023-02-14T06:00:19
| 2023-02-14T06:00:19
| 116,701,843
| 29
| 11
|
Unlicense
| 2023-02-09T07:08:01
| 2018-01-08T16:39:21
|
R
|
UTF-8
|
R
| false
| false
| 2,455
|
r
|
methylation_scores.R
|
#' Various methylation scores
#'
#'
#' @rdname MethylationScores
#' @param beta matrix of beta values
#' @param model Name of the model, i.e., one of `maternal_smoking`, `gestational_age`, or `horvath_clock`
#'
methylation_score = function(beta,model){
if(model=="cord_blood:maternal_smoking"){
### model based on Table S5 from Reese et al. (2017) available at doi.org/10.1289/EHP333
markers = data.table(
probe_id = c("cg02256631","cg02482603","cg04103532","cg04180046","cg04506190","cg05549655","cg05575921","cg08698721","cg09743950","cg10799846","cg12186702","cg13834112","cg13893782","cg14179389","cg14351425","cg14633298","cg14743346","cg17397069","cg19381766","cg22154659","cg22802102","cg23304605","cg25189904","cg25949550","cg26764244","cg27291468")
,coef = c(-0.191,2.706,1.786,14.027,2.318,6.210,-10.909,1.142,-6.330,-4.963,3.847,1.514,-0.963,-6.304,6.361,5.050,2.286,-2.912,5.245,-0.773,-0.254,0.011,-3.903,-46.991,-0.246,0.836)
)
i = match(markers$probe_id,rownames(beta))
y = beta[i,]
y = y * markers$coef
y = colSums(y,na.rm=TRUE)
return(y)
}else if(model=="cord_blood:gestational_age"){
### doi.org/10.1186/s13059-016-1068-z
markers = system.file(paste0("data/13059_2016_1068_MOESM3_ESM.csv"),package="ewastools")
markers = fread(markers)
setnames(markers,1:2,c("probe_id","coef"))
markers = markers[-1]
i = match(markers$probe_id,rownames(beta))
y = beta[i,]
y = y * markers$coef
y = colSums(y,na.rm=TRUE)
y = y + 41.72579759
return(y)
}else if(model=="placenta:gestational_age"){
### https://doi.org/10.18632/aging.102049
markers = system.file(paste0("data/102049-SupFile1.csv"),package="ewastools")
markers = fread(markers)
setnames(markers,1:2,c("probe_id","coef"))
markers = markers[-1]
i = match(markers$probe_id,rownames(beta))
y = beta[i,]
y = y * markers$coef
y = colSums(y,na.rm=TRUE)
y = y + 24.99772133
return(y)
}else if(model=="horvath_clock"){
### model based on https://doi.org/10.1186/gb-2013-14-10-r115
markers = system.file(paste0("data/horvath_clock.csv"),package="ewastools")
markers = fread(markers,header=TRUE)
i = match(markers$probe_id,rownames(beta))
y = beta[i,]
y = y * markers$coef
y = colSums(y,na.rm=TRUE)
y = y + 0.695507258
inverse_transformation <- function(x,adult.age=20) { ifelse(x<0, (1+adult.age)*exp(x)-1, (1+adult.age)*x+adult.age) }
return(inverse_transformation(y))
}else return(NULL)
}
|
2644744048cce434ef9d8c2bc42b856c32b5a8e0
|
2baed5a8a605c42d1e8ba05a341ac1ef63bcfeb2
|
/scripts/01-datasets/01-real/helpers-download_from_sources/dataset_planaria-plass.R
|
6f0870d1a6dc578c80579bfd60975e1b081dc0bd
|
[
"MIT"
] |
permissive
|
dynverse/dynbenchmark
|
0c58ef1a9909b589b1cd8b0a0e69c2fa222aeb2b
|
8dca4eb841b8ce6edfb62d37ff6cfd4c974af339
|
refs/heads/master
| 2022-12-08T04:01:13.746186
| 2022-11-25T08:25:50
| 2022-11-25T08:25:50
| 102,579,801
| 171
| 40
| null | 2019-04-07T20:59:59
| 2017-09-06T07:53:11
|
R
|
UTF-8
|
R
| false
| false
| 1,858
|
r
|
dataset_planaria-plass.R
|
library(dynbenchmark)
library(tidyverse)
dataset_preprocessing("real/silver/whole-schmidtea-mediterranea_plass")
# get settings
source(paste0(dynbenchmark::get_dynbenchmark_folder(), "/scripts/01-datasets/01-real/helpers-download_from_sources/helper_planaria-plass.R"))
# counts
counts_file <- download_dataset_source_file(
"dge.txt.gz",
"http://bimsbstatic.mdc-berlin.de/rajewsky/PSCA/dge.txt.gz"
)
counts_file_unzipped <- gsub("\\.gz", "", counts_file)
read_lines(counts_file) %>% {.[[1]] <- paste0("\"gene\"\t", .[[1]]); .} %>% write_lines(counts_file_unzipped)
counts_all <- read_tsv(counts_file_unzipped) %>%
as.data.frame() %>%
column_to_rownames("gene") %>%
as.matrix() %>%
t
# cell info
cell_info_file <- download_dataset_source_file(
"R_annotation.txt",
"http://bimsbstatic.mdc-berlin.de/rajewsky/PSCA/R_annotation.txt"
)
cell_info_all <- tibble(group_id = read_lines(cell_info_file))
cell_info_all$cell_id <- rownames(counts_all)
for (setting in settings) {
print(setting$id)
milestone_network <- setting$milestone_network
milestone_ids <- unique(c(milestone_network$from, milestone_network$to))
if (!all(milestone_ids %in% cell_info_all$group_id)) {stop(setdiff(milestone_ids, cell_info_all$group_id))}
if (!"length" %in% names(milestone_network)) milestone_network$length <- 1
milestone_network$length[is.na(milestone_network$length)] <- TRUE
if (!"directed" %in% names(milestone_network)) milestone_network$directed <- TRUE
milestone_network$directed[is.na(milestone_network$directed)] <- TRUE
cell_info <- cell_info_all %>%
filter(group_id %in% milestone_ids)
grouping <- cell_info %>%
select(cell_id, group_id) %>%
deframe()
counts <- counts_all[names(grouping), ]
save_raw_dataset(
lst(
milestone_network,
grouping,
cell_info,
counts
),
setting$id)
}
|
b264d171b50947a170d594367e341e08053963cb
|
4e838c6d530ce49fb79f37eba659ec15f0efce4b
|
/butterfat/butterfat.R
|
552bcf9ddc01f809f8a5d4c6055c68d91a31d2e9
|
[] |
no_license
|
amromeo/learnR
|
5d2fe303f2857f62388b1245c91a0185a6c302af
|
8af7c861c71a1c8baa13e4cead4585bbadbcb70d
|
refs/heads/master
| 2020-12-30T09:58:52.396605
| 2017-08-15T00:50:59
| 2017-08-15T00:50:59
| 99,250,020
| 0
| 1
| null | 2017-08-03T15:51:52
| 2017-08-03T15:51:51
| null |
UTF-8
|
R
| false
| false
| 392
|
r
|
butterfat.R
|
bwplot(Butterfat ~ Age, data=butterfat)
lm1 = lm(Butterfat ~ Age, data=butterfat)
coef(lm1)
bwplot(Butterfat ~ Breed, data=butterfat)
lm2 = lm(Butterfat ~ Breed, data=butterfat)
coef(lm2)
lm3 = lm(Butterfat ~ Breed + Age, data=butterfat)
coef(lm3)
lm4 = lm(Butterfat ~ Breed + Age + Breed:Age, data=butterfat)
coef(lm4)
anova(lm3)
# Balanced design
xtabs(~Breed + Age, data=butterfat)
|
cd4bb9b4e866785479687273dda2cd53c70b78c8
|
ab9315145932e1d0edcb1b52df1cc3ed078a317c
|
/tests/testthat.R
|
e60123a6ea4ee29849654028dd0c4b67f4412248
|
[] |
no_license
|
johnchower/flashreport
|
cfcbefc1afe5d77da6857ae21323d48ed3a6db96
|
c23dca38331dc9632c251983a2db59cf95dae664
|
refs/heads/master
| 2020-07-28T12:31:42.252620
| 2017-05-03T16:39:10
| 2017-05-03T16:39:10
| 73,411,648
| 0
| 0
| null | 2017-05-03T20:53:11
| 2016-11-10T18:54:18
|
R
|
UTF-8
|
R
| false
| false
| 66
|
r
|
testthat.R
|
library(testthat)
library(flashreport)
test_check("flashreport")
|
414230cbc1c82d5aab086dc176b2d614fa0f75e9
|
9e6884df4d8f0e26355026761393e3bb47c4b7e8
|
/mcri/scThyroidcluster.R
|
c13f832094bcae77540cc6fbc45a7dac3aa04c07
|
[] |
no_license
|
Shicheng-Guo/GscRbasement
|
f965ecc6e191175f371aa1edeae81e5c545f1759
|
8d599bed0dd8b61b455f97965c0f4bed5aae2e96
|
refs/heads/master
| 2022-05-01T09:20:23.072449
| 2022-03-13T18:46:04
| 2022-03-13T18:46:04
| 62,922,944
| 1
| 1
| null | null | null | null |
UTF-8
|
R
| false
| false
| 8,651
|
r
|
scThyroidcluster.R
|
setwd("~/hpc/methylation/Pancancer/RNA-seq")
source("https://raw.githubusercontent.com/Shicheng-Guo/GscRbasement/master/GscTools.R")
library("metafor")
library("meta")
library("metacor")
load("~/hpc/methylation/Pancancer/RNA-seq/rnaseqdata.pancancer.RData")
Symbol2ENSG<-function(Symbol){
db<-read.table("https://raw.githubusercontent.com/Shicheng-Guo/AnnotationDatabase/master/ENSG.ENST.ENSP.Symbol.hg19.bed",sep="\t")
ENSG<-as.character(db[match(Symbol,db$V4),8])
ENSG<-na.omit(data.frame(Symbol,ENSG))
return(ENSG)
}
ENSG2Symbol<-function(ENSG){
db<-read.table("https://raw.githubusercontent.com/Shicheng-Guo/AnnotationDatabase/master/ENSG.ENST.ENSP.Symbol.hg19.bed",sep="\t")
ENSG<-unlist(lapply(strsplit(ENSG,split="[.]"),function(x) x[1]))
Symbol<-db[match(as.character(ENSG),db$V8),4]
return(Symbol)
}
ensg2bed<-function(ENSG){
db<-read.table("https://raw.githubusercontent.com/Shicheng-Guo/AnnotationDatabase/master/hg19/ENSG.ENST.hg19.txt",as.is=T,head=F)
ENSG<-unlist(lapply(strsplit(ENSG,split="[.]"),function(x) x[1]))
bed<-unique(db[db$V5 %in% as.character(ENSG),c(1,2,3,5)])
return(bed)
}
GSIMethDecon<-function(data){
data<-data.matrix(data)
group=names(table(colnames(data)))
index=colnames(data)
gsi<-gmaxgroup<-avebase<-c()
for(i in 1:nrow(data)){
gsit<-0
gmax<-names(which.max(tapply(as.numeric(data[i,]),index,function(x) mean(x,na.rm=T))))
for(j in 1:length(group)){
tmp<-(1-10^(mean(data[i,][which(index==group[j])],na.rm=T))/10^(mean(data[i,][which(index==gmax)],,na.rm=T)))/(length(group)-1)
gsit<-gsit+tmp
}
ave<-tapply(data[i,], index, function(x) mean(x,na.rm=T))
gmaxgroup<-c(gmaxgroup,gmax)
gsi<-c(gsi,gsit)
avebase<-rbind(avebase,ave)
}
rlt=data.frame(region=rownames(data),group=gmaxgroup,GSI=gsi,AVE=avebase)
return(rlt)
}
gsi<-function(data){
group=names(table(colnames(data)))
index=colnames(data)
GSI<-c()
gmaxgroup<-c()
for(i in 1:nrow(data)){
gsit<-0
gmax<-names(which.max(tapply(as.numeric(data[i,]),index,function(x) mean(x,na.rm=T))))
if(length(gmax)<1){print(data[i,])}
for(j in 1:length(group)){
tmp<-(1-10^(mean(na.omit(as.numeric(data[i,which(index==group[j])])),na.rm=T))/10^(mean(na.omit(as.numeric(data[i,which(index==gmax)])))))/(length(group)-1)
gsit<-c(gsit,tmp)
}
gmaxgroup<-c(gmaxgroup,gmax)
GSI<-c(GSI,sum(gsit,na.rm=T)) # debug for GSI=NAN
}
rlt=data.frame(region=rownames(data),group=gmaxgroup,GSI=GSI)
return(rlt)
}
HeatMap<-function(data,Rowv=T,Colv=T){
# note: this function include correlation based heatmap (pearson or spearman)
# data: row is gene and column is sample
# colname and rowname cannot be NULL
# Usage example:
# test<- matrix(runif(100),nrow=20)
# colnames(test)=c("A","A","A","B","B")
# rownames(test)=paste("Gene",1:20,sep="")
# HeatMap(test)
library("gplots")
colors <- colorpanel(75,"midnightblue","mediumseagreen","yellow")
colors <-bluered(75)
sidecol<-function(x){
x<-as.numeric(as.factor(x))
col<-rainbow(length(table(colnames(data))))
sapply(x,function(x) col[x])
}
Hclust=function(x){hclust(x,method="complete")}
Distfun=function(x){as.dist((1 - cor(t(x),method = "spearman")))}
ColSideColors=sidecol(colnames(data))
heatmap.2(data,trace="none",
hclust=Hclust,
distfun=Distfun,
cexRow = 0.5, cexCol = 0.5,
ColSideColors=ColSideColors,
density.info="none",col=colors,
Colv=Colv,Rowv = Rowv,
keysize=0.9, margins = c(5, 10)
)
}
TCGAProjects=c("BLCA","BRCA","CESC","CHOL","COAD","ESCA","GBM","HNSC","KICH","KIRC","KIRP","LIHC","LUAD","LUSC","PAAD","PCPG","PRAD","READ","SARC","STAD","THCA","THYM","UCEC")
TCGAProjects=c("THCA")
phen1=read.table("~/hpc/methylation/TCGA-clinical-11093.tsv",header = T,sep="\t")
phen2=read.table("~/hpc/methylation/Pancancer/RNA-seq/File_metadata2.txt",header = T,sep="\t")
head(phen1)
head(phen2)
colnames(rnaseqdata)<-unlist(lapply(strsplit(colnames(rnaseqdata),"/"),function(x) x[2]))
phen<-data.frame(phen2,phen1[match(phen2$cases.0.case_id,phen1$case_id),])
phen$file_name=gsub(".gz","",phen$file_name)
# prepare phenotype information
phen<-phen[match(colnames(rnaseqdata),phen$file_name),]
phen$phen4<-id2phen4(phen$cases.0.samples.0.submitter_id)
phen$phen3<-id2phen3(phen$cases.0.samples.0.submitter_id)
phen$phen2<-id2bin(phen$cases.0.samples.0.submitter_id)
phen$pid<-phen$project_id
head(phen)
idx<-which(phen$phen2==1)
phen<-phen[idx,]
input<-rnaseqdata[,idx]
idx<-which(phen$pid %in% paste("TCGA-",TCGAProjects,sep=""))
phen<-phen[idx,]
input<-input[,idx]
input[1:5,1:5]
input<-log(input+1,2)
input<-RawNARemove(input)
input<-RawZeroRemove(input)
input[1:5,1:5]
colnames(input)<-phen$cases.0.submitter_id
input[1:5,1:5]
############################################################################################################
### GSI and HEATMAP (scRNA-seq)
setwd("/home/local/MFLDCLIN/guosa/hpc/project/thyroid/scRNA")
data<-read.csv("https://raw.githubusercontent.com/Shicheng-Guo/thyroidscrna/master/extdata/scTCGA2019.csv")
# data$Manual_Type.according.to.SC.seq
# match(colnames(input),data$Patient_barcode)
# data$Patient_barcode[which(! data$Patient_barcode %in% colnames(input))]
newinput<-input[,which(colnames(input) %in% data$Patient_barcode)]
sctype<-data[match(colnames(newinput),data$Patient_barcode),]$Manual_Type.according.to.SC.seq
colnames(newinput)<-sctype
newinput<-newinput[,order(colnames(newinput))]
rlt<-GSIMethDecon(newinput)
xsel<-subset(rlt,GSI>0.99)
matrix<-newinput[match(xsel[order(xsel$group),1],rownames(newinput)),]
library("gplots")
pdf("heatmap2.pdf")
heatmap.2(scale(matrix),Rowv=NA,Colv=NA)
dev.off()
library("gplots")
pdf("heatmap2.pdf")
heatmap.2(scale(matrix),Rowv=F,Colv=F,keysize=1, density.info="none",trace="none")
dev.off()
pdf("heatmap4.pdf")
HeatMap(scale(matrix),Rowv=T,Colv=F)
dev.off()
pdf("heatmap6.pdf")
HeatMap(matrix,Rowv=F,Colv=F)
dev.off()
pdf("heatmap7.pdf")
HeatMap(scale(matrix),Rowv=F,Colv=F)
dev.off()
############################################################################################################
### GSI and HEATMAP to DNA methylation beta matrix
setwd("/home/local/MFLDCLIN/guosa/hpc/project/thyroid/scRNA")
sam<-read.csv("https://raw.githubusercontent.com/Shicheng-Guo/thyroidscrna/master/extdata/scTCGA2019.csv")
# data$Manual_Type.according.to.SC.seq
# match(colnames(input),data$Patient_barcode)
# data$Patient_barcode[which(! data$Patient_barcode %in% colnames(input))]
load("/home/guosa/hpc/methylation/Pancancer/methdata.pancancer.RData")
source("https://raw.githubusercontent.com/Shicheng-Guo/GscRbasement/master/GscTools.R")
id2phen4<-function(filename){
library("stringr")
as.array(str_extract(filename,"TCGA-[0-9|a-z|A-Z]*-[0-9|a-z|A-Z]*-[0-9]*"))
}
id2phen3<-function(filename){
library("stringr")
as.array(str_extract(filename,"TCGA-[0-9|a-z|A-Z]*-[0-9|a-z|A-Z]*"))
}
id2bin<-function(filename){
library("stringr")
filename<-as.array(str_extract(filename,"TCGA-[0-9|a-z|A-Z]*-[0-9|a-z|A-Z]*-[0-9]*"))
as.numeric(lapply(strsplit(filename,"-"),function(x) x[4]))
}
input<-methdata
phen2<-id2bin(colnames(input))
input<-input[,which(phen2==1)]
phen3<-id2phen3(colnames(input))
input<-input[,match(sam$Patient_barcode,phen3)]
colnames(input)<-id2phen3(colnames(input))
newinput<-RawNARemove(input)
newinput<-RawZeroRemove(newinput)
colnames(newinput)<-colnames(input)
sctype<-sam[match(colnames(newinput),sam$Patient_barcode),]$Manual_Type.according.to.SC.seq
colnames(newinput)<-sctype
newinput<-newinput[,order(colnames(newinput))]
rlt<-GSIMethDecon(newinput)
xsel<-subset(rlt,GSI>0.43)
dim(xsel)
matrix<-newinput[match(xsel[order(xsel$group),1],rownames(newinput)),]
save(matrix,file="scRNA-thryoid-tcga-methylation.RData")
setwd("~/hpc/project/thyroid/scRNA")
library("gplots")
pdf("meth-heatmap2.pdf")
heatmap.2(scale(matrix),Rowv=NA,Colv=NA)
dev.off()
library("gplots")
pdf("meth-heatmap3.pdf")
heatmap.2(scale(matrix),Rowv=F,Colv=F,keysize=1, density.info="none",trace="none")
dev.off()
pdf("meth-heatmap4.pdf")
HeatMap(scale(na.omit(matrix)),Rowv=T,Colv=F)
dev.off()
pdf("meth-heatmap5.pdf")
HeatMap(matrix,Rowv=F,Colv=F,)
dev.off()
pdf("meth-heatmap6.pdf")
HeatMap(scale(matrix),Rowv=F,Colv=F)
dev.off()
|
ef911c4eee4eb8fb49d27dcdd48efb0d7e0393ae
|
37805035a6f36ac225ebf20026209b50184f8b4d
|
/processSurveys.R
|
45038e5d4714a5f0083f623d10f12e020be17b57
|
[
"MIT"
] |
permissive
|
dwulff/dwulff.github.io
|
fbabcac6173898ae5a9d2d1e077094e325043953
|
089804b3df53ca3499e92cb92d8e60ca6f6419f9
|
refs/heads/master
| 2021-01-18T12:12:32.532553
| 2018-11-13T08:27:23
| 2018-11-13T08:27:23
| 68,724,311
| 0
| 3
| null | null | null | null |
UTF-8
|
R
| false
| false
| 645
|
r
|
processSurveys.R
|
options(stringsAsFactors = F)
require(googlesheets)
setwd('~/Dropbox (2.0)/Work/Software/dwulff.github.io/')
goodchoices = read.table('_Goodchoices/GoodchoicesSurveys.txt',header=F,sep='\n')[,1]
networks = read.table('_Networks/NetworksSurveys.txt',header=F,sep='\n')[,1]
#tab = paste0(networks[10],' (Antworten)')
tab = paste0(goodchoices[11],' (Antworten)')
gs = gs_title(tab)
d = gs_read(gs)
d = as.data.frame(d)
# networks
names = d[,3]
comp = unlist(d[,4:6])
crit = unlist(d[,7:9])
for(com in comp) cat(com,'\n\n')
for(cri in crit) cat(cri,'\n\n')
comp[grepl('die Wörter gelernt',comp)]
crit[grepl('die Wörter gelernt',crit)]
|
3d88be484f645cbf46a8d4091d76f047fe910f0a
|
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
|
/data/genthat_extracted_code/FSTpackage/examples/FST.prelim.Rd.R
|
7bc4843e37fe876cdda64845c769b073a78f7631
|
[] |
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
| 600
|
r
|
FST.prelim.Rd.R
|
library(FSTpackage)
### Name: FST.prelim
### Title: The preliminary data management for FST (functional score tests)
### Aliases: FST.prelim
### Keywords: preliminary work
### ** Examples
library(FSTpackage)
# Load data example
# Y: outcomes, n by 1 matrix where n is the total number of observations
# X: covariates, n by d matrix
# G: genotype matrix, n by p matrix where n is the total number of subjects
# Z: functional annotation matrix, p by q matrix
data(FST.example)
Y<-FST.example$Y;X<-FST.example$X;G<-FST.example$G
# Preliminary data management
result.prelim<-FST.prelim(Y,X=X)
|
99153ae39ecfa797d633abf20e3083875f513418
|
e4119d40fe082fce021731457061ec399f158d8e
|
/ui.R
|
987f548d9e96a618ddb336d5d3f42b8d15514759
|
[] |
no_license
|
musarder/shiny-myapp
|
4bd422fb956c785049eb773beebc1a9c4d5a519d
|
f62fb052a78fe014e7ab724a77b0e153f5f38cde
|
refs/heads/master
| 2021-01-10T06:51:56.103455
| 2016-02-28T15:07:00
| 2016-02-28T15:07:00
| 52,726,457
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 478
|
r
|
ui.R
|
library(shiny)
# Define UI for dataset viewer application
shinyUI(pageWithSidebar(
# Application title
headerPanel("Air Pollution in China"),
# Sidebar with controls to select a city
sidebarPanel(
selectInput("city", "Choose a city:",
choices = c("Beijing", "Shanghai", "Tianjin", "Xiamen", "Chongqing", "Hangzhou"))),
# Show a plot of the air pollution of the chosen city
mainPanel(
plotOutput("plot_c")
)
))
|
aa65e0789d5f6f74b45cf12d79ff68beec18ecb4
|
9f2a64b71a9888f6a1e7d7bdd3c941131f6a5005
|
/man/plotCRM.Rd
|
d8318e33ee2f4d1af2e5754d18b412ba57ab32a6
|
[] |
no_license
|
cran/EstCRM
|
b2ae3dd49a1a30540a8bfb23d7fc6bfa0881dc7d
|
c46090d13106c3840fdd076ae66274caa04bd8da
|
refs/heads/master
| 2022-09-25T16:16:35.107516
| 2022-09-16T20:46:10
| 2022-09-16T20:46:10
| 17,679,047
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,208
|
rd
|
plotCRM.Rd
|
\name{plotCRM}
\alias{plotCRM}
\title{
Draw Three-Dimensional Item Category Response Curves
}
\description{
This function draws the 3D item category response curves given the item parameter matrix and the maximum and minimum possible values that examinees can get as a score for the item. This 3D representation is an extension of 2D item category response curves in binary and polytomous IRT models. Due to the fact that there are many possible response categories, another dimension is drawn for the response categories in the 3D representation.
}
\usage{
plotCRM(ipar, item, min.item, max.item)
}
\arguments{
\item{ipar}{
a matrix with \emph{m} rows and three columns, with \emph{m} denoting the number of items. The first column is the \emph{a} parameters, the second column is the \emph{b} parameters, and the third column is the \emph{alpha} parameters
}
\item{item}{
item number, an integer between 1 and \emph{m} with \emph{m} denoting the number of items
}
\item{min.item}{
a vector of length \emph{m} indicating the minimum possible score for each item.
}
\item{max.item}{
a vector of length \emph{m} indicating the maximum possible score for each item.
}
}
\value{
\item{irf}{ a 3D theoretical item category response curves}
}
\author{
Cengiz Zopluoglu
}
\seealso{
\code{\link{EstCRMitem}} for estimating item parameters,
\code{\link{EstCRMperson}} for estimating person parameters,
\code{\link{fitCRM}} for computing item-fit residual statistics and drawing empirical 3D item category response curves,
\code{\link{simCRM}} for generating data under CRM.
}
\examples{
\dontrun{
##load the dataset EPIA
data(EPIA)
##Define the vectors "max.item" and "min.item". The maximum possible
##score was 112 and the minimum possible score was 0 for all items
min.item <- c(0,0,0,0,0)
max.item <- c(112,112,112,112,112)
##Estimate item parameters
CRM <- EstCRMitem(EPIA, max.item, min.item, max.EMCycle = 500, converge = 0.01)
par <- CRM$param
##Draw theoretical item category response curves for Item 2
plotCRM(par,2,min.item, max.item)
}
}
|
320977b3a9c445ac01a0024ae16810f4689559fd
|
1a8a95fc74b655288b46c9ee16b77ff9e6e48bfa
|
/Capstone Data Wrangling.R
|
5f4f51d2acb9acf17fc1ea07c99d102028d03ec4
|
[] |
no_license
|
colemanGH319/Springboard-Capstone-Project-Foundations-
|
535ce3e869dc881b910428a732beb4e27f419d54
|
a9b98e843ccf51ca010389659c4f0b2fc8d0efcb
|
refs/heads/master
| 2021-01-01T16:09:44.953205
| 2017-09-14T17:28:51
| 2017-09-14T17:28:51
| 97,783,189
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 9,621
|
r
|
Capstone Data Wrangling.R
|
#1.Loading data and packages
library(dplyr)
library(tidyr)
library(ggplot2)
library(caTools)
library(caret)
loans14 <- read.csv("LoanStats3c.csv")
loans15 <- read.csv("LoanStats3d.csv")
#Lending Club offers a table with definitions for each column header from
#the loan dataset. This will be useful for renaming columns to make them more
#readily understandable. Definitions have been imported below:
definitions <- read.csv("LCDataDictionary.csv")
definitions$LoanStatNew <- as.character(definitions$LoanStatNew)
definitions$Description <- as.character(definitions$Description)
#Create a simple function to research variable definitions (example: loan_status)
define.var <- function(x) {
definitions[definitions$LoanStatNew == x,]
}
define.var("loan_status")
#Combine the data prior to wrangling
loans <- rbind(loans14, loans15)
#2.Wrangling the loan data.
summary(loans)
sapply(loans, function(x) {mean(is.na(x))}) %>%
hist(breaks = 50)
#Reviewing the output from the summary called above, it looks like some variables
#contain little or no data. Let's discard them any column that's less than 15%
#populated with actual data.
emptycols <- c()
for(i in 1:ncol(loans)) {
if(mean(is.na(loans[,i])) > 0.85) {
emptycols <- c(emptycols, i)
}
}
loans[,emptycols] <- NULL
#This got rid of 37 columns.
summary(loans)
#There are a number of other variables with missing values. Let's start by
#looking at months since last delinquency:
summary(loans$mths_since_last_delinq)
#Roughly half of the rows in this column are missing values. Since a lower
#value for this variable most likely corresponds to a higher potential for
#defaulting, we don't want to set this to zero, nor do we want to assume these
#borrowers fall in the middle of the distribution. In all likelihood, a missing
#value indicates that the borrower has never had a delinquency. Imputing values
#here may be too complex a task, so instead I will create a new column that
#simply denotes whether a borrower has any delinquencies in their history.
loans$ever_delinq <- ifelse(is.na(loans$mths_since_last_delinq), 0, 1)
#We can use the same logic for the number of months since most recent 90-day or
#worse rating. This variable has 467,000 missing values.
loans$derog_hist <- ifelse(is.na(loans$mths_since_last_major_derog), 0, 1)
summary(loans$avg_cur_bal)
#Average current balance only has 6 missing values. I will impute the value using
#the median of all current balances
loans <- loans %>% replace_na(list(avg_cur_bal = median(loans$avg_cur_bal, na.rm = TRUE)),
avg_cur_bal)
#I will use the same imputation method for bankcard open-to-buy and bankcard utilization
loans <- loans %>% replace_na(list(bc_open_to_buy = median(loans$bc_open_to_buy, na.rm = TRUE)),
bc_open_to_buy)
loans <- loans %>% replace_na(list(bc_util = median(loans$bc_util, na.rm = TRUE)), bc_util)
#Months since oldest bank installment account opened has 19,425 missing
#values. Since the credit report is looking back 7 years, an NA can be
#replaced with 7*12 months = 84 months.
loans <- loans %>% replace_na(list(mo_sin_old_il_acct = 84), mo_sin_old_il_acct)
#Months since most recent bankcard account opened has 6,044 missing values. An NA
#for this column most likely implies that they have never opened a bankcard account.
#Since only 1% of the data is missing here, the most straight forward method would be
#to use the median.
loans <- loans %>% replace_na(list(mths_since_recent_bc = median(loans$mths_since_recent_bc,
na.rm = TRUE)), mths_since_recent_bc)
summary(loans$mths_since_recent_bc_dlq)
mean(is.na(loans$mths_since_recent_bc_dlq))
#Months since most recent bankcard delinquency has NA's for 74% of its rows. This
#should be converted to a factor indicating any history of delinquency on a bankcard.
loans$bc_delinq_hist <- ifelse(is.na(loans$mths_since_recent_bc_dlq), 0, 1)
loans$bc_delinq_hist <- as.factor(loans$bc_delinq_hist)
summary(loans$mths_since_recent_inq)
loans$recent_inq <- ifelse(is.na(loans$mths_since_recent_inq), 0, 1)
summary(loans$mths_since_recent_revol_delinq)
loans$revol_delinq_hist <- ifelse(is.na(loans$mths_since_recent_revol_delinq), 0, 1)
summary(loans$num_tl_120dpd_2m)
unique(loans$num_tl_120dpd_2m)
#Number of accounts 120 days past due has only 5 unique values, not counting NA's.
#We can replace this column with a factor with 2 levels.
loans$acc_120dpd <- as.factor(ifelse(is.na(loans$num_tl_120dpd_2m), 0, 1))
summary(loans$percent_bc_gt_75)
#This is the percentage of bankcard accounts where spending has passed 75% of the
#card's limit. A missing value most likely indicates that the borrower does not
#have a bankcard. I will set these to zero.
loans <- loans %>%
replace_na(list(percent_bc_gt_75 = 0), percent_bc_gt_75)
summary(loans$num_rev_accts)
#An NA for number of revolving accounts presumably indicates that there are
#no revolving accounts in that borrower's credit history.
loans <- loans %>%
replace_na(list(num_rev_accts = 0), num_rev_accts)
#Multiple columns exist to denote loans that have incurred a hardship. These
#columns are nearly completely empty and can be removed.
loans$hardship_flag <- NULL
loans$hardship_type <- NULL
loans$hardship_reason <- NULL
loans$hardship_status <- NULL
loans$hardship_start_date <- NULL
loans$hardship_end_date <- NULL
#Interest rates are stored as a factor w/ 150 levels. These need to be
#converted to integers but the % symbol is causing issues with the as.numeric
#formula. Below is the workaround:
loans$int_rate <- as.character(loans$int_rate)
loans$int_rate <- gsub("%$", "", loans$int_rate)
loans$int_rate <- as.numeric(loans$int_rate)
#Employment title to character vector
loans$emp_title <- as.character(loans$emp_title)
summary(loans$emp_length)
#Employment length is a factor w/ 12 levels, one of which is "n/a". There are
#35,836 borrowers with employment length n/a.
summary(loans[loans$emp_length == "n/a", "annual_inc"])
#The median annual income for borrowers who listed employment length as "n/a"
#is $45,000. This may suggest that certain borrowers are earning income other
#than wages or salary and therefore left their employment information blank. I
#will collapse the employment length column from 12 levels to 11, converting
#the "n/a" level to true NA's. Then I will use this column in conjunction with
#a new column, "employment_listed".
loans$emp_length <- factor(loans$emp_length, levels = c("< 1 year", "1 year",
"2 years", "3 years",
"4 years", "5 years",
"6 years", "7 years",
"8 years", "9 years",
"10+ years"))
loans$employment_listed <- ifelse(is.na(loans$emp_length), 0, 1)
#Home ownership is currently a factor with 4 levels, one of which ("ANY") only
#has 3 records. Collapse to 3 levels.
loans$home_ownership <- factor(loans$home_ownership, levels = c("MORTGAGE",
"OWN",
"RENT"))
#The issue date of the loans is recorded in character format as abbreviated
#month and 2 digit year. I chose to split the year and month apart, replacing
#the year with 4-digit year (numeric) and the month with the full name of the
#month (factor)
loans$issue_year <- ifelse(grepl("14", loans$issue_d), 2014, 2015)
loans$issue_month <- loans$issue_d
loans$issue_month <- gsub(".*Jan.*", "January", loans$issue_month)
loans$issue_month <- gsub(".*Feb.*", "February", loans$issue_month)
loans$issue_month <- gsub(".*Mar.*", "March", loans$issue_month)
loans$issue_month <- gsub(".*Apr.*", "April", loans$issue_month)
loans$issue_month <- gsub(".*May.*", "May", loans$issue_month)
loans$issue_month <- gsub(".*Jun.*", "June", loans$issue_month)
loans$issue_month <- gsub(".*Jul.*", "July", loans$issue_month)
loans$issue_month <- gsub(".*Aug.*", "August", loans$issue_month)
loans$issue_month <- gsub(".*Sep.*", "September", loans$issue_month)
loans$issue_month <- gsub(".*Oct.*", "October", loans$issue_month)
loans$issue_month <- gsub(".*Nov.*", "November", loans$issue_month)
loans$issue_month <- gsub(".*Dec.*", "December", loans$issue_month)
unique(loans$issue_month)
loans$issue_month <- factor(loans$issue_month, levels = c("January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"))
summary(loans$issue_month)
#Convert loan descriptions to characters
loans$desc <- as.character(loans$desc)
#Create a "defaulted" column as a factor, where 1 indicates a default
loans <- loans %>%
mutate(defaulted = as.factor(loan_status == "Default" | loan_status == "Charged Off"))
nrow(loans[loans$defaulted == TRUE,])/nrow(loans)
summary(loans$defaulted)
summary(loans)
#The dataset is clean and we've created a response variable ("defaulted") that
#will be used in the logistic regression model.
write.csv(loans, file = "loans_clean.csv")
|
48119af67a9e2a124030ca4cd4742f165524d704
|
acd892099150ca5482399db8e88a0f5dbb731d75
|
/R/print.ggedit.R
|
4fff20b37090bef3ff34135f38ef53077f030e3b
|
[] |
no_license
|
DataXujing/ggedit
|
a30ecb4f47b2d4f9131b5cd0983b7d6504d60445
|
4a329cfe4ff3e099b2b389d84042bda64d61671b
|
refs/heads/master
| 2021-07-14T01:44:51.790528
| 2017-10-17T20:23:52
| 2017-10-17T20:23:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,797
|
r
|
print.ggedit.R
|
#' @title Print ggedit objects
#' @description Plots lists of ggplot2 plot objects
#' layout functionality.
#' @param x list of ggplot2 plot objects
#' @param ... list which defines the location of each plot within
#' the viewport layout. (see details)
#' @details If ... is NULL then a default layout is used filling in
#' a grid.layout row.wise. Defining plot.layout as a nested list giving
#' the rows and the column indicies of each plot will produce a specific layout.
#' @examples
#' p <- as.gglist(list(pList[[1]],pList[[2]]))
#' p
#'
#' p1 <- p+geom_hline(aes(yintercept=3))
#' p1
#'
#' print(p1,plot.layout = list(list(rows=2,cols=2),list(rows=1,cols=1:2)))
#'
#' @export
print.ggedit <- function(x,...){
plot.layout=NULL
l <- list(...)
list2env(l,envir = environment())
if( !is.null(x$UpdatedPlots) )
x <- x$UpdatedPlots
if( is.null(plot.layout) ){
plot.layout <- 1:length(x)
numPlots <- length(x)
cols <- min(numPlots,2)
plotCols <- cols
plotRows <- ceiling(numPlots/plotCols)
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(plotRows,plotCols)))
for (i in 1:numPlots) {
curRow <- ceiling(i/plotCols)
curCol <- (i-1) %% plotCols + 1
print(x[[i]], vp = vplayout(curRow, curCol))
}
}else{
numPlots <- length(x)
plotRows <- max(unlist(lapply(plot.layout,'[',1)))
plotCols <- max(unlist(lapply(plot.layout,'[',2)))
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(plotRows,plotCols)))
for (i in 1:numPlots) {
print(x[[i]], vp = vplayout(plot.layout[[i]]$rows, plot.layout[[i]]$cols))
}
}
}
|
ec588d4192fd88c94caf7af9d3a025ee106e2fbc
|
81b587b4ba6c0e5cc7da4b73bb7d5104ff5112e0
|
/R/explore_metadata.R
|
a563abc3cd2430061861ac79b7735ebedb6ed7ef
|
[
"MIT"
] |
permissive
|
gzahn/syringodium_bacteria
|
09bf99d1987e22407f79bf442a54adfffd3776c0
|
4bc89d345e5c4df2c37088ff5d216af4de29d822
|
refs/heads/main
| 2023-05-02T09:26:57.728802
| 2023-04-25T14:52:39
| 2023-04-25T14:52:39
| 584,835,022
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 674
|
r
|
explore_metadata.R
|
# load packages ####
library(tidyverse)
library(readxl)
source("./R/theme.R")
# read and clean metadata ####
meta <- read_xlsx("./data/SI_Indo_Metadata_CorrectGPS.xlsx") %>%
janitor::clean_names() %>%
rename("east_west" = "east_or_west_of_wallace_line") %>%
separate(gps,into = c("lat","lon"),sep=" ") %>%
mutate(lat=as.numeric(lat),
lon=as.numeric(lon)) %>%
select(-barcode) %>%
mutate(blank = grepl("^Blank",sample))
# clean up remaining "N/A" values
meta[meta == "N/A"] <- NA
# plots ####
meta %>%
filter(blank == FALSE) %>%
ggplot(aes(x=lon,y=lat,color=location)) +
geom_point(size=10) +
scale_color_manual(values=pal.discrete)
|
47d9f4d8b93991a52c6296df96b6ac450c1ed179
|
19c54dba01519328e58e21e348eae3638930d803
|
/man/phyloFromCtree.Rd
|
dc22020f2f70f44216ddb3ef0da6a29e60d4e621
|
[] |
no_license
|
jtmccr1/TransPhylo
|
724961ddcc1af0ccd0843ef99d92e722cac63681
|
181f975316286645e5f6a5179e1e925f1249f246
|
refs/heads/master
| 2020-05-20T12:34:55.313194
| 2019-05-30T10:14:33
| 2019-05-30T10:14:33
| 185,575,975
| 0
| 1
| null | 2019-05-08T09:35:26
| 2019-05-08T09:35:26
| null |
UTF-8
|
R
| false
| true
| 502
|
rd
|
phyloFromCtree.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/phyloFromCtree.R
\name{phyloFromCtree}
\alias{phyloFromCtree}
\title{Converts a phylogenetic tree into an ape phylo object with node.comments identifying the host of each node}
\usage{
phyloFromCtree(ctree)
}
\arguments{
\item{ctree}{combined tree}
}
\value{
phylo object
}
\description{
Converts a phylogenetic tree into an ape phylo object with node.comments identifying the host of each node
}
\seealso{
phyloFromPtree
}
|
63087a769545ec74d20c909d990a41b1653da46f
|
c750c1991c8d0ed18b174dc72f3014fd35e5bd8c
|
/pkgs/bayesm/man/rbprobitGibbs.Rd
|
10d7a02342b6f1b290a1c948010c49c58068f80e
|
[] |
no_license
|
vaguiar/EDAV_Project_2017
|
4b190e66fe7a6b4078cfe1b875bccd9b5a594b25
|
288ffaeec1cfdd873fe7439c0fa0c46a90a16a4f
|
refs/heads/base
| 2021-01-23T02:39:36.272851
| 2017-05-01T23:21:03
| 2017-05-01T23:21:03
| 86,010,131
| 1
| 0
| null | 2017-05-01T23:43:04
| 2017-03-24T00:21:20
|
HTML
|
UTF-8
|
R
| false
| false
| 2,136
|
rd
|
rbprobitGibbs.Rd
|
\name{rbprobitGibbs}
\alias{rbprobitGibbs}
\concept{bayes}
\concept{MCMC}
\concept{probit}
\concept{Gibbs Sampling}
\title{ Gibbs Sampler (Albert and Chib) for Binary Probit }
\description{
\code{rbprobitGibbs} implements the Albert and Chib Gibbs Sampler for the binary probit model.
}
\usage{
rbprobitGibbs(Data, Prior, Mcmc)
}
\arguments{
\item{Data}{ list(X,y)}
\item{Prior}{ list(betabar,A)}
\item{Mcmc}{ list(R,keep,nprint) }
}
\details{
Model: \eqn{z = X\beta + e}. \eqn{e} \eqn{\sim}{~} \eqn{N(0,I)}. y=1, if z> 0.
Prior: \eqn{\beta} \eqn{\sim}{~} \eqn{N(betabar,A^{-1})}.
List arguments contain
\describe{
\item{\code{X}}{Design Matrix}
\item{\code{y}}{n x 1 vector of observations, (0 or 1)}
\item{\code{betabar}}{k x 1 prior mean (def: 0)}
\item{\code{A}}{k x k prior precision matrix (def: .01I)}
\item{\code{R}}{ number of MCMC draws }
\item{\code{keep}}{ thinning parameter - keep every keepth draw (def: 1)}
\item{\code{nprint}}{ print the estimated time remaining for every nprint'th draw (def: 100)}
}
}
\value{
\item{betadraw }{R/keep x k array of betadraws}
}
\references{ For further discussion, see \emph{Bayesian Statistics and Marketing}
by Rossi, Allenby and McCulloch, Chapter 3. \cr
\url{http://www.perossi.org/home/bsm-1}
}
\author{ Peter Rossi, Anderson School, UCLA,
\email{perossichi@gmail.com}.
}
\seealso{ \code{\link{rmnpGibbs}} }
\examples{
##
## rbprobitGibbs example
##
if(nchar(Sys.getenv("LONG_TEST")) != 0) {R=2000} else {R=10}
set.seed(66)
simbprobit=
function(X,beta) {
## function to simulate from binary probit including x variable
y=ifelse((X\%*\%beta+rnorm(nrow(X)))<0,0,1)
list(X=X,y=y,beta=beta)
}
nobs=200
X=cbind(rep(1,nobs),runif(nobs),runif(nobs))
beta=c(0,1,-1)
nvar=ncol(X)
simout=simbprobit(X,beta)
Data1=list(X=simout$X,y=simout$y)
Mcmc1=list(R=R,keep=1)
out=rbprobitGibbs(Data=Data1,Mcmc=Mcmc1)
summary(out$betadraw,tvalues=beta)
if(0){
## plotting example
plot(out$betadraw,tvalues=beta)
}
}
\keyword{ models }
|
2196dcc8220a0415ed6c5f9b01d64a2cba8599d9
|
2c170474a479f0582d1685a8df22ca98dd157798
|
/R/helper.R
|
02e8cf4e84dcc1fa887f8d1a76523bfc0286a352
|
[] |
no_license
|
wcmbishop/gogoplot
|
80574a1161a44222265f9478d891ac6d4a696033
|
1857b750305c15a9bb90dfdb12b96230c14a0ff8
|
refs/heads/master
| 2021-03-27T17:13:16.813628
| 2018-03-30T18:08:07
| 2018-03-30T18:08:07
| 106,642,044
| 3
| 2
| null | 2018-03-30T18:08:08
| 2017-10-12T03:53:19
|
R
|
UTF-8
|
R
| false
| false
| 253
|
r
|
helper.R
|
select_choices <- function(.data) {
# name choices with: "name (type)"
var_types <- vapply(.data, tibble::type_sum, character(1))
x <- c(CONST_NONE, names(var_types))
names(x) <- c("none", sprintf("%s (%s)", names(var_types), var_types))
x
}
|
358d99ccf8a1fe5b53dae5c7e41e50e999c970d2
|
3d3f11d6002a505483003a59e0a94264ddd86757
|
/R/lqa.update2.R
|
f13fba36e16d1299dba33a49815a23a053a4ae18
|
[] |
no_license
|
cran/lqa
|
75a867677d54e2e1b84dbe90822628adf42e6238
|
fb0b5a6a7e8ce9028ac5f48adee8ffa8b3434d0b
|
refs/heads/master
| 2020-06-03T14:21:37.296678
| 2010-07-12T00:00:00
| 2010-07-12T00:00:00
| 17,697,200
| 2
| 2
| null | null | null | null |
UTF-8
|
R
| false
| false
| 3,123
|
r
|
lqa.update2.R
|
lqa.update2 <-
function (x, y, family = NULL, penalty = NULL, intercept = TRUE, weights = rep (1, nobs), control = lqa.control (), initial.beta, mustart, eta.new, gamma1 = 1, ...)
{
gamma <- gamma1
if (is.null (family))
stop ("lqa.update: family not specified")
if (is.null (penalty))
stop ("lqa.update: penalty not specified")
if (!is.null (dim (y)))
stop ("lqa.update: y must be a vector")
x <- as.matrix (x)
converged <- FALSE
n.iter <- control$max.steps
eps <- control$conv.eps
c1 <- control$c1
stop.at <- n.iter
p <- ncol (x)
nobs <- nrow (x)
converged <- FALSE
beta.mat <- matrix (0, nrow = n.iter, ncol = p) # to store the coefficient updates
if (missing (initial.beta))
initial.beta <- rep (0.01, p)
else
eta.new <- drop (x %*% initial.beta)
if (missing (mustart))
{
etastart <- drop (x %*% initial.beta)
eval (family$initialize)
}
if (missing (eta.new))
eta.new <- family$linkfun (mustart) # predictor
for (i in 1 : n.iter)
{
beta.mat[i,] <- initial.beta
mu.new <- family$linkinv (eta.new) # fitted values
d.new <- family$mu.eta (eta.new) # derivative of response function
v.new <- family$variance (mu.new) # variance function of the response
weights <- d.new / sqrt (v.new) # decomposed elements (^0.5) of weight matrix W, see GLM notation
x.star <- weights * x
y.tilde.star <- weights * (eta.new + (y - mu.new) / d.new)
A.lambda <- get.Amat (initial.beta = initial.beta, penalty = penalty, intercept = intercept, c1 = c1, x = x, ...)
p.imat.new <- crossprod (x.star) + A.lambda # penalized information matrix
chol.pimat.new <- chol (p.imat.new) # applying cholesky decomposition for matrix inversion
inv.pimat.new <- chol2inv (chol.pimat.new) # inverted penalized information matrix
beta.new <- gamma * drop (inv.pimat.new %*% t (x.star) %*% y.tilde.star) + (1 - gamma) * beta.mat[i,] # computes the next iterate of the beta vector
if ((sum (abs (beta.new - initial.beta)) / sum (abs (initial.beta)) <= eps)) # check convergence condition
{
converged <- TRUE
stop.at <- i
if (i < n.iter)
break
}
else
{
initial.beta <- beta.new # update beta vector
eta.new <- drop (x %*% beta.new)
}
}
Hatmat <- x.star %*% inv.pimat.new %*% t (x.star)
tr.H <- sum (diag (Hatmat))
dev.m <- sum (family$dev.resids (y, mu.new, weights))
aic.vec <- dev.m + 2 * tr.H
bic.vec <- dev.m + log (nobs) * tr.H
if (!converged & (stop.at == n.iter))
cat ("lqa.update with ", penalty$penalty, ": convergence warning! (lambda = ", penalty$lambda, ")\n")
fit <- list (coefficients = beta.new, beta.mat = beta.mat[1 : stop.at,], tr.H = tr.H, fitted.values = mu.new, family = family, Amat = A.lambda, converged = converged, stop.at = stop.at, m.stop = stop.at, linear.predictors = eta.new, weights = weights^2, p.imat = p.imat.new, inv.pimat = inv.pimat.new, x.star = x.star, v.new = v.new)
}
|
a18ea8debf937a586d72540741ec3ecd9a7b74fd
|
b6f0c3c44642b22a7338f8f45baf704ca2bcaf81
|
/run_analysis.R
|
1902fb21f1033b4aa8c9f257eaa2b2b3892d5e8f
|
[] |
no_license
|
LiuyinC/GettingClearingDataAssignment
|
0bd5027e1f92fefab90720e6d20ea01fa64f82a5
|
95aa8d82468ab408875cb439e03613dda24071d8
|
refs/heads/master
| 2021-01-10T22:10:13.753229
| 2014-05-23T22:05:05
| 2014-05-23T22:05:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,723
|
r
|
run_analysis.R
|
## Read Training data with Y label as the first column, subject lable as second column
Training <- cbind(read.table("./UCI HAR Dataset/train/y_train.txt"),
read.table("./UCI HAR Dataset/train/subject_train.txt"),
read.table("./UCI HAR Dataset/train/X_train.txt"))
## Read Testing data with Y label as the first column, subject lable as second column
Testing <-cbind(read.table("./UCI HAR Dataset/test/y_test.txt"),
read.table("./UCI HAR Dataset/test/subject_test.txt"),
read.table("./UCI HAR Dataset/test/X_test.txt"))
## Combine the training and testing data into one data frame with
## first column being Y label.
ActDataRow <- rbind(Training, Testing)
## Figure our which feature vectors contain "mean()" and "std()"
## and generate a indicator vector MeanStdlist to extract desired
## measurements.
features <- read.table("./UCI HAR Dataset/features.txt")
MeanStdlist <- sort(c(grep("mean()", features[1:561,2]),
grep("std()", features[1:561,2]))) + 2
ActData <- ActDataRow[,c(1,2, MeanStdlist)]
names(ActData) <- c("ActLable", "Subject", as.character(features[MeanStdlist-2,2]))
## Replace the activity lables by their description.
ActLables <- read.table("./UCI HAR Dataset/activity_labels.txt",
col.names = c("ActLable","Activity"))
NamedActData <- merge(ActData,ActLables, by.x = "ActLable", by.y = "ActLable")
NamedActData <- NamedActData[,c(82, 2:81)]
## Create a tidy data with avergae of each variable for each activity and each subject.
library(plyr)
AveData <- ddply(NamedActData, .(Activity, Subject), numcolwise(mean))
write.table(AveData, "./Average_Activity.txt", row.names = F)
|
90da350475640803d1633e70d595802e0a8c1662
|
550b5147909aa269b50af580c55f9e59f9c91d5e
|
/man/sfWideCsvToCorpus.Rd
|
4e41d992a15916011fe392e96de005f0fafcd911
|
[] |
no_license
|
clbustos/SemanticFields
|
b96ca71308428e1afc740dc527e4acdbfca8356a
|
9ebfaa0044db74a2f3e349be0e30f8d832179c73
|
refs/heads/master
| 2021-01-15T11:50:18.353144
| 2015-10-16T18:43:39
| 2015-10-16T18:43:39
| 34,122,591
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 657
|
rd
|
sfWideCsvToCorpus.Rd
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/sf_wide_csv_to_corpus.r
\name{sfWideCsvToCorpus}
\alias{sfWideCsvToCorpus}
\title{Transform wide representation (each line a set of responses)
on a csv file to corpus object representation}
\usage{
sfWideCsvToCorpus(filename, center_of_interest = "_ci_", other.vars)
}
\arguments{
\item{filename}{CSV filename}
\item{other.vars}{set other variables, as a list or data.frame}
\item{center}{of interest for the corpus}
}
\value{
a corpus object
}
\description{
Transform wide representation (each line a set of responses)
on a csv file to corpus object representation
}
|
0c0d9e8f16e69a49c22e7eb58ed7e103bf6741aa
|
73e26f49080d5b49902636b7099e89b38dc48ed6
|
/scripts/2_LOAD_DATA/create_empty_data_frame.R
|
7d81966fefd8ff6588121d64a3188bc215c7767e
|
[] |
no_license
|
bteinstein/SLA
|
14f67ff687eb30cc9fcc73552b25f93ce1f8d55e
|
e416d6bc6f8d95f38779dfe264768bc9c1d3c9ae
|
refs/heads/master
| 2023-07-22T17:04:26.216051
| 2021-09-07T19:31:27
| 2021-09-07T19:31:27
| 403,389,954
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 942
|
r
|
create_empty_data_frame.R
|
create_TBL_Attempt_TABLE <- function(nr){
suppressWarnings(
data.table::data.table(
# data_frame(
AWB = character(),
# Expected
First_Attempt_Time = as.POSIXct(character()),
# First_Attempt_Site = character(nr),
First_Attempt_Site = character(length = nr),
# Optional
Last_Attempt_Time = as.POSIXct(character()),
Last_Attempt_Site = character(length = nr),
# Temp Table
First_IssueParcel_Time = as.POSIXct(character()),
First_IssueParcel_Site = character(length = nr),
First_delivery_Time = as.POSIXct(character()),
First_delivery_Site = character(length = nr),
# Counter
Max_Attempt = integer(length = nr),
IssueParcel_Scan_Count = integer(length = nr),
Delivery_Scan_Count = integer(length = nr),
First_Attempt_Type = character(length = nr)
)
)
}
# p = create_TBL_Attempt_TABLE(length(AWB))
# p$AWB <- AWB
# p %>% left_join(l_attempt_df, by = c("AWB" = "AWB"))
# p %>% left_join(l_attempt_df)
|
311cd68c46460f06d108d3bec0e50f575933ecec
|
451013306c7697810789dd0610f03fa1e81e9bbc
|
/plot4.R
|
b95c8dc75fac34fc93cd33c8cd0a8e50ebee359a
|
[] |
no_license
|
justgo129/ExData_Plotting1
|
17369111f94502f12d54959c846ea6b051df6101
|
885de76b4fe53b3c780a6a8ea73689313d3b30d3
|
refs/heads/master
| 2020-12-02T16:36:17.469837
| 2017-07-13T02:34:02
| 2017-07-13T02:34:02
| 96,559,084
| 0
| 0
| null | 2017-07-07T17:02:49
| 2017-07-07T17:02:48
| null |
UTF-8
|
R
| false
| false
| 2,336
|
r
|
plot4.R
|
#Plot 4.R
#Read in Data to R - needed for all plots
par(mar = c(5.1, 4.1, 4.1, 2.1))
powerc<-read.csv ("household_power_consumption.txt", header=TRUE, sep=";")
powerc[powerc == "?"]<-NA # replace all "?" fields with "NA"
library(lubridate); library(dplyr); library(tidyr); library(graphics)
powerc<-filter(powerc, Date == "1/2/2007" | Date == "2/2/2007")
powerc[,1]<-as.Date(powerc[,1]) # -> change date from a factor to one of date
powerc<-cbind(powerc, paste(powerc[,1], powerc[,2])) # combine date and time: New col 10
powerc<-cbind(powerc, paste(powerc[,7], powerc[,8], powerc[,9])) #Define new col 11: plotted area to include cols 7-9
# Change col class types from factors, to facilitate plotting
for (i in 3:5) {
powerc[,i]<-as.numeric(powerc[,i])
}
for (i in 7:9) {
powerc[,i]<-as.numeric(powerc[,i])
}
png(file="plot4.png",width=480,height=480)
# 2*2 juxtaposition
par(mfrow=c(2,2))
# TOP LEFT PLOT
plot(powerc[,10], powerc[,3], ylab="Global Active Power (kilowatts)", type="l", xaxt="n")
axis(1, at=c(1,1441, 2880), labels = c("Thurs", "Fri", "Sat"))
lines(powerc[,10], powerc[,3], type="l", lwd=1)
# TOP RIGHT PLOT
plot(powerc[,10], powerc[,5], type="l",
xaxt="n", xlab="datetime",
ylab="Voltage")
lines(powerc[,10], powerc[,5], type="l", lwd=2)
axis(1, at=c(1,1441, 2880), labels = c("Thurs", "Fri", "Sat"))
# BOTTOM LEFT PLOT
legendcolors<-c("black", "red", "blue") # Prepare legend colors
plot(powerc[,10], powerc[,7], xlab="", type="l", ylab="Energy sub metering",
yaxt="n", xaxt="n")
lines(powerc[,10], powerc[,7], type="l", col = legendcolors[1], lwd=1)
lines(powerc[,10], powerc[,8], type="l", col = legendcolors[2], lwd=1)
lines(powerc[,10], powerc[,9], type="l", col = legendcolors[3], lwd=1)
axis(1, at=c(1,1441, 2880), labels = c("Thurs", "Fri", "Sat"))
axis(side = 2, at = c(0,10,20,30), labels = c("0", "10", "20", "30"))
legend("topright", legend = names(powerc[,7:9]),
lwd = 2, col = legendcolors, bty = "n")
# BOTTOM RIGHT PLOT
plot(powerc[,10], powerc[,4], type="l",
xlab="datetime", xaxt="n",
ylab="Global_reactive_power")
lines(powerc[,10], powerc[,4], type="l", col = "black", lwd=1)
axis(1, at=c(1,1441, 2880), labels = c("Thurs", "Fri", "Sat"))
dev.off()
|
c32944bc762a2f96a6de96c5fa3da1f03f3c499b
|
5d555b24611a2967fd7942cb69dbea15b713c9a2
|
/scripts/figures/venn.r
|
44e8d2041c71a876cd890081febb1c19422518bc
|
[] |
no_license
|
utsw-medical-center-banaszynski-lab/Martire-et-al-2019-Nature-Genetics
|
a6429413ed87ab6365e64c8f977acd4f0b2477a7
|
8b8fb2de7e1310de7ab3257a44bc9a7802a22cde
|
refs/heads/master
| 2020-05-14T21:40:29.161485
| 2019-07-08T22:58:47
| 2019-07-08T22:58:47
| 181,966,915
| 3
| 3
| null | null | null | null |
UTF-8
|
R
| false
| false
| 2,120
|
r
|
venn.r
|
#########Using VennDiagram package in R ##########
#Install the package
install.packages("gdata")
install.packages("VennDiagram")
#Load the package
library(gdata)
require("VennDiagram")
library(gplots)
geneList <- read.xls("GeneList.xlsx", sheet=1, stringsAsFactors=FALSE, header=FALSE)
head(geneList)
# Notice there are empty strings to complete the data frame in column 1 (V1)
tail(geneList)
# To convert this data frame to separate gene lists with the empty strings removed we can use lapply() with our home made function(x) x[x != ""]
geneLS <- lapply(as.list(geneList), function(x) x[x != ""])
# If this is a bit confusing you can also write a function and then use it in lapply()
removeEMPTYstrings <- function(x) {
newVectorWOstrings <- x[x != ""]
return(newVectorWOstrings)
}
geneLS2 <- lapply(as.list(geneList), removeEMPTYstrings)
# You can print the last 6 entries of each vector stored in your list, as follows:
lapply(geneLS, tail)
lapply(geneLS2, tail) # Both methods return the same results
# We can rename our list vectors
names(geneLS) <- c("RNA", "ChIP")
# Now we can plot a Venn diagram with the VennDiagram R package, as follows:
#require("VennDiagram")
pdf("venn.pdf")
VENN.LIST <- geneLS
venn.plot <- venn.diagram(VENN.LIST , NULL, fill=c("darkmagenta", "darkblue"), alpha=c(0.5,0.5), cex = 2, cat.fontface=4, category.names=c("RNA", "ChIP"), main="plot title")
# To plot the venn diagram we will use the grid.draw() function to plot the venn diagram
grid.draw(venn.plot)
# To get the list of gene present in each Venn compartment we can use the gplots package
#require("gplots")
a <- venn(VENN.LIST, show.plot=FALSE)
# You can inspect the contents of this object with the str() function
str(a)
# By inspecting the structure of the a object created,
# you notice two attributes: 1) dimnames 2) intersections
# We can store the intersections in a new object named inters
inters <- attr(a,"intersections")
# We can summarize the contents of each venn compartment, as follows:
# in 1) ConditionA only, 2) ConditionB only, 3) ConditionA & ConditionB
lapply(inters, head)
dev.off()
|
8cafa761fb59be3878434070e5b25e1ad2a56e2e
|
81354954be61599eae884b0fa9f6ce4bccdd06b0
|
/man/ctd_BlueLake2018_VisualCortexOnly.Rd
|
b287e7c4f4780e0f31ae513973af4a7bdfe1fb22
|
[] |
no_license
|
obada-alzoubi/MAGMA_Celltyping
|
272631794f31733c24c6384fd2f181a0972eca9c
|
f931877dedcde103723f14242d5242fdca7b3af6
|
refs/heads/master
| 2023-07-10T15:53:22.307531
| 2021-08-20T09:19:22
| 2021-08-20T09:19:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| true
| 546
|
rd
|
ctd_BlueLake2018_VisualCortexOnly.Rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.r
\docType{data}
\name{ctd_BlueLake2018_VisualCortexOnly}
\alias{ctd_BlueLake2018_VisualCortexOnly}
\title{Celltype data (Blue Lake 2018 Visual Cortex)}
\format{
An object of class \code{list} of length 2.
}
\source{
# Generated on Nathan's Mac: ~/Single Cell Datasets/BlueLake2018
usethis::use_data(ctd_BlueLake2018_FrontalCortexOnly,overwrite=TRUE)
}
\usage{
ctd_BlueLake2018_VisualCortexOnly
}
\description{
CTD file with data from humans
}
\keyword{datasets}
|
ec5557f0657f5d6c63aa07fe89896e337c7e92e0
|
ed1920915c1f7070c7cec39de8ca82672be18cc5
|
/source/mhealth/downtime.R
|
27fcc17b6ae25e2e37b1ce8000ba6f6d5c319c70
|
[] |
no_license
|
sthallor/miscRscripts
|
d28f7a9cdbc53fc7c7994c6000d1753b3679236d
|
c3a5a206c35cdbbb15f07a4ea9250ff861b2e7f1
|
refs/heads/master
| 2022-11-06T03:39:03.951539
| 2020-06-21T23:21:47
| 2020-06-21T23:21:47
| 273,998,540
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 6,056
|
r
|
downtime.R
|
#######################################################################################
# downtime.R - looking at EDR rig downtime data
# Ensign Energy Services Inc. retains all rights to this software
# FHS, May 6, 2016
#######################################################################################
dirName <- '/Users/Fred.Seymour/EDR_Data/160506_Downtime/'
inputFilename <- '160506_Downtime.csv'
outputFilename <- '160506_log.txt'
tableFilename <- 'downtimes.csv'
inputFilename <- paste0(dirName,inputFilename)
outputFilename <- paste0(dirName,outputFilename)
tableFilename <- paste0(dirName,tableFilename)
cat('EDR Downtime analysis sending output to:\n',outputFilename,'\n')
sink(file=outputFilename)
options(width=120)
# Historian installation history
historian <- data.frame(rig=NULL,historianStart=NULL)
historian <- rbind(historian,data.frame(rig=148,historianStart="2015-07-01"))
historian <- rbind(historian,data.frame(rig=151,historianStart="2015-11-24"))
historian <- rbind(historian,data.frame(rig=769,historianStart="2015-11-25"))
historian <- rbind(historian,data.frame(rig=155,historianStart="2015-11-25"))
historian <- rbind(historian,data.frame(rig=774,historianStart="2015-12-10"))
historian <- rbind(historian,data.frame(rig=773,historianStart="2015-12-11"))
historian <- rbind(historian,data.frame(rig=156,historianStart="2016-01-13"))
historian <- rbind(historian,data.frame(rig=161,historianStart="2016-01-15"))
historian <- rbind(historian,data.frame(rig=162,historianStart="2016-02-13"))
historian <- rbind(historian,data.frame(rig=119,historianStart="2016-03-18"))
historian <- rbind(historian,data.frame(rig=135,historianStart="2016-03-18"))
historian <- rbind(historian,data.frame(rig=121,historianStart="2016-03-19"))
historian <- rbind(historian,data.frame(rig=152,historianStart="2016-03-20"))
historian <- rbind(historian,data.frame(rig=775,historianStart="2016-03-29"))
historian <- rbind(historian,data.frame(rig=157,historianStart="2016-04-16"))
inputFilename <- '/Users/Fred.Seymour/EDR_Data/160506_Downtime/160506_Downtime.csv'
cat('\nReading selected downtime rig observation from file: \n',inputFilename)
dt <- read.csv(inputFilename,nrow=-1)
cat('\nRead ',nrow(dt),' rows and ',ncol(dt),' columns.')
cat('\nDrillingDesc "Downtime" count=',length(grep('Downtime',as.character(dt$DrillingDesc))))
cat('\nFiltering to just include observations with "Downtime" in DrillingDesc')
dt <- dt[grep('Downtime',as.character(dt$DrillingDesc)),]
cat('\nNow have ',nrow(dt),' rows and ',ncol(dt),' columns.')
dt$DrillingDesc <- as.factor(as.character(dt$DrillingDesc))
cat('\nThis represents approximately ',round(nrow(dt)/360),' Hours of downtime')
cat('\n\nlength(unique(dt$DrillingDesc))=',length(unique(dt$DrillingDesc)))
cat('\n\nTable of observation counts for Downtime DrillingDesc\n\n')
tableDrillingDesc <- as.data.frame(table(dt$DrillingDesc))
colnames(tableDrillingDesc) <- c('DrillingDesc','Count')
tableDrillingDesc$Hours <- round(tableDrillingDesc$Count/360)
tableDrillingDesc$Prop <- round(tableDrillingDesc$Count/nrow(dt),digits=3)
tableDrillingDesc$Rigs <- 0
tableDrillingDesc$Wells <- 0
tableDrillingDesc$Remarks <- 0
for (i in 1:nrow(tableDrillingDesc)) {
tableDrillingDesc$Rigs[i] <- length(unique(dt$Rig[dt$DrillingDesc==tableDrillingDesc$DrillingDesc[i]]))
tableDrillingDesc$Wells[i] <- length(unique(dt$WellName[dt$DrillingDesc==tableDrillingDesc$DrillingDesc[i]]))
tableDrillingDesc$Remarks[i] <- length(unique(dt$Remark[dt$DrillingDesc==tableDrillingDesc$DrillingDesc[i]]))
}
tableDrillingDesc <- tableDrillingDesc[order(tableDrillingDesc$Count,decreasing=TRUE),]
print(tableDrillingDesc)
cat('\nTable of observation counts for Downtime DrillingDesc (Rows) and Rig (Cols)\n\n')
print(table(dt$DrillingDesc,dt$Rig))
# Assemble downtime 'report'
dt$time <- paste0(substr(dt$time,1,10),' ',substr(dt$time,12,19))
dt$time <- as.POSIXlt(dt$time,"%Y-%m-%d %H:%M:%S",tz="")
# dt$RigDescRemark <- paste(dt$Rig,dt$DrillingDesc,dt$Remark,sep=' - ')
dt$RigDesc <- paste(dt$Rig,as.character(as.numeric(dt$WellName)),dt$DrillingDesc,dt$Remark,sep='-')
rep <- data.frame(event=rle(as.vector(dt$RigDesc))$values,
lengths=rle(as.vector(dt$RigDesc))$lengths)
rep$from <- 0
rep$to <- 0
rep$to <- cumsum(rep$lengths)
rep$from <- rep$to - rep$lengths + 1
colnames(rep) <- c('rig','event','from','to')
rep$count <- rep$event
rep$rig <- dt$Rig[rep$from]
rep$well <- dt$WellName[rep$from]
rep$event <-dt$DrillingDesc[rep$from]
rep$remark <- dt$Remark[rep$from]
rep$startTime <- dt$time[rep$from]
rep$endTime <- dt$time[rep$to]
rep$elapsed_HR <- round(as.numeric(difftime(rep$endTime,rep$startTime,units='hours')),digits=1)
rep$count_HR <- round((rep$to - rep$from+1)/360,digits=1)
rep$from <- NULL
rep$to <- NULL
rep$historian <- rep$rig %in% historian$rig
rep$historian <- as.character(rep$historian)
rep$historian[rep$historian=='TRUE'] <- 'Yes'
rep$historian[rep$historian=='FALSE'] <- ''
rep <- merge(rep,historian,by="rig",all.x=TRUE)
rep$historian[rep$historian=='Yes' & as.numeric(difftime(rep$startTime,rep$historianStart,units='secs'))<0] <- 'Prior'
rep$historianStart <- as.character(rep$historianStart)
rep$historianStart[is.na(rep$historianStart)] <- ''
rep <- rep[order(rep$event,rep$count_HR,decreasing=TRUE),]
cat('\n\nListing of individual down times by events\n\n')
print(rep[,c('rig','event','startTime','endTime','count_HR','historian','historianStart')],row.names=FALSE)
cat('\n\nListing of sum of "Downtime - Top drive" hours for each rig that has historian data\n')
print(aggregate(.~rig,data=rep[rep$historian=='Yes' & rep$event=='Downtime - Top drive',c('rig','count_HR')],
FUN=function(x){sum(x,na.rm=T)}))
cat('\n\nWriting ',tableFilename,' to disk')
write.csv(rep[,c('rig','well','event','remark','startTime','endTime','count_HR','historian')],file=tableFilename,row.names=FALSE)
# rep <- rep[order(rep$rig),]
# cat('\n\nListing of individual down times by rig\n\n')
# print(rep)
cat('\nDone.\n')
if (sink.number()>0) sink(file=NULL)
|
2c8fa94b08c6c9d38e6a97726d2ca408b9e003bd
|
de8b069ae217e9d0c14c3b9b2c9bb8afb43baad4
|
/inst/unitTests/test_compartments.R
|
07a783bf66c5864866cc8e23e98d16ba84d961d0
|
[] |
no_license
|
aleiyishi/minfi
|
833723ffbb2af19318d23fc44c22a15eff7a50ba
|
52832f5f5f71f38a371effab01eba6957f577264
|
refs/heads/master
| 2020-12-25T22:19:56.790474
| 2016-07-27T00:42:27
| 2016-07-27T00:42:27
| 64,294,127
| 1
| 0
| null | 2016-07-27T09:09:49
| 2016-07-27T09:09:49
| null |
UTF-8
|
R
| false
| false
| 528
|
r
|
test_compartments.R
|
test_compartments <- function() {
stopifnot(require(minfiData))
stopifnot(require(digest))
load(file.path(path.package("minfi"), "unitTests", "digest_compartments.rda"))
GMsetEx <- mapToGenome(MsetEx)
gr.cor <- createCorMatrix(GMsetEx, res=500*1000)
checkEquals(digest_compartments$cor.matrix,
minfi:::.digestMatrix(gr.cor$cor.matrix))
set.seed(456)
gr.ab <- extractAB(gr.cor)
checkEquals(digest_compartments$pc,
minfi:::.digestVector(gr.ab$pc, digits = 2))
}
|
726533fe37e1eb085ed29a79f444a546226b3c03
|
8a2ef8564dac1551f9a389c3cc04837453c933d6
|
/5_ScriptConsensusClustering/7_ObtencionGrupos_NMF_Luad_Lusc.R
|
41b32155525da9449162392b644616e16a198551
|
[] |
no_license
|
anemartinezlarrinaga2898/TFM_ANE_MARTINEZ
|
0a311e96ccad34f331d798b1f3c459539614e1c7
|
8e41157613fff0cfa4f5eb27e6984d02d000b9ef
|
refs/heads/main
| 2023-07-27T21:41:44.218050
| 2021-08-27T10:15:35
| 2021-08-27T10:15:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 4,912
|
r
|
7_ObtencionGrupos_NMF_Luad_Lusc.R
|
# TFM, Master en Metodos Computacionales UNAV
#Autor: Ane Martinez Larrinaga
#Tutores: Silvestre Vicent Cambra y Mikel Hernaez
#Fecha: 17-04-2021
#SCRIPT para obtener los grupos de NMF:
#####################################################################################################################################
directory <- setwd("/Users/anemartinezlarrinaga/OneDrive/2_MASTER_Computacional/5_TFM/CODIGO/SCRIPTS_Y_DATOS/5_ScriptConsensusClustering/")
nmf_extract_group <- function(res, type="consensus", matchConseOrder=F){
data <- NULL
if(type=="consensus"){
predict.consensus <- predict(res, what="consensus")
silhouette.consensus <- silhouette(res, what="consensus")
# It turns out the factor levels is the NMF_assigned_groups from consensus matrix
# that matches the original sampleNames(res) order
# The attributes(a.predict.consensus)$iOrd is the idx order for it to match the
# order of the samples in consensusmap(res). It is just for displaying
# Therefore, the merged data frame sampleNames(res) + a.predict.consensus is the final
# consensus results.
data <- data.frame(Sample_ID=sampleNames(res),
nmf_subtypes = predict.consensus,
sil_width = signif(silhouette.consensus[, "sil_width"], 3))
# If we want to display as we see in consensusmap, we just need to reoder everything.
# Now re-order data to match consensusmap sample order
if(matchConseOrder){
sample.order <- attributes(predict.consensus)$iOrd
data <- data[sample.order, ]
}
}else if(type=="samples"){
predict.samples <- predict(res, what="samples", prob=T)
silhouette.samples <- silhouette(res, what="samples")
data <- data.frame(Sample_ID=names(predict.samples$predict),
nmf_subtypes = predict.samples$predict,
sil_width = signif(silhouette.samples[, "sil_width"], 3),
prob = signif(predict.samples$prob, 3))
}else{
stop(paste("Wrong type:", type, "Possible options are: 'consensus', 'samples' "))
}
return(data)
}
library(NMF)
library(tidyverse)
#####################################################################################################################################
# ······················· L U A D ·············································
resultadosNMFLuad <- readRDS("Resultados_NMF_Total_Luad.rds")
K2_NMF_Luad <- resultadosNMFLuad[[1]]
K3_NMF_Luad <- resultadosNMFLuad[[2]]
K4_NMF_Luad <- resultadosNMFLuad[[3]]
K5_NMF_Luad <- resultadosNMFLuad[[4]]
K6_NMF_Luad <- resultadosNMFLuad[[5]]
K7_NMF_Luad <- resultadosNMFLuad[[6]]
K2_NMF_Luad <- nmf_extract_group(K2_NMF_Luad)
K3_NMF_Luad <- nmf_extract_group(K3_NMF_Luad)
K4_NMF_Luad <- nmf_extract_group(K4_NMF_Luad)
K5_NMF_Luad <- nmf_extract_group(K5_NMF_Luad)
K6_NMF_Luad <- nmf_extract_group(K6_NMF_Luad)
K7_NMF_Luad <- nmf_extract_group(K7_NMF_Luad)
saveRDS(K2_NMF_Luad,"K2_NMF_Luad.rds")
saveRDS(K3_NMF_Luad,"K3_NMF_Luad.rds")
saveRDS(K4_NMF_Luad,"K4_NMF_Luad.rds")
saveRDS(K5_NMF_Luad,"K5_NMF_Luad.rds")
saveRDS(K6_NMF_Luad,"K6_NMF_Luad.rds")
saveRDS(K7_NMF_Luad,"K7_NMF_Luad.rds")
K3.1_NMF_Luad <- K3_NMF_Luad %>% filter(nmf_subtypes==1)
K3.2_NMF_Luad <- K3_NMF_Luad %>% filter(nmf_subtypes==2)
K3.3_NMF_Luad <- K3_NMF_Luad %>% filter(nmf_subtypes==3)
saveRDS(K3.1_NMF_Luad,"K3.1_NMF_Luad.rds")
saveRDS(K3.2_NMF_Luad,"K3.2_NMF_Luad.rds")
saveRDS(K3.3_NMF_Luad,"K3.3_NMF_Luad.rds")
#####################################################################################################################################
resultadosNMFLusc <- readRDS("Resultados_NMF_Total_Lusc.rds")
K2_NMF_Lusc <- resultadosNMFLusc[[1]]
K3_NMF_Lusc <- resultadosNMFLusc[[2]]
K4_NMF_Lusc <- resultadosNMFLusc[[3]]
K5_NMF_Lusc <- resultadosNMFLusc[[4]]
K6_NMF_Lusc <- resultadosNMFLusc[[5]]
K7_NMF_Lusc <- resultadosNMFLusc[[6]]
K2_NMF_Lusc <- nmf_extract_group(K2_NMF_Lusc)
K3_NMF_Lusc <- nmf_extract_group(K3_NMF_Lusc)
K4_NMF_Lusc <- nmf_extract_group(K4_NMF_Lusc)
K5_NMF_Lusc <- nmf_extract_group(K5_NMF_Lusc)
K6_NMF_Lusc <- nmf_extract_group(K6_NMF_Lusc)
K7_NMF_Lusc <- nmf_extract_group(K7_NMF_Lusc)
saveRDS(K2_NMF_Lusc,"K2_NMF_Lusc.rds")
saveRDS(K3_NMF_Lusc,"K3_NMF_Lusc.rds")
saveRDS(K4_NMF_Lusc,"K4_NMF_Lusc.rds")
saveRDS(K5_NMF_Lusc,"K5_NMF_Lusc.rds")
saveRDS(K6_NMF_Lusc,"K6_NMF_Lusc.rds")
saveRDS(K7_NMF_Lusc,"K7_NMF_Lusc.rds")
K3.1_NMF_Lusc <- K3_NMF_Lusc %>% filter(nmf_subtypes==1)
K3.2_NMF_Lusc <- K3_NMF_Lusc %>% filter(nmf_subtypes==2)
K3.3_NMF_Lusc <- K3_NMF_Lusc %>% filter(nmf_subtypes==3)
saveRDS(K3.1_NMF_Lusc,"K3.1_NMF_Lusc.rds")
saveRDS(K3.2_NMF_Lusc,"K3.2_NMF_Lusc.rds")
saveRDS(K3.3_NMF_Lusc,"K3.3_NMF_Lusc.rds")
#####################################################################################################################################
|
4f44a754ea7d26e6505b2985b7db59824669ec19
|
19f7fc6594fcbce0c4e1c76ae455887976eb6859
|
/R/FLLogRegr.R
|
eab8890e329d41fea00a7f4c5dcbcd33338e0aa0
|
[] |
no_license
|
AnanyaT/AdapteR
|
696d16ebed0df716614c1d90c7f6b1092953cb69
|
3842d3e662f8e4fdf5709df41deada875aff9a2e
|
refs/heads/master
| 2021-01-18T17:10:47.836244
| 2016-06-03T09:57:24
| 2016-06-03T09:57:24
| 59,019,034
| 0
| 0
| null | 2016-05-17T12:08:53
| 2016-05-17T12:08:52
| null |
UTF-8
|
R
| false
| false
| 11,306
|
r
|
FLLogRegr.R
|
#' @include utilities.R
#' @include data_prep.R
#' @include FLTable.R
NULL
#' An S4 class to represent FLLinRegr
#'
#' @slot formula an object of class 'formula': Model Formula
#' @slot deeptable A character vector containing
#' the deeptable on conversion from a widetable
#' @slot AnalysisID An output character ID from CALL FLLogRegr
#' @slot wideToDeepAnalysisID An output character ID from FLRegrDataPrep
#' @slot mapTable name of the mapping table
#' @slot scoreTable name of the scoring table
#' @slot modelID id of the model with best fit
#' @slot table input FLTable object
#' @slot results cache list of results computed
#' @slot vfcalls contains names of tables
#' @method print FLLogRegr
#' @method coefficients FLLogRegr
#' @method residuals FLLogRegr
#' @method influence FLLogRegr
#' @method lm.influence FLLogRegr
#' @method plot FLLogRegr
#' @method summary FLLogRegr
#' @method predict FLLogRegr
setClass(
"FLLogRegr",
slots=list(formula="formula",
AnalysisID="character",
wideToDeepAnalysisId="character",
table="FLTable",
results="list",
deeptable="FLTable",
mapTable="character",
scoreTable="character",
offset="character",
vfcalls="character"))
#' @export
glm <- function (formula,data=list(),...) {
UseMethod("glm", data)
}
#' @export
glm.default <- stats::glm
#' Logistic and Poisson Regression.
#'
#' \code{glm} performs logistic and poisson regression on FLTable objects.
#'
#' @param formula A symbolic description of model to be fitted
#' @param family Can be one of poisson,binomial,linear or multinomial.
#' Can be family functions like stats::poisson wherever possible.
#' @param data An object of class FLTable
#' @param catToDummy Transform categorical variables to numerical values
#' either using dummy variables or by using Empirical
#' Logit. If the value is 1, transformation is done using
#' dummy variables, else if the value is 0,
#' transformation is done using Empirical Logit.
#' @param performNorm 0/1 indicating whether to perform standardization of data.
#' @param performVarReduc 0/1. If the value is 1,
#' the stored procedure eliminates variables based on standard deviation and
#' correlation.
#' @param makeDataSparse If 0,Retains zeroes and NULL values
#' from the input table. If 1, Removes zeroes and NULL. If 2,Removes zeroes
#' but retains NULL values.
#' @param minStdDev Minimum acceptable standard deviation for
#' elimination of variables. Any variable that has a
#' standard deviation below this threshold is
#' eliminated. This parameter is only consequential if
#' the parameter PerformVarReduc = 1. Must be >0.
#' @param maxCorrel Maximum acceptable absolute correlation between
#' a pair of columns for eliminating variables. If the
#' absolute value of the correlation exceeds this
#' threshold, one of the columns is not transformed.
#' Again, this parameter is only consequential if the
#' parameter PerformVarReduc = 1. Must be >0 and <=1.
#' @param classSpec list describing the categorical dummy variables.
#' @param whereconditions takes the where_clause as a string.
#' @param pThreshold The threshold for False positive value
#' that a user can specify to calculate the false positives
#' and false negatives. Must be between 0 and 1.
#' @param pRefLevel Reference value for dependent variable
#' in case of multinomial family.
#' @param maxiter maximum number of iterations.
#' @section Constraints:
#' The anova method is not yet available for FLLogRegr.
#' In case of multinomial family, residuals,fitted.values
#' properties are not available.plot,influence methods are
#' also not available.
#' @return \code{glm} performs logistic
#' or poisson regression and replicates equivalent R output.
#' @examples
#' library(RODBC)
#' connection <- flConnect("Gandalf")
#' deeptable <- FLTable("FL_DEMO","tblLogRegr","ObsID","VarID","Num_Val",
#' whereconditions="ObsID<7001")
#' glmfit <- glm(NULL,data=deeptable)
#' summary(glmfit)
#' plot(glmfit)
#' glmfit <- glm(NULL,data=deeptable,family="logisticwt",eventweight=0.8,noneventweight=1)
#' summary(glmfit)
#' plot(glmfit)
#' connection <- flConnect(odbcSource = "Gandalf",database = "FL_DEV")
#' widetable <- FLTable("FL_DEV", "siemenswidetoday1", "ObsID")
#' poissonfit <- glm(event ~ meanTemp, family=poisson, data=widetable,offset="age")
#' summary(poissonfit)
#' plot(poissonfit)
#' predData <- FLTable("FL_DEV","preddata1","ObsID")
#' mu <- predict(poissonfit,newdata=predData)
#' deeptable <- FLTable("FL_DEMO","tblLogRegrMN10000","ObsID","VarID","Num_Val",
#' whereconditions="ObsID<7001")
#' glmfit <- glm(NULL,data=deeptable,family="multinomial")
#' glmfit$coefficients
#' glmfit$FLLogRegrStats
#' glmfit$FLCoeffStdErr
#' summary(glmfit)
#' print(glmfit)
#' @export
glm.FLTable <- function(formula,
family="binomial",
data,
...)
{
vcallObject <- match.call()
data <- setAlias(data,"")
if(is.character(family)){
if(!family%in%c("poisson","binomial","multinomial","logisticwt"))
stop("only poisson,binomial and multinomial are currently supported in glm\n")
if(family %in% "binomial") family <- "logistic"
}
if(is.function(family)){
if(base::identical(family,stats::poisson))
family <- "poisson"
else if(base::identical(family,stats::binomial))
family <- "logistic"
else stop("only poisson,binomial,multinomial and logisticwt are currently supported in glm\n")
}
return(lmGeneric(formula=formula,
data=data,
callObject=vcallObject,
familytype=family,
...))
}
#' @export
`$.FLLogRegr`<-function(object,property){
#parentObject <- deparse(substitute(object))
parentObject <- unlist(strsplit(unlist(strsplit(
as.character(sys.call()),"(",fixed=T))[2],",",fixed=T))[1]
if(property %in% c("coefficients","residuals",
"fitted.values","FLCoeffStdErr",
"FLCoeffPValue","call","model","x",
"y","qr","rank","xlevels","terms","assign"))
{
propertyValue <- `$.FLLinRegr`(object,property)
assign(parentObject,object,envir=parent.frame())
return(propertyValue)
}
else if(property=="FLCoeffChiSq")
{
coeffVector <- coefficients.FLLogRegr(object)
assign(parentObject,object,envir=parent.frame())
return(object@results[["FLCoeffChiSq"]])
}
else if(property=="FLLogRegrStats")
{
if(!is.null(object@results[["FLLogRegrStats"]]))
return(object@results[["FLLogRegrStats"]])
else
{
sqlstr <- paste0("SELECT * FROM ",object@vfcalls["statstablename"],"\n",
" WHERE AnalysisID=",fquote(object@AnalysisID),
ifelse(!is.null(object@results[["modelID"]]),
paste0(" \nAND ModelID=",object@results[["modelID"]]),""))
statsdataframe <- sqlQuery(getOption("connectionFL"),sqlstr)
object@results <- c(object@results,list(FLLogRegrStats=statsdataframe))
assign(parentObject,object,envir=parent.frame())
return(statsdataframe)
}
}
else if(property=="df.residual")
{
df.residualsvector <- nrow(object@table)-length(object$coefficients)
assign(parentObject,object,envir=parent.frame())
return(df.residualsvector)
}
else stop("That's not a valid property")
}
#' @export
coefficients.FLLogRegr<-function(object){
parentObject <- unlist(strsplit(unlist(strsplit(
as.character(sys.call()),"(",fixed=T))[2],")",fixed=T))[1]
coeffVector <- coefficients.lmGeneric(object,
FLCoeffStats=c(FLCoeffStdErr="STDERR",
FLCoeffPValue="PVALUE",
FLCoeffChiSq="CHISQ"))
assign(parentObject,object,envir=parent.frame())
return(coeffVector)
}
#' @export
residuals.FLLogRegr<-function(object)
{
parentObject <- unlist(strsplit(unlist(strsplit(
as.character(sys.call()),"(",fixed=T))[2],")",fixed=T))[1]
residualsvector <- residuals.FLLinRegr(object)
assign(parentObject,object,envir=parent.frame())
return(residualsvector)
}
#' @export
predict.FLLogRegr <- function(object,
newdata=object@table,
scoreTable=""){
return(predict.lmGeneric(object,newdata=newdata,
scoreTable=scoreTable))
}
#' @export
summary.FLLogRegr<-function(object){
ret <- object$FLLogRegrStats
colnames(ret) <- toupper(colnames(ret))
vresiduals <- object$residuals
sqlstr <- paste0("WITH z (id,val)",
" AS(SELECT 1,",
"a.vectorValueColumn AS deviation",
" FROM (",constructSelect(vresiduals),") AS a) ",
" SELECT FLMin(z.val),FLMax(z.val),q.*",
" FROM (SELECT a.oPercVal as perc
FROM TABLE (FLPercUdt(z.id, z.val, 0.25)
HASH BY z.id
LOCAL ORDER BY z.id) AS a) AS q,z
group by 3")
vresult1 <- sqlQuery(getOption("connectionFL"),sqlstr)
sqlstr <- paste0("WITH z (id,val)",
" AS(SELECT 1,",
"a.vectorValueColumn AS deviation",
" FROM (",constructSelect(vresiduals),") AS a) ",
" SELECT q.*",
" FROM (SELECT a.oPercVal as perc
FROM TABLE (FLPercUdt(z.id, z.val, 0.50)
HASH BY z.id
LOCAL ORDER BY z.id) AS a) AS q")
vresult2 <- sqlQuery(getOption("connectionFL"),sqlstr)
sqlstr <- paste0("WITH z (id,val)",
" AS(SELECT 1,",
"a.vectorValueColumn AS deviation",
" FROM (",constructSelect(vresiduals),") AS a) ",
" SELECT q.*",
" FROM (SELECT a.oPercVal as perc
FROM TABLE (FLPercUdt(z.id, z.val, 0.75)
HASH BY z.id
LOCAL ORDER BY z.id) AS a) AS q")
vresult3 <- sqlQuery(getOption("connectionFL"),sqlstr)
coeffframe <- data.frame(object$coefficients,
object$FLCoeffStdErr,
object$FLCoeffChiSq,
object$FLCoeffPValue)
colnames(coeffframe)<-c("Estimate","Std. Error","ChiSquare","Pr(>|t|)")
residualframe <- data.frame(vresult1[[1]],
vresult1[[3]],
vresult2[[1]],
vresult3[[1]],
vresult1[[2]])
colnames(residualframe) <- c("Min","1Q","Median","3Q","Max")
parentObject <- unlist(strsplit(unlist(strsplit
(as.character(sys.call()),"(",fixed=T))[2],")",fixed=T))[1]
assign(parentObject,object,envir=parent.frame())
cat("Call:\n")
cat(paste0(object$call),"\n")
cat("\nResiduals:\n")
print(residualframe)
cat("\n\nCoefficients:\n")
print(coeffframe)
cat("\n---\n")
cat("Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 '' 1\n")
print(ret)
cat("\n")
}
#' @export
print.FLLogRegr<-function(object){
parentObject <- unlist(strsplit(unlist(strsplit(
as.character(sys.call()),"(",fixed=T))[2],")",fixed=T))[1]
print.FLLinRegr(object)
assign(parentObject,object,envir=parent.frame())
}
#' @export
setMethod("show","FLLogRegr",print.FLLinRegr)
#' @export
plot.FLLogRegr <- function(object)
{
plot.FLLinRegr(object)
parentObject <- unlist(strsplit(unlist(strsplit(
as.character(sys.call()),"(",fixed=T))[2],")",fixed=T))[1]
assign(parentObject,object,envir=parent.frame())
}
#' @export
influence.FLLogRegr <- function(model,...){
parentObject <- unlist(strsplit(unlist(strsplit(as.character
(sys.call()),"(",fixed=T))[2],")",fixed=T))[1]
vresult <- influence.FLLinRegr(model,...)
assign(parentObject,model,envir=parent.frame())
return(vresult)
}
#' @export
lm.influence.FLLogRegr <- function(model,do.coef=TRUE,...){
parentObject <- unlist(strsplit(unlist(strsplit(as.character
(sys.call()),"(",fixed=T))[2],")",fixed=T))[1]
vresult <- lm.influence.FLLinRegr(model,do.coef=do.coef,...)
assign(parentObject,model,envir=parent.frame())
return(vresult)
}
|
409f32ec4d3bdb1925581e9c36b55811fd022df5
|
a2295ee6ec97b25e993259b4161673caec545943
|
/basic_assignment/assignment_1_task1/combine data.R
|
50fb663db95b941bf79710b3e1b0f7d2593a7270
|
[] |
no_license
|
ccfelius/DataMining
|
f9f7dc27e8f9e8cd7511e6720b9b3dab75cc260c
|
be381fd57454cbe6ba86f31725cc06cf3375605d
|
refs/heads/main
| 2023-05-11T22:47:51.694508
| 2021-05-28T11:56:51
| 2021-05-28T11:56:51
| 352,127,800
| 0
| 2
| null | null | null | null |
UTF-8
|
R
| false
| false
| 1,065
|
r
|
combine data.R
|
# combine data
# load packages
library(tidyverse)
library(rstudioapi)
library(lubridate)
# set working directory
setwd(dirname(getActiveDocumentContext()$path))
# load the cat data
cat_data <- read_delim("data/data_fin.csv", delim = ";")
program_data <- read_csv("data/cleaned_programs.csv")
# join data
data <- cat_data %>%
left_join(program_data, by = c("X1" = "id")) %>%
select(-X1, -What.programme.are.you.in.)
data_clean <- data %>%
rename(ml = Have.you.taken.a.course.on.machine.learning.,
ir = Have.you.taken.a.course.on.information.retrieval.,
stats = Have.you.taken.a.course.on.statistics.,
db = Have.you.taken.a.course.on.databases.,
gender = What.is.your.gender.,
chocolate = Chocolate.makes.you.....,
birthday = birthday.x,
neighbors = neighbors.x,
good_day_1 = What.makes.a.good.day.for.you..1..,
good_day_2 = What.makes.a.good.day.for.you..2..,
program = clean_program) %>%
relocate(program)
#write_csv(data_clean, "data/final/data_clean.csv")
|
6ca2427d4643ccfad9faf169eadd994866a523dd
|
c7e42d6a5fef98d887fafb1d4e0b0e4265fa8a5e
|
/abc/ououcirabc.r
|
9b7d6a725d0f3692184dc936ebd0dbcefe729c93
|
[] |
no_license
|
ChihPingWang/ououcir
|
97a8353f9cae07be4e09c5d7a54068f8003642cc
|
5ea14ad175d1bcc1991bbc00fff50747318f59b5
|
refs/heads/master
| 2020-05-18T17:13:05.538999
| 2019-05-02T08:29:56
| 2019-05-02T08:29:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 10,189
|
r
|
ououcirabc.r
|
rm(list=ls())
#install.packages("TreeSim")
library(TreeSim)
library(EasyABC)
library(coda)
#oubmbmintegrand<-function(s, alpha.y=alpha.y){
# alpha.y*exp(alpha.y*s)*rnorm(n=1,mean=0,sd=s)
# }
n<-20
numbsim<-1;lambda<-2.0;mu<-0.5;frac<-0.6;age<-2
tree<-sim.bd.taxa.age(n=n,numbsim=1,lambda=lambda,mu=mu,frac=frac,age=age,mrca=TRUE)[[1]]
tree<-reorder(tree,"postorder")
tree$edge
plot(tree)
nodelabels()
tiplabels()
root<-1
true.alpha.y<-1
true.alpha.x<-0.2
true.theta.x<-0.5
true.sigma.sq.x<-2
true.alpha.tau<-0.5
true.theta.tau<-3
true.sigma.tau<-2
n_t<-10
n_s<-10
true.b0 <- 0
true.b1 <- 1
true.b2 <- 0.2
x1nodestates<-array(0,c(2*n-1))
x1nodestates[n+1]<-root
x2nodestates<-array(0,c(2*n-1))
x2nodestates[n+1]<-root
optimnodestates<-array(0,c(2*n-1))
optimnodestates[n+1]<-root
sigmasqnodestates<-array(0,c(2*n-1))
sigmasqnodestates[n+1]<-root
ynodestates<-array(0,c(2*n-1))
ynodestates[n+1]<-root
N<-dim(tree$edge)[1]
anc<-tree$edge[,1]
des<-tree$edge[,2]
treelength<-tree$edge.length
int3integrand<- function(s,alpha.x=alpha.x,sigma.sq.theta=sigma.sq.theta,alpha.y=alpha.y){
int3stochV<-(exp(2* alpha.x) -1 ) / (2*alpha.x)
f<-sqrt(sigma.sq.theta)*alpha.y*exp((alpha.y-alpha.x)*t)*1/sqrt(2*pi*int3stochV)*exp(-0.5/int3stochV*s^2)
return(f)
}
for(index in N:1){
x1ou.mean<-x1nodestates[anc[index]]*exp(-true.alpha.x*treelength[index]) + true.theta.x*(1-exp(-true.alpha.x*treelength[index]))
x1ou.sd<-sqrt((true.sigma.sq.x/(2*true.alpha.x))*(1-exp(-2*true.alpha.x*treelength[index])))
x1nodestates[des[index]]<-rnorm(n=1,mean=x1ou.mean,sd=x1ou.sd)
x2ou.mean<-x2nodestates[anc[index]]*exp(-true.alpha.x*treelength[index]) + true.theta.x*(1-exp(-true.alpha.x*treelength[index]))
x2ou.sd<-sqrt((true.sigma.sq.x/(2*true.alpha.x))*(1-exp(-2*true.alpha.x*treelength[index])))
x2nodestates[des[index]]<-rnorm(n=1,mean=x2ou.mean,sd=x2ou.sd)
optimnodestates[des[index]]<- true.b0 + true.b1*x1nodestates[des[index]] + true.b2*x2nodestates[des[index]]
c<- true.sigma.tau^2*(1-exp(-true.alpha.tau*treelength[index]))/(4*true.alpha.tau)
k<- (4*true.theta.tau*true.alpha.tau)/true.sigma.tau^2
lambda<-4*true.alpha.tau*exp(-true.alpha.tau*treelength[index])/(true.sigma.tau^2*(1-exp(-true.alpha.tau*treelength[index])))*sigmasqnodestates[anc[index]]
tmp = rchisq(n=1, df=k, ncp = lambda)
sig_u <- c*tmp
sigmasqnodestates[des[index]]<-sig_u
sigma.sq.theta<- true.b1^2*true.sigma.sq.x + true.b2^2*true.sigma.sq.x
#inttheta<-integrate(oubmbmintegrand,lower=0 ,upper=treelength[index], alpha.y=true.alpha.y)
A1<- (true.alpha.y*optimnodestates[des[index]]/ (true.alpha.y-true.alpha.x)) *(exp((true.alpha.y-true.alpha.x)*treelength[index]) -1)
theta1<-0
A2<- theta1*(exp(true.alpha.y*treelength[index])-1) - (true.alpha.y*theta1/(true.alpha.y-true.alpha.x))*(exp((true.alpha.y-true.alpha.x)*treelength[index]) -1)
# WRONG A3<- integrate(int3intgrand,lower=0,upper=treelength[index],alpha.x=true.alpha.x,sigma.sq.theta=true.sigma.sq.theta,alpha.y=true.alpha.y)
A3<-1/(sigma.sq.theta*true.alpha.y^2)*rnorm(1,mean=0,sd=sqrt( (sigma.sq.theta*true.alpha.y^2)^3 *treelength[index]^3 /3 ))
INTtime<- A1+A2+A3
INT1<-exp(-true.alpha.y*treelength[index])*INTtime
a <- rnorm(n=1, mean=0, sd=sqrt(true.theta.tau^2*(exp(2*true.alpha.y*treelength[index])-1)/(2*true.alpha.y)))
b <- rnorm(n=1, mean=0, sd=sqrt(((sigmasqnodestates[des[index]]-true.theta.tau)^2/(2*(true.alpha.y-true.alpha.tau)))*(exp(2*(true.alpha.y-true.alpha.tau)*treelength[index])-1)))
# ((sigmasqnodestates[des[index]]-true.theta.tau)^2/(2*(true.alpha.y-true.alpha.tau)))
# *(exp(2*(true.alpha.y-true.alpha.tau)*treelength[index])-1)
#
outer.int.sum=0
for(outer.index in 1:n_t){
inner.int.sum = 0
for(inner.index in 1:n_s){
c<- true.sigma.tau^2*(1-exp(-true.alpha.tau*(inner.index/n_s)))/(4*true.alpha.tau)
k<- (4*true.theta.tau*true.alpha.tau)/true.sigma.tau^2
lambda<- 4*true.alpha.tau*exp(-true.alpha.tau*(inner.index/n_s))/(true.sigma.tau^2*(1-exp(-true.alpha.tau*(inner.index/n_s))))*sigmasqnodestates[des[index]]
tmp = rchisq(n=1, df=k, ncp = lambda)
sig_u <- c*tmp
inner.int.sum <- inner.int.sum + exp(true.alpha.tau*(inner.index/n_s))*rnorm(n=1,mean=0, sd=sqrt(1/n_s))*sqrt(sig_u)
}
outer.int.sum <- outer.int.sum + exp(-true.alpha.y*(outer.index/n_t))*inner.int.sum*rnorm(n=1,mean=0, sd=sqrt(1/n_t))
}
outer.int.sum
c <- true.sigma.tau*outer.int.sum
INTsigdWy <- exp(-true.alpha.y*treelength[index])*(a + b + c)
ynodestates[des[index]]<-ynodestates[anc[index]] + INT1 + INTsigdWy
}
ytipstates<-ynodestates[1:n]
print(ytipstates)
ytruetrait<-ytipstates
print(ytruetrait)
summarytrait=c(mean(ytruetrait),sd(ytruetrait))
##################NOT YET
model<-function(model.params,reg.params,root=root,tree=tree){
alpha.y<-model.params[1]
alpha.x<-model.params[2]
theta.x<-model.params[3]
sigma.sq.x<-model.params[4]
alpha.tau<-model.params[5]
theta.tau<-model.params[6]
sigma.tau<-model.params[7]
b0<-reg.params[1]
b1<-reg.params[2]
b2<-reg.params[3]
n<-Ntip(tree)
x1nodestates<-array(0,c(2*n-1))
x1nodestates[n+1]<-root
x2nodestates<-array(0,c(2*n-1))
x2nodestates[n+1]<-root
optimnodestates<-array(0,c(2*n-1))
optimnodestates[n+1]<-root
sigmasqnodestates<-array(0,c(2*n-1))
sigmasqnodestates[n+1]<-root
ynodestates<-array(0,c(2*n-1))
ynodestates[n+1]<-root
N<-dim(tree$edge)[1]
anc<-tree$edge[,1]
des<-tree$edge[,2]
treelength<-tree$edge.length
for(index in N:1){
x1ou.mean<-x1nodestates[anc[index]]*exp(-alpha.x*treelength[index]) + theta.x*(1-exp(-alpha.x*treelength[index]))
x1ou.sd<-sqrt((sigma.sq.x/(2*alpha.x))*(1-exp(-2*alpha.x*treelength[index])))
x1nodestates[des[index]]<-rnorm(n=1,mean=x1ou.mean,sd=x1ou.sd)
x2ou.mean<-x2nodestates[anc[index]]*exp(-alpha.x*treelength[index]) + theta.x*(1-exp(-alpha.x*treelength[index]))
x2ou.sd<-sqrt((sigma.sq.x/(2*alpha.x))*(1-exp(-2*alpha.x*treelength[index])))
x2nodestates[des[index]]<-rnorm(n=1,mean=x2ou.mean,sd=x2ou.sd)
optimnodestates[des[index]]<- b0 + b1*x1nodestates[des[index]] + b2*x2nodestates[des[index]]
c<- true.sigma.tau^2*(1-exp(-true.alpha.tau*treelength[index]))/(4*true.alpha.tau)
k<- (4*true.theta.tau*true.alpha.tau)/true.sigma.tau^2
lambda<-4*true.alpha.tau*exp(-true.alpha.tau*treelength[index])/(true.sigma.tau^2*(1-exp(-true.alpha.tau*treelength[index])))*sigmasqnodestates[anc[index]]
tmp = rchisq(n=1, df=k, ncp = lambda)
sig_u <- c*tmp
sigmasqnodestates[des[index]]<-sig_u
sigma.sq.theta<- b1^2*sigma.sq.x + b2^2*sigma.sq.x
#inttheta<-integrate(oubmbmintegrand,lower=0 ,upper=treelength[index], alpha.y=true.alpha.y)
A1<- (alpha.y*optimnodestates[des[index]]/ (alpha.y-alpha.x)) *(exp((alpha.y-alpha.x)*treelength[index]) -1)
theta1<-0
A2<- theta1*(exp(alpha.y*treelength[index])-1) - (alpha.y*theta1/(alpha.y-alpha.x))*(exp((alpha.y-alpha.x)*treelength[index]) -1)
A3<-1/(sigma.sq.theta*alpha.y^2)*rnorm(1,mean=0,sd=sqrt((sigma.sq.theta*alpha.y^2)^3 *treelength[index]^3 /3))
INTtime<- A1+A2+A3
INT1<-exp(-alpha.y*treelength[index])*INTtime
a <- rnorm(n=1, mean=0, sd=sqrt(true.theta.tau^2*(exp(2*true.alpha.y*treelength[index])-1)/(2*true.alpha.y)))
b <- rnorm(n=1, mean=0, sd=sqrt(((sigmasqnodestates[des[index]]-true.theta.tau)^2/(2*(true.alpha.y-true.alpha.tau)))*(exp(2*(true.alpha.y-true.alpha.tau)*treelength[index])-1)))
# ((sigmasqnodestates[des[index]]-true.theta.tau)^2/(2*(true.alpha.y-true.alpha.tau)))
# *(exp(2*(true.alpha.y-true.alpha.tau)*treelength[index])-1)
#
outer.int.sum=0
for(outer.index in 1:n_t){
inner.int.sum = 0
for(inner.index in 1:n_s){
c<- true.sigma.tau^2*(1-exp(-true.alpha.tau*(inner.index/n_s)))/(4*true.alpha.tau)
k<- (4*true.theta.tau*true.alpha.tau)/true.sigma.tau^2
lambda<- 4*true.alpha.tau*exp(-true.alpha.tau*(inner.index/n_s))/(true.sigma.tau^2*(1-exp(-true.alpha.tau*(inner.index/n_s))))*sigmasqnodestates[des[index]]
tmp = rchisq(n=1, df=k, ncp = lambda)
sig_u <- c*tmp
inner.int.sum <- inner.int.sum + exp(true.alpha.tau*(inner.index/n_s))*rnorm(n=1,mean=0, sd=sqrt(1/n_s))*sqrt(sig_u)
}
outer.int.sum <- outer.int.sum + exp(-true.alpha.y*(outer.index/n_t))*inner.int.sum*rnorm(n=1,mean=0, sd=sqrt(1/n_t))
}
outer.int.sum
c <- true.sigma.tau*outer.int.sum
INTsigdWy <- exp(-true.alpha.y*treelength[index])*(a + b + c)
ynodestates[des[index]]<-ynodestates[anc[index]] + INT1 + INTsigdWy
}
simtrait<-ynodestates[1:n]
return(c(mean(simtrait),sd(simtrait)))
}
ABC_acc<-function(model.params,reg.params,root=root,tree=tree,summarytrait=summarytrait){
alpha.y<-model.params[1]
alpha.x<-model.params[2]
theta.x<-model.params[3]
sigma.sq.x<-model.params[4]
alpha.tau<-model.params[5]
theta.tau<-model.params[6]
sigma.tau<-model.params[7]
b0<-reg.params[1]
b1<-reg.params[2]
b2<-reg.params[3]
if(alpha.y<=0 | alpha.x<=0 | theta.x<=0 |sigma.sq.x<=0 | alpha.tau<=0 | theta.tau<=0 |sigma.tau<=0){return(FALSE)}
summarysamples<-model(model.params,reg.params,root=root,tree=tree)
diffmean<-abs(summarysamples[1]-summarytrait[1])
diffsd<-abs(summarysamples[2]-summarytrait[2])
if((diffmean<0.1) & (diffsd <0.2)){
return(TRUE)}else{return(FALSE)}
}
run_MCMC_ABC<-function(startvalue,iterations,root=root,tree=tree,summarytrait=summarytrait){
chain<-array(0,dim=c(iterations+1,10))
chain[1,]<-startvalue
for(i in 1:iterations){
proposal<-rnorm(n=10,mean=chain[i,],sd=rep(1,10))
model.params.proposal<-proposal[1:7]
reg.params.proposal<-proposal[8:10]
if(ABC_acc(model.params.proposal,reg.params.proposal, root=root, tree=tree,summarytrait=summarytrait)){
chain[i+1,]<-proposal
}else{
chain[i+1,]<-chain[i,]
}
}
return(mcmc(chain))
}
posterior<-run_MCMC_ABC(c(true.alpha.y,true.alpha.x,true.theta.x,true.sigma.sq.x,true.alpha.tau,true.theta.tau,true.sigma.tau,true.b0,true.b1,true.b2),10000,root=root,tree=tree,summarytrait=summarytrait)
plot(posterior)
summary(posterior)
|
1f6ff464a1236ef87778bd03f73624853033430d
|
a0d9649db543993b406a1a221483f07542662a2a
|
/2017-06-21/entries-vs-discovery.R
|
32f60dc280abe48018f2281cf287386e996a9672
|
[] |
no_license
|
chrokh/rndsim-stats
|
01aee26576bac78903b90a7b8d263d36aaa305a4
|
b8f2eed3de395da9f977ad2b3829b94e89a6dd03
|
refs/heads/master
| 2021-01-20T16:24:33.543641
| 2017-08-30T13:28:36
| 2017-08-30T13:28:36
| 90,836,674
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 5,664
|
r
|
entries-vs-discovery.R
|
source('shared.R')
library(RColorBrewer)
# ARGUMENTS
# ==================
args <-
parseArgs(list(
make_option(
c('-i', '--input'),
default =NULL,
help ='dataset file path',
metavar ='file'),
make_option(
c('-o', '--output'),
default ='plot.png',
help ='output file name [default= %default]',
metavar ='file'),
make_option(
c('-c', '--cache'), default = '.',
help = 'cache folder [default= %default]',
metavar = 'folder')
),
function(args) !is.null(args$input))
# PREPARE
# ============================================
binSize <- 0.5
prepare <- function(df) {
print('Rename columns')
names(df)[names(df) == 'proj_type_discovery_rate'] <- 'discovery'
names(df)[names(df) == 'orgs_infcap_thresh'] <- 'thresh'
names(df)[names(df) == 'inv_rate'] <- 'rate'
names(df)[names(df) == 'proj_tot_cash'] <- 'cash'
names(df)[names(df) == 'interventions_tot_size'] <- 'intervention_size'
print('Removing initial discoveries')
df <- subset(df, df$discovery != 0)
print(head(df))
print('Subsetting on scenario')
df <- subset(df,
df$thresh >= 200 &
df$thresh <= 500 &
df$rate >= 0.2 &
df$cash <= 1500)
print('Round discovery rates')
df$discovery <- roundToNearest(df$discovery, binSize)
print('Counting entries')
df <- ddply(df, c(
'RUN',
'discovery',
'intervention',
'intervention_size'
), summarise,
tot_pois = countCompletes(proj_state),
projs = length(unique(PROJ))
)
return(df)
}
df <- getSet(args$input,
args$cache,
'entries-vs-discovery.csv',
prepare,
c('RUN',
'proj_type_discovery_rate',
'interventions_tot_size',
'intervention',
'proj_state',
'inv_rate',
'proj_tot_cash',
'orgs_infcap_thresh',
'PROJ'
))
# PLOTTING PREPARATION FUNCTION
# ============================================
prepareSet <- function(df) {
months <- 23 * 12
print('Recompute entry rate')
df$discovery <- df$projs / months
df$discovery <- roundToNearest(df$discovery, binSize)
print('Estimate number of market entries')
df$poi_estimate <- df$tot_pois / df$projs * df$discovery * months
print('Group by discovery rate')
df <- ddply(df, c(
'discovery',
'intervention_size'
), summarise,
pois = mean(poi_estimate))
}
# PLOTTING FUNCTION
# ============================================
plotSet <- function(df, context) {
interventions <- sort(unique(df$intervention_size))
generateColorscale <- colorRampPalette(c('red', 'orange', 'green'))
colorscale <- generateColorscale(length(interventions))
df$color <- colorscale[findInterval(df$intervention_size, interventions)]
plot(df$pois ~ df$discovery,
col = df$color,
ylab = 'Derived Mean Number of Market Entries Per Run',
xlab = paste('Monthly Entry Rate ( \u00B1', binSize / 2, ')'),
xaxt = 'n',
yaxt = 'n',
main = 'Derived Mean Market Entries Per Run vs Entry Rate',
ylim = c(min(context$pois), max(context$pois)),
pch = 19
)
for (bin in unique(df$intervention_size)) {
sub <- subset(df, df$intervention_size == bin)
lines(sub$pois ~ sub$discovery,
col = sub$color)
}
# Ticks
xticks <- seq(round(min(context$discovery)), round(max(context$discovery)), by = 1)
yticks <- seq(roundToNearest(min(context$pois), 10), roundToNearest(max(df$pois), 10), by = 10)
axis(side=1, col='black', at = xticks)
axis(side=2, col='black', las = 2, at = yticks)
# Minor grid
xticks <- seq(round(min(context$discovery)), round(max(context$discovery)), by = 2)
yticks <- seq(roundToNearest(min(context$pois), 10), roundToNearest(max(df$pois), 10), by = 20)
abline(h=yticks, v=xticks, col='gray', lty=3)
# Major grid
xticks <- seq(round(min(context$discovery)) + 1, round(max(context$discovery)), by = 2)
yticks <- seq(roundToNearest(min(context$pois), 10) + 10, roundToNearest(max(df$pois), 10), by = 20)
abline(h=yticks, v=xticks, col='gray')
legend('topleft', levels(factor(df$intervention_size)),
pch = 19, col = df$color, bty = 'n', title='Intervention',
cex = 1)
}
# PLOT
# ============================================
plotToPortrait(args$output)
#layout(matrix(c(
# 1,1,1,1,1,1,1,1,1,1,1,1,
# 2,2,2,2,2,2,2,2,2,2,2,2,
# 3), nrow = 25, byrow = TRUE))
layout(matrix(c(1,2), nrow=2, byrow = TRUE))
sub1 <- prepareSet(subset(df, df$intervention == 'FDMER'))
sub2 <- prepareSet(subset(df, df$intervention == 'PDMER'))
all <- rbind(sub1, sub2)
plotSet(sub1, all)
mtext('Full Delinkage (BP Threshold 200-500 + VC DR 20-30% + Revenues <= 1.5B)')
plotSet(sub2, all)
mtext('Partial Delinkage (BP Threshold 200-500 + VC DR 20-30% + Revenues <= 1.5B)')
#mtext('DERIVATION = entry_rate * 30 years * likelihood_of_reaching_market', outer=TRUE, cex=0.8, side=1, line=-2)
|
3c887cc6d69514176d3cd486c06c0efc1fc1c6b1
|
1930041c603bc542e02b921c02daf5e43ec11f7c
|
/R/get_privateHoldings.R
|
22dda9be23b92b9e47761237687d8117b6874a20
|
[] |
no_license
|
bplloyd/Core
|
826069468e1da5fdf0e2c631101ce5be38e21b9f
|
f7731b36c222f1c097a94d872ac1ac3f78f25ca2
|
refs/heads/master
| 2021-01-21T17:32:13.584931
| 2017-05-09T21:55:21
| 2017-05-09T21:55:21
| 81,851,307
| 0
| 0
| null | null | null | null |
UTF-8
|
R
| false
| false
| 324
|
r
|
get_privateHoldings.R
|
#' @include executeSP.R
#' @include abbToStrategy.R
#' @include make_paramString.R
get_privateHoldings = function(id=NA, strategy=NA, vintage=NA, active = NA)
{
paramString = make_paramString(id, strategy, vintage, active)
procString = "usp_get_PrivateHoldings"
executeSP(procString, paramString, schema = "Core")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.