content large_stringlengths 0 6.46M | path large_stringlengths 3 331 | license_type large_stringclasses 2 values | repo_name large_stringlengths 5 125 | language large_stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.46M | extension large_stringclasses 75 values | text stringlengths 0 6.46M |
|---|---|---|---|---|---|---|---|---|---|
data <- read.table("household_power_consumption.txt", header = TRUE, sep = ";")
data.use <- data[data$Date %in% c("1/2/2007","2/2/2007"), ]
date <- strptime(paste(data.use$Date, data.use$Time, sep = " "), "%d/%m/%Y %H:%M:%S")
gap <- as.numeric(data.use$Global_active_power)
sm1 <- as.numeric(data.use$Sub_metering_1)
sm2 <- as.numeric(data.use$Sub_metering_2)
sm3 <- as.numeric(data.use$Sub_metering_3)
grpow <- as.numeric(data.use$Global_reactive_power)
par(mfrow = c(2, 2))
with(data.use, {
hist(gap, col = "red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)", ylab = "Frequency")
plot(date, gap, type = "l", xlab = "", ylab = "Global Active Power (kilowatts)")
plot(date, sm1, type = "l", xlab = "", ylab = "Energy sub metering")
lines(date, sm2, type = "l", col = "red")
lines(date, sm3, type = "l", col = "blue")
legend("topright", inset = 0.05, bty = "n", c("Sub met. 1", "Sub_met. 2", "Sub_met. 3"), lty=1, lwd=1, cex = 0.5, y.intersp = 0.5, col=c("black", "red", "blue"))
plot(date, grpow, type = "l", xlab = "", ylab = "Global Reactive Power")
})
dev.copy(png, file = "Plot4.png", width = 480, height = 480)
dev.off() | /Plot4.R | no_license | nsaubes/ExData_Plotting1 | R | false | false | 1,236 | r | data <- read.table("household_power_consumption.txt", header = TRUE, sep = ";")
data.use <- data[data$Date %in% c("1/2/2007","2/2/2007"), ]
date <- strptime(paste(data.use$Date, data.use$Time, sep = " "), "%d/%m/%Y %H:%M:%S")
gap <- as.numeric(data.use$Global_active_power)
sm1 <- as.numeric(data.use$Sub_metering_1)
sm2 <- as.numeric(data.use$Sub_metering_2)
sm3 <- as.numeric(data.use$Sub_metering_3)
grpow <- as.numeric(data.use$Global_reactive_power)
par(mfrow = c(2, 2))
with(data.use, {
hist(gap, col = "red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)", ylab = "Frequency")
plot(date, gap, type = "l", xlab = "", ylab = "Global Active Power (kilowatts)")
plot(date, sm1, type = "l", xlab = "", ylab = "Energy sub metering")
lines(date, sm2, type = "l", col = "red")
lines(date, sm3, type = "l", col = "blue")
legend("topright", inset = 0.05, bty = "n", c("Sub met. 1", "Sub_met. 2", "Sub_met. 3"), lty=1, lwd=1, cex = 0.5, y.intersp = 0.5, col=c("black", "red", "blue"))
plot(date, grpow, type = "l", xlab = "", ylab = "Global Reactive Power")
})
dev.copy(png, file = "Plot4.png", width = 480, height = 480)
dev.off() |
#' This script projects the distribution of the market invariants for stock market (i.e. compounded returns)
#' from the estimation interval to the investment horizon.
#' Then it computes the distribution of prices at the investment horizon and performs the two-step mean-variance
#' optimization in terms of returns and relative portfolio weights.
#' Described in A. Meucci,"Risk and Asset Allocation", Springer, 2005, Chapter 6.
#'
#' @references
#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
#' "E 256 - Mean-variance pitfalls: horizon effect".
#'
#' See Meucci's script for "S_MeanVarianceHorizon.m" and "E 255 - Mean-variance pitfalls: two-step approach II" from the book.
#
#' @author Xavier Valls \email{flamejat@@gmail.com}
##################################################################################################################
### Load data
data("stockSeries");
##################################################################################################################
### Inputs
tau = 1/252; # time to horizon expressed in years
tau_tilde = 1/52; # estimation period expressed in years
nSim = 10000;
Budget = 100;
Zeta = 10; # risk aversion parameter
##################################################################################################################
### Estimation of weekly invariants stock market (compounded returns)
Week_C = diff( log( StockSeries$Prices.TimeSeries ) );
N = ncol( Week_C );
la = 0.1;
Shrk_Exp = matrix( 0, N, 1);
Exp_C_Hat = (1 - la) * matrix( apply( Week_C, 2, mean ) ) + la * Shrk_Exp;
lb = 0.1;
Shrk_Cov = diag( 1, N ) * sum( diag( cov( Week_C ) ) ) / N;
Cov_C_Hat = (1 - lb) * cov(Week_C) + lb * (Shrk_Cov);
##################################################################################################################
### Stock market projection to horizon and pricing
Exp_Hrzn_C_Hat = Exp_C_Hat * tau / tau_tilde;
Cov_Hrzn_C_Hat = Cov_C_Hat * tau / tau_tilde;
StockCompReturns_Scenarios = rmvnorm( nSim, Exp_Hrzn_C_Hat, Cov_Hrzn_C_Hat);
StockCurrent_Prices = matrix( StockSeries$Prices.TimeSeries[ nrow( StockSeries$Prices.TimeSeries ), ]);
StockMarket_Scenarios = ( matrix( 1, nSim, 1) %*% t(StockCurrent_Prices)) * exp( StockCompReturns_Scenarios );
##################################################################################################################
### MV inputs - analytical
Stock = ConvertCompoundedReturns2Price(Exp_Hrzn_C_Hat, Cov_Hrzn_C_Hat, StockCurrent_Prices);
print( Stock$Exp_Prices );
print( Stock$Cov_Prices );
##################################################################################################################
### MV inputs - numerical
StockExp_Prices = matrix( apply( StockMarket_Scenarios, 2, mean ));
StockCov_Prices = cov( StockMarket_Scenarios );
print(StockExp_Prices);
print(StockCov_Prices);
StockExp_LinRets = StockExp_Prices / StockCurrent_Prices - 1;
StockCov_LinRets = diag( c(1 / StockCurrent_Prices) ) %*% StockCov_Prices %*% diag( c(1 / StockCurrent_Prices) );
##################################################################################################################
### Portolio optimization
# step 1: MV quadratic optimization to determine one-parameter frontier of quasi-optimal solutions ...
NumPortf = 40;
EFR = EfficientFrontierReturns( NumPortf, StockCov_LinRets, StockExp_LinRets );
# step 2: ...evaluate satisfaction for all allocations on the frontier ...
Store_Satisfaction = NULL;
for( n in 1 : NumPortf )
{
Allocation = matrix( EFR$Composition[ n, ] ) * Budget / StockCurrent_Prices;
Objective_Scenario = StockMarket_Scenarios %*% Allocation;
Utility = -exp( -1 / Zeta * Objective_Scenario);
ExpU = apply( Utility, 2, mean );
Satisfaction = -Zeta * log( -ExpU );
Store_Satisfaction = cbind( Store_Satisfaction, Satisfaction ); ##ok<AGROW>
}
# ... and pick the best
Optimal_Index = which.max(Store_Satisfaction);
Optimal_Allocation = EFR$Composition[ Optimal_Index, ];
##################################################################################################################
### Plots
dev.new();
par(mfrow = c( 2, 1 ) );
# rets MV frontier
h = plot(EFR$Volatility, EFR$ExpectedValue, "l", lwd = 2, xlab = "st.dev. rets.", ylab = "exp.val rets.",
xlim = c( EFR$Volatility[1], EFR$Volatility[ length(EFR$Volatility) ]), ylim = c( min( EFR$ExpectedValue ), max( EFR$ExpectedValue ) ) );
# satisfaction as function of st.deviation on the frontier
h = plot( EFR$Volatility, Store_Satisfaction, "l", lwd = 2, xlab = "st.dev. rets.", ylab = "satisfaction",
xlim = c( EFR$Volatility[1], EFR$Volatility[ length(EFR$Volatility) ]), ylim = c( min(Store_Satisfaction), max(Store_Satisfaction) ) );
| /demo/S_MeanVarianceHorizon.R | no_license | runiaruni/Meucci | R | false | false | 4,806 | r | #' This script projects the distribution of the market invariants for stock market (i.e. compounded returns)
#' from the estimation interval to the investment horizon.
#' Then it computes the distribution of prices at the investment horizon and performs the two-step mean-variance
#' optimization in terms of returns and relative portfolio weights.
#' Described in A. Meucci,"Risk and Asset Allocation", Springer, 2005, Chapter 6.
#'
#' @references
#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
#' "E 256 - Mean-variance pitfalls: horizon effect".
#'
#' See Meucci's script for "S_MeanVarianceHorizon.m" and "E 255 - Mean-variance pitfalls: two-step approach II" from the book.
#
#' @author Xavier Valls \email{flamejat@@gmail.com}
##################################################################################################################
### Load data
data("stockSeries");
##################################################################################################################
### Inputs
tau = 1/252; # time to horizon expressed in years
tau_tilde = 1/52; # estimation period expressed in years
nSim = 10000;
Budget = 100;
Zeta = 10; # risk aversion parameter
##################################################################################################################
### Estimation of weekly invariants stock market (compounded returns)
Week_C = diff( log( StockSeries$Prices.TimeSeries ) );
N = ncol( Week_C );
la = 0.1;
Shrk_Exp = matrix( 0, N, 1);
Exp_C_Hat = (1 - la) * matrix( apply( Week_C, 2, mean ) ) + la * Shrk_Exp;
lb = 0.1;
Shrk_Cov = diag( 1, N ) * sum( diag( cov( Week_C ) ) ) / N;
Cov_C_Hat = (1 - lb) * cov(Week_C) + lb * (Shrk_Cov);
##################################################################################################################
### Stock market projection to horizon and pricing
Exp_Hrzn_C_Hat = Exp_C_Hat * tau / tau_tilde;
Cov_Hrzn_C_Hat = Cov_C_Hat * tau / tau_tilde;
StockCompReturns_Scenarios = rmvnorm( nSim, Exp_Hrzn_C_Hat, Cov_Hrzn_C_Hat);
StockCurrent_Prices = matrix( StockSeries$Prices.TimeSeries[ nrow( StockSeries$Prices.TimeSeries ), ]);
StockMarket_Scenarios = ( matrix( 1, nSim, 1) %*% t(StockCurrent_Prices)) * exp( StockCompReturns_Scenarios );
##################################################################################################################
### MV inputs - analytical
Stock = ConvertCompoundedReturns2Price(Exp_Hrzn_C_Hat, Cov_Hrzn_C_Hat, StockCurrent_Prices);
print( Stock$Exp_Prices );
print( Stock$Cov_Prices );
##################################################################################################################
### MV inputs - numerical
StockExp_Prices = matrix( apply( StockMarket_Scenarios, 2, mean ));
StockCov_Prices = cov( StockMarket_Scenarios );
print(StockExp_Prices);
print(StockCov_Prices);
StockExp_LinRets = StockExp_Prices / StockCurrent_Prices - 1;
StockCov_LinRets = diag( c(1 / StockCurrent_Prices) ) %*% StockCov_Prices %*% diag( c(1 / StockCurrent_Prices) );
##################################################################################################################
### Portolio optimization
# step 1: MV quadratic optimization to determine one-parameter frontier of quasi-optimal solutions ...
NumPortf = 40;
EFR = EfficientFrontierReturns( NumPortf, StockCov_LinRets, StockExp_LinRets );
# step 2: ...evaluate satisfaction for all allocations on the frontier ...
Store_Satisfaction = NULL;
for( n in 1 : NumPortf )
{
Allocation = matrix( EFR$Composition[ n, ] ) * Budget / StockCurrent_Prices;
Objective_Scenario = StockMarket_Scenarios %*% Allocation;
Utility = -exp( -1 / Zeta * Objective_Scenario);
ExpU = apply( Utility, 2, mean );
Satisfaction = -Zeta * log( -ExpU );
Store_Satisfaction = cbind( Store_Satisfaction, Satisfaction ); ##ok<AGROW>
}
# ... and pick the best
Optimal_Index = which.max(Store_Satisfaction);
Optimal_Allocation = EFR$Composition[ Optimal_Index, ];
##################################################################################################################
### Plots
dev.new();
par(mfrow = c( 2, 1 ) );
# rets MV frontier
h = plot(EFR$Volatility, EFR$ExpectedValue, "l", lwd = 2, xlab = "st.dev. rets.", ylab = "exp.val rets.",
xlim = c( EFR$Volatility[1], EFR$Volatility[ length(EFR$Volatility) ]), ylim = c( min( EFR$ExpectedValue ), max( EFR$ExpectedValue ) ) );
# satisfaction as function of st.deviation on the frontier
h = plot( EFR$Volatility, Store_Satisfaction, "l", lwd = 2, xlab = "st.dev. rets.", ylab = "satisfaction",
xlim = c( EFR$Volatility[1], EFR$Volatility[ length(EFR$Volatility) ]), ylim = c( min(Store_Satisfaction), max(Store_Satisfaction) ) );
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/speedestimates.R
\name{rho}
\alias{rho}
\title{Probability of fixation in a Moran process}
\usage{
rho(i, K, r)
}
\arguments{
\item{i}{number of cells of the focus type}
\item{K}{deme carrying capacity}
\item{r}{relative fitness of the focus type}
}
\value{
The fixation probability.
}
\description{
Probability of fixation in a Moran process
}
\examples{
rho(1, 8, 1.1)
}
| /man/rho.Rd | no_license | robjohnnoble/demonanalysis | R | false | true | 453 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/speedestimates.R
\name{rho}
\alias{rho}
\title{Probability of fixation in a Moran process}
\usage{
rho(i, K, r)
}
\arguments{
\item{i}{number of cells of the focus type}
\item{K}{deme carrying capacity}
\item{r}{relative fitness of the focus type}
}
\value{
The fixation probability.
}
\description{
Probability of fixation in a Moran process
}
\examples{
rho(1, 8, 1.1)
}
|
suppressPackageStartupMessages(library(dplyr))
data("usz_13c")
data = usz_13c %>%
dplyr::filter( patient_id %in%
c("norm_001", "norm_002", "norm_004", "norm_007", "pat_004", "pat_012", "pat_023")) %>%
cleanup_data()
fit = nls_fit(data)
cm = comment(fit$data)
test_that("Result with default parameters is tbl_df with required columns",{
cf = coef_diff_by_group(fit)
expect_s3_class(cf, "tbl_df")
expect_s3_class(cf, "coef_diff_by_group")
expect_identical(ncol(cf), 7L)
expect_identical(nrow(cf), 54L)
expect_lt(min(cf$p.value), 5e-8)
expect_equal(length(unique(cf$groups)), 6)
expect_equal(comment(cf), cm)
})
test_that("Result with Dunnett contrast only returns 3 groups",{
cf = coef_diff_by_group(fit, mcp_group = "Dunnett")
expect_s3_class(cf, "tbl_df")
expect_s3_class(cf, "coef_diff_by_group")
expect_identical(ncol(cf), 7L)
expect_identical(nrow(cf), 27L)
expect_lt(min(cf$p.value), 5.e-8)
expect_equal(unique(cf$groups),
c("liquid_patient - liquid_normal", "solid_normal - liquid_normal",
"solid_patient - liquid_normal" ))
})
test_that("Only Dunnett and Tukey are allowed for mcp_group",{
expect_error(coef_diff_by_group(fit, mcp_group = "blub"))
})
test_that("Fit must be of class breathtestfit",{
expect_error(coef_diff_by_group(NULL))
})
test_that("Correct Dunnett contrast when reference value is given",{
coef(fit)$group
cf = coef_diff_by_group(fit, mcp_group = "Dunnett", reference_group = "solid_patient")
expect_equal(unique(cf$groups),
c("liquid_normal - solid_patient",
"liquid_patient - solid_patient",
"solid_normal - solid_patient"))
})
test_that("nlme_fit can be used to compute coefficients",{
skip_on_cran()
fit = nlme_fit(data)
cf = coef_diff_by_group(fit)
expect_s3_class(cf, "tbl_df")
expect_s3_class(cf, "coef_diff_by_group")
})
digs = function(x){
nchar(stringr::str_replace_all(paste(abs(x)), "[0\\.]",""))
}
test_that("Options digits is served",{
options(digits = 4)
cf = coef_diff_by_group(fit)
expect_s3_class(cf, "tbl_df")
expect_lte(digs(cf[[1,"estimate"]]) ,4L)
expect_lte(digs(cf[[1,"conf.low"]]), 4L)
expect_lte(digs(cf[[1,"conf.high"]]),4L)
})
test_that("NULL returned if there is only one group", {
data = usz_13c %>%
dplyr::filter( patient_id %in%
c("pat_001", "pat_002","pat_003")) %>%
cleanup_data()
fit = nls_fit(data)
cf = coef_diff_by_group(fit)
expect_null(cf)
})
| /tests/testthat/test_coef_diff_by_group.R | no_license | dmenne/breathtestcore | R | false | false | 2,461 | r | suppressPackageStartupMessages(library(dplyr))
data("usz_13c")
data = usz_13c %>%
dplyr::filter( patient_id %in%
c("norm_001", "norm_002", "norm_004", "norm_007", "pat_004", "pat_012", "pat_023")) %>%
cleanup_data()
fit = nls_fit(data)
cm = comment(fit$data)
test_that("Result with default parameters is tbl_df with required columns",{
cf = coef_diff_by_group(fit)
expect_s3_class(cf, "tbl_df")
expect_s3_class(cf, "coef_diff_by_group")
expect_identical(ncol(cf), 7L)
expect_identical(nrow(cf), 54L)
expect_lt(min(cf$p.value), 5e-8)
expect_equal(length(unique(cf$groups)), 6)
expect_equal(comment(cf), cm)
})
test_that("Result with Dunnett contrast only returns 3 groups",{
cf = coef_diff_by_group(fit, mcp_group = "Dunnett")
expect_s3_class(cf, "tbl_df")
expect_s3_class(cf, "coef_diff_by_group")
expect_identical(ncol(cf), 7L)
expect_identical(nrow(cf), 27L)
expect_lt(min(cf$p.value), 5.e-8)
expect_equal(unique(cf$groups),
c("liquid_patient - liquid_normal", "solid_normal - liquid_normal",
"solid_patient - liquid_normal" ))
})
test_that("Only Dunnett and Tukey are allowed for mcp_group",{
expect_error(coef_diff_by_group(fit, mcp_group = "blub"))
})
test_that("Fit must be of class breathtestfit",{
expect_error(coef_diff_by_group(NULL))
})
test_that("Correct Dunnett contrast when reference value is given",{
coef(fit)$group
cf = coef_diff_by_group(fit, mcp_group = "Dunnett", reference_group = "solid_patient")
expect_equal(unique(cf$groups),
c("liquid_normal - solid_patient",
"liquid_patient - solid_patient",
"solid_normal - solid_patient"))
})
test_that("nlme_fit can be used to compute coefficients",{
skip_on_cran()
fit = nlme_fit(data)
cf = coef_diff_by_group(fit)
expect_s3_class(cf, "tbl_df")
expect_s3_class(cf, "coef_diff_by_group")
})
digs = function(x){
nchar(stringr::str_replace_all(paste(abs(x)), "[0\\.]",""))
}
test_that("Options digits is served",{
options(digits = 4)
cf = coef_diff_by_group(fit)
expect_s3_class(cf, "tbl_df")
expect_lte(digs(cf[[1,"estimate"]]) ,4L)
expect_lte(digs(cf[[1,"conf.low"]]), 4L)
expect_lte(digs(cf[[1,"conf.high"]]),4L)
})
test_that("NULL returned if there is only one group", {
data = usz_13c %>%
dplyr::filter( patient_id %in%
c("pat_001", "pat_002","pat_003")) %>%
cleanup_data()
fit = nls_fit(data)
cf = coef_diff_by_group(fit)
expect_null(cf)
})
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data_manip_utils.R
\name{quotemeta}
\alias{quotemeta}
\title{Escape a string for use in a Perl-compatible regular expression}
\usage{
quotemeta(string)
}
\arguments{
\item{string}{The string to escape}
}
\value{
\code{string}, with all non-word characters escaped with backslashes.
Note that this strategy does not work for R's own regular
expression syntax, so you should specify \code{perl = TRUE}, or an
equivalent option, when using this to construct a regular
expression.
}
\description{
This is an implementation of Perl's \code{quotemeta} operator. It is
meant for escaping any characters that might have special meanings
in a PCRE.
}
\examples{
s <- "A (string) with [many] regex *characters* in it."
grepl(s, s, perl = TRUE)
quotemeta(s)
# After escaping, the string matches itself.
grepl(quotemeta(s), s, perl = TRUE)
}
| /man/quotemeta.Rd | no_license | DarwinAwardWinner/rctutils | R | false | true | 911 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data_manip_utils.R
\name{quotemeta}
\alias{quotemeta}
\title{Escape a string for use in a Perl-compatible regular expression}
\usage{
quotemeta(string)
}
\arguments{
\item{string}{The string to escape}
}
\value{
\code{string}, with all non-word characters escaped with backslashes.
Note that this strategy does not work for R's own regular
expression syntax, so you should specify \code{perl = TRUE}, or an
equivalent option, when using this to construct a regular
expression.
}
\description{
This is an implementation of Perl's \code{quotemeta} operator. It is
meant for escaping any characters that might have special meanings
in a PCRE.
}
\examples{
s <- "A (string) with [many] regex *characters* in it."
grepl(s, s, perl = TRUE)
quotemeta(s)
# After escaping, the string matches itself.
grepl(quotemeta(s), s, perl = TRUE)
}
|
lagp <- function(x, p){
return(c(rep(0,p), x[1:(length(x)-p)]))
}
CMean <- function(b) {
b <- b[b != 0]
if (length(b) > 0)
return(mean(b))
return(0)
}
calculate_distances <- function(all_markets, data, id, i, warping_limit, matches, dtw_emphasis){
row <- 1
ThisMarket <- all_markets[i]
distances <- data.frame(matrix(nrow=length(all_markets), ncol=5))
names(distances) <- c(id, "BestControl", "RelativeDistance", "Correlation", "Length")
messages <- 0
for (j in 1:length(all_markets)){
ThatMarket <- all_markets[j]
distances[row, id] <- ThisMarket
distances[row, "BestControl"] <- ThatMarket
mkts <- create_market_vectors(data, ThisMarket, ThatMarket)
test <- mkts[[1]]
ref <- mkts[[2]]
dates <- mkts[[3]]
if ((var(test)==0 | length(test)<=2*warping_limit+1) & messages==0){
print(paste0("NOTE: test market ", ThisMarket, " has insufficient data or no variance and hence will be excluded"))
messages <- messages + 1
}
if (ThisMarket != ThatMarket & messages==0 & var(ref)>0 & length(test)>2*warping_limit){
if (dtw_emphasis>0){
dist <- dtw(test, ref, window.type=sakoeChibaWindow, window.size=warping_limit)$distance / abs(sum(test))
} else{
dist <- 0
}
distances[row, "Correlation"] <- cor(test, ref)
distances[row, "RelativeDistance"] <- dist
distances[row, "Skip"] <- FALSE
distances[row, "Length"] <- length(ref)
} else{
distances[row, "Skip"] <- TRUE
distances[row, "RelativeDistance"] <- NA
distances[row, "Correlation"] <- NA
distances[row, "Length"] <- NA
}
row <- row + 1
}
distances$matches <- matches
distances$w <- dtw_emphasis
distances <- dplyr::filter(distances, Skip==FALSE) %>%
dplyr::mutate(dist_rank=rank(RelativeDistance)) %>%
dplyr::mutate(corr_rank=rank(-Correlation)) %>%
dplyr::mutate(combined_rank=w*dist_rank+(1-w)*corr_rank) %>%
dplyr::arrange(combined_rank) %>%
dplyr::select(-dist_rank, -Skip, -combined_rank, -corr_rank) %>%
dplyr::mutate(rank=row_number()) %>%
dplyr::filter(rank<=matches) %>%
dplyr::select(-matches, -w)
distances$MatchingStartDate <- min(dates)
distances$MatchingEndDate <- max(dates)
return(distances)
}
stopif <- function(value, clause, message){
if (value==clause){
stop(message)
}
}
check_inputs <- function(data=NULL, id=NULL, matching_variable=NULL, date_variable=NULL){
stopif(is.null(data), TRUE, "ERROR: No data is provided")
stopif(is.null(id), TRUE, "ERROR: No ID is provided")
stopif(is.null(matching_variable), TRUE, "ERROR: No matching metric is provided")
stopif(is.null(date_variable), TRUE, "ERROR: No date variable is provided")
stopif(id %in% names(data), FALSE, "ERROR: ID variable not found in input data")
stopif(date_variable %in% names(data), FALSE, "ERROR: date variable not found in input data")
stopif(matching_variable %in% names(data), FALSE, "ERROR: matching metric not found in input data")
stopif(length(unique(data[[id]]))>2, FALSE, "ERROR: Need at least 3 unique markets")
}
#' @importFrom reshape2 melt dcast
create_market_vectors <- function(data, test_market, ref_market){
d <- subset(data, !is.na(match_var))
test <- subset(d, id_var==test_market)[,c("date_var", "match_var")]
names(test)[2] <- "y"
if (length(ref_market)==1){
ref <- subset(d, id_var == ref_market[1])[,c("date_var", "match_var")]
names(ref)[2] <- "x1"
f <- dplyr::inner_join(test, ref, by="date_var")
return(list(as.numeric(f$y), as.numeric(f$x1), as.Date(f$date_var)))
} else if (length(ref_market)>1){
ref <- reshape2::dcast(subset(d, id_var %in% ref_market), date_var ~ id_var, value.var="match_var")
names(ref) <- c("date_var", paste0("x", seq(1:length(ref_market))))
f <- data.frame(dplyr::inner_join(test, ref, by="date_var"))
return(list(as.numeric(f$y), dplyr::select(f, num_range("x", 1:length(ref_market))), as.Date(f$date_var)))
}
}
mape_no_zeros <- function(test, ref){
d <- cbind.data.frame(test, ref)
d <- subset(d, abs(test)>0)
return(mean(abs(lm(test ~ ref, data=d)$residuals)/d$test))
}
dw <- function(y, yhat){
res <- y - yhat
lagres <- lagp(res, 1)
r <- cor(res[2:length(res)], lagres[2:length(lagres)])
return(2*(1-r))
}
#' For each market, find the best matching control market
#'
#' \code{best_matches} finds the best matching control markets for each market in the dataset
#' using dynamic time warping (\code{dtw} package). The algorithm simply loops through all viable candidates for each
#' market in a parallel fashion, and then ranks by distance and/or correlation.
#'
#' @param data input data.frame for analysis. The dataset should be structured as "stacked" time series (i.e., a panel dataset).
#' In other words, markets are rows and not columns -- we have a unique row for each area/time combination.
#' @param id_variable the name of the variable that identifies the markets
#' @param date_variable the time stamp variable
#' @param matching_variable the variable (metric) used to match the markets. For example, this could be sales or new customers
#' @param parallel set to TRUE for parallel processing. Default is TRUE
#' @param warping_limit the warping limit used for matching. Default is 1,
#' which means that a single query value can be mapped to at most 2 reference values.
#' @param start_match_period the start date of the matching period (pre period).
#' Must be a character of format "YYYY-MM-DD" -- e.g., "2015-01-01"
#' @param end_match_period the end date of the matching period (pre period).
#' Must be a character of format "YYYY-MM-DD" -- e.g., "2015-10-01"
#' @param matches Number of matching markets to keep in the output
#' @param dtw_emphasis Number from 0 to 1. The amount of emphasis placed on dtw distances, versus correlation, when ranking markets.
#' Default is 1 (all emphasis on dtw). If emphasis is set to 0, all emphasis would be put on correlation.
#' An emphasis of 0.5 would yield equal weighting.
#'
#' @import foreach
#' @importFrom parallel detectCores
#' @importFrom data.table rbindlist
#' @import dplyr
#' @import iterators
#' @import utils
#' @import dtw
#' @importFrom doParallel registerDoParallel stopImplicitCluster
#'
#' @export best_matches
#' @examples
#' ##-----------------------------------------------------------------------
#' ## Find best matches for each airport time series
#' ##-----------------------------------------------------------------------
#' library(MarketMatching)
#' data(weather, package="MarketMatching")
#' mm <- best_matches(data=weather, id="Area",
#' date_variable="Date",
#' matching_variable="Mean_TemperatureF",
#' parallel=FALSE,
#' start_match_period="2014-01-01",
#' end_match_period="2014-10-01")
#' head(mm$BestMatches)
#'
#' @usage
#' best_matches(data=NULL,
#' id_variable=NULL,
#' date_variable=NULL,
#' matching_variable=NULL,
#' warping_limit=1,
#' parallel=TRUE,
#' start_match_period=NULL,
#' end_match_period=NULL,
#' matches=5)
#'
#' @return Returns an object of type \code{market_matching}. The object has the
#' following elements:
#'
#' \item{\code{BestMatches}}{A data.frame that contains the best matches for each market in the input dataset}
#' \item{\code{Data}}{The raw data used to do the matching}
#' \item{\code{MarketID}}{The name of the market identifier}
#' \item{\code{MatchingMetric}}{The name of the matching variable}
#' \item{\code{DateVariable}}{The name of the date variable}
best_matches <- function(data=NULL, id_variable=NULL, date_variable=NULL, matching_variable=NULL, warping_limit=1, parallel=TRUE, start_match_period=NULL, end_match_period=NULL, matches=5, dtw_emphasis=1){
## Check the start date and end dates
stopif(is.null(start_match_period), TRUE, "No start date provided")
stopif(is.null(end_match_period), TRUE, "No end date provided")
# Clean up the emphasis
if (is.null(dtw_emphasis)){
dtw_emphasis<-1
} else if (dtw_emphasis>1){
dtw_emphasis<-1
} else if(dtw_emphasis<0){
dtw_emphasis<-0
}
## check the inputs
check_inputs(data=data, id=id_variable, matching_variable=matching_variable, date_variable=date_variable)
data$date_var <- data[[date_variable]]
data$id_var <- data[[id_variable]]
data$match_var <- data[[matching_variable]]
data <- dplyr::arrange(data, id_var, date_var) %>% ungroup() %>% select(id_var, date_var, match_var)
## save a reduced version of the data
saved_data <- data
## get a vector of all markets
all_markets <- unique(data$id_var)
## set up a list to hold all distance matrices
all_distances <- list()
## filter the dates
data <- dplyr::filter(data, date_var>=as.Date(start_match_period) & date_var<=as.Date(end_match_period))
## check if any data is left
stopif(nrow(data)>0, FALSE, "ERROR: no data left after filter for dates")
## loop through markets and compute distances
if (parallel==FALSE){
for (i in 1:length(all_markets)){
all_distances[[i]] <- calculate_distances(all_markets, data, id_variable, i, warping_limit, matches, dtw_emphasis)
}
shortest_distances <- data.frame(rbindlist(all_distances))
} else{
ncore <- detectCores()-1
registerDoParallel(ncore)
loop_result <- foreach(i=1:length(all_markets)) %dopar% {
calculate_distances(all_markets, data, id_variable, i, warping_limit, matches, dtw_emphasis)
}
shortest_distances <- data.frame(rbindlist(loop_result))
stopImplicitCluster()
}
### Return the results
object <- list(BestMatches=shortest_distances, Data=as.data.frame(saved_data), MarketID=id_variable, MatchingMetric=matching_variable, DateVariable=date_variable)
class(object) <- "matched_market"
return (object)
}
#' Given a test market, analyze the impact of an intervention
#'
#' \code{inference} Analyzes the causal impact of an intervention using the CausalImpact package, given a test market and a matched_market object from the best_matches function.
#' The function returns an object of type "market_inference" which contains the estimated impact of the intervention (absolute and relative).
#'
#' @param matched_markets A matched_market object created by the market_matching function
#' @param test_market The name of the test market (character)
#' @param end_post_period The end date of the post period. Must be a character of format "YYYY-MM-DD" -- e.g., "2015-11-01"
#' @param alpha Desired tail-area probability for posterior intervals. For example, 0.05 yields 0.95 intervals
#' @param prior_level_sd Prior SD for the local level term (Gaussian random walk). Default is 0.01. The bigger this number is, the more wiggliness is allowed for the local level term.
#' Note that more wiggly local level terms also translate into larger posterior intervals.
#' @param control_matches Number of matching control markets to use in the analysis
#' @importFrom scales comma
#' @import ggplot2
#' @import zoo
#' @export inference
#' @examples
#' library(MarketMatching)
#' ##-----------------------------------------------------------------------
#' ## Analyze causal impact of a made-up weather intervention in Copenhagen
#' ## Since this is weather data it is a not a very meaningful example.
#' ## This is merely to demonstrate the function.
#' ##-----------------------------------------------------------------------
#' data(weather, package="MarketMatching")
#' mm <- best_matches(data=weather, id="Area",
#' date_variable="Date",
#' matching_variable="Mean_TemperatureF",
#' parallel=FALSE,
#' warping_limit=1, # warping limit=1
#' dtw_emphasis=1, # rely only on dtw for pre-screening
#' matches=5, # request 5 matches
#' start_match_period="2014-01-01",
#' end_match_period="2014-10-01")
#' library(CausalImpact)
#' results <- inference(matched_markets=mm,
#' test_market="CPH",
#' end_post_period="2015-12-15",
#' prior_level_sd=0.002)
#' @usage
#' inference(matched_markets=NULL,
#' test_market=NULL,
#' end_post_period=NULL,
#' alpha=0.05,
#' prior_level_sd=0.01,
#' control_matches=5)
#'
#' @return Returns an object of type \code{inference}. The object has the
#' following elements:
#' \item{\code{AbsoluteEffect}}{The estimated absolute effect of the intervention}
#' \item{\code{AbsoluteEffectLower}}{The lower limit of the estimated absolute effect of the intervention.
#' This is based on the posterior interval of the counterfactual predictions.
#' The width of the interval is determined by the \code{alpha} parameter.}
#' \item{\code{AbsoluteEffectUpper}}{The upper limit of the estimated absolute effect of the intervention.
#' This is based on the posterior interval of the counterfactual predictions.
#' The width of the interval is determined by the \code{alpha} parameter.}
#' \item{\code{RelativeEffectLower}}{Same as the above, just for relative (percentage) effects}
#' \item{\code{RelativeEffectUpper}}{Same as the above, just for relative (percentage) effects}
#' \item{\code{TailProb}}{Posterior probability of a non-zero effect}
#' \item{\code{PrePeriodMAPE}}{Pre-intervention period MAPE}
#' \item{\code{DW}}{Durbin-Watson statistic. Should be close to 2.}
#' \item{\code{PlotActualVersusExpected}}{Plot of actual versus expected using \code{ggplot2}}
#' \item{\code{PlotCumulativeEffect}}{Plot of the cumulative effect using \code{ggplot2}}
#' \item{\code{PlotPointEffect}}{Plot of the pointwise effect using \code{ggplot2}}
#' \item{\code{PlotActuals}}{Plot of the actual values for the test and control markets using \code{ggplot2}}
#' \item{\code{PlotPriorLevelSdAnalysis}}{Plot of DW and MAPE for different values of the local level SE using \code{ggplot2}}
#' \item{\code{PlotLocalLevel}}{Plot of the local level term using \code{ggplot2}}
#' \item{\code{TestData}}{A \code{data.frame} with the test market data}
#' \item{\code{TestData}}{A \code{data.frame} with the data for the control markets}
#' \item{\code{PlotResiduals}}{Plot of the residuals using \code{ggplot2}}
#' \item{\code{TestName}}{The name of the test market}
#' \item{\code{TestName}}{The name of the control market}
#' \item{\code{zooData}}{A \code{zoo} time series object with the test and control data}
#' \item{\code{Predictions}}{Actual versus predicted values}
#' \item{\code{CausalImpactObject}}{The CausalImpact object created}
#' \item{\code{Coefficients}}{The average posterior coefficients}
inference <- function(matched_markets=NULL, test_market=NULL, end_post_period=NULL, alpha=0.05, prior_level_sd=0.01, control_matches=5, nseasons=1){
## copy the distances
mm <- dplyr::filter(matched_markets$BestMatches, rank<=control_matches)
data <- matched_markets$Data
mm$id_var <- mm[[names(mm)[1]]]
mm <- dplyr::arrange(mm, id_var, BestControl)
## check if the test market exists
stopif(test_market %in% unique(data$id_var), FALSE, paste0("test market ", test_market, " does not exist"))
## if an end date has not been provided, then choose the max of the data
if (is.null(end_post_period)){
end_post_period <- as.Date(max(subset(data, id_var==test_market)$date_var))
}
# filter for dates
MatchingStartDate <- as.Date(subset(mm, id_var==test_market)$MatchingStartDate[1])
MatchingEndDate <- as.Date(subset(mm, id_var==test_market)$MatchingEndDate[1])
data <- dplyr::filter(data, date_var>=MatchingStartDate & date_var<=as.Date(end_post_period))
## get the control market name
control_market <- subset(mm, id_var==test_market)$BestControl
## get the test and ref markets
mkts <- create_market_vectors(data, test_market, control_market)
y <- mkts[[1]]
ref <- mkts[[2]]
date <- mkts[[3]]
end_post_period <- max(date)
post_period <- date[date > as.Date(mm[1, "MatchingEndDate"])]
stopif(length(post_period)==0, TRUE, "ERROR: no valid data in the post period")
post_period_start_date <- min(post_period)
post_period_end_date <- max(post_period)
ts <- zoo(cbind.data.frame(y, ref), date)
## print the settings
cat("\t------------- Inputs -------------\n")
cat(paste0("\tTest Market: ", test_market, "\n"))
for (i in 1:length(control_market)){
cat(paste0("\tControl Market ", i, ": ", control_market[i], "\n"))
}
cat(paste0("\tMarket ID: ", matched_markets$MarketID, "\n"))
cat(paste0("\tDate Variable: ", matched_markets$DateVariable, "\n"))
cat(paste0("\tMatching (pre) Period Start Date: ", MatchingStartDate, "\n"))
cat(paste0("\tMatching (pre) Period End Date: ", MatchingEndDate, "\n"))
cat(paste0("\tPost Period Start Date: ", post_period_start_date, "\n"))
cat(paste0("\tPost Period End Date: ", post_period_end_date, "\n"))
cat(paste0("\tMatching Metric: ", matched_markets$MatchingMetric, "\n"))
cat(paste0("\tLocal Level Prior SD: ", prior_level_sd, "\n"))
cat(paste0("\tPosterior Intervals Tail Area: ", 100*(1-alpha), "%\n"))
cat("\n")
cat("\n")
## run the inference
pre.period <- c(as.Date(MatchingStartDate), as.Date(MatchingEndDate))
post.period <- c(as.Date(post_period_start_date), as.Date(post_period_end_date))
set.seed(2015)
impact <- CausalImpact(ts, pre.period, post.period, alpha=alpha, model.args=list(prior.level.sd=prior_level_sd, nseasons=nseasons))
## estimate betas for different values of prior sd
betas <- data.frame(matrix(nrow=11, ncol=4))
names(betas) <- c("SD", "SumBeta", "DW", "MAPE")
for (i in 0:20){
step <- (max(0.1, prior_level_sd) - min(0.001, prior_level_sd))/20
sd <- min(0.001, prior_level_sd) + step*i
m <- CausalImpact(ts, pre.period, post.period, alpha=alpha, model.args=list(prior.level.sd=sd))
burn <- SuggestBurn(0.1, m$model$bsts.model)
b <- sum(apply(m$model$bsts.model$coefficients[-(1:burn),], 2, CMean))
betas[i+1, "SD"] <- sd
betas[i+1, "SumBeta"] <- b
preperiod <- subset(m$series, cum.effect == 0)
betas[i+1, "DW"] <- dw(preperiod$response, preperiod$point.pred)
betas[i+1, "MAPE"] <- mape_no_zeros(preperiod$response, preperiod$point.pred)
}
## create statistics
results <- list()
results[[1]] <- impact$summary$AbsEffect[2]
results[[2]] <- impact$summary$AbsEffect.lower[2]
results[[3]] <- impact$summary$AbsEffect.upper[2]
results[[4]] <- impact$summary$RelEffect[2]
results[[5]] <- impact$summary$RelEffect.lower[2]
results[[6]] <- impact$summary$RelEffect.upper[2]
results[[7]] <- impact$summary$p[2]
## compute mape
preperiod <- subset(impact$series, cum.effect == 0)
preperiod$res <- preperiod$response - preperiod$point.pred
results[[8]] <- mape_no_zeros(preperiod$response, preperiod$point.pred)
results[[9]] <- dw(preperiod$response, preperiod$point.pred)
cat("\t------------- Model Stats -------------\n")
cat(paste0("\tMatching (pre) Period MAPE: ", round(100*results[[8]], 2) , "%\n"))
avg_coeffs <- data.frame(nrow=dim(impact$model$bsts.model$coefficients)[2]-1, ncol=2)
names(avg_coeffs) <- c("Market", "AverageBeta")
for (i in 2:dim(impact$model$bsts.model$coefficients)[2]){
avg_coeffs[i-1, "Market"] <- control_market[i-1]
avg_coeffs[i-1, "AverageBeta"] <- apply(impact$model$bsts.model$coefficients[-(1:burn),], 2, CMean)[i]
cat(paste0("\tBeta ", i-1, " [", control_market[i-1], "]: ", round(avg_coeffs[i-1, "AverageBeta"], 4) , "\n"))
}
cat(paste0("\tDW: ", round(results[[9]], 2) , "\n"))
cat("\n")
cat("\n")
ymin <- min(min(impact$series$response), min(impact$series$point.pred.lower), min(ref), min(y))
ymax <- max(max(impact$series$response), max(impact$series$point.pred.upper), max(ref), max(y))
## create actual versus predicted plots
avp <- cbind.data.frame(date, data.frame(impact$series)[,c("response", "point.pred", "point.pred.lower", "point.pred.upper")])
names(avp) <- c("Date", "Response", "Predicted", "lower_bound", "upper_bound")
avp$test_market <- test_market
results[[10]] <- ggplot(data=avp, aes(x=Date)) +
geom_line(aes(y=Response, colour = "Observed"), size=1.2) +
geom_ribbon(aes(ymin=lower_bound, ymax=upper_bound), fill="grey", alpha=0.3) +
geom_line(aes(y=Predicted, colour = "Expected"), size=1.2) +
theme_bw() + theme(legend.title = element_blank()) + ylab("") + xlab("") +
geom_vline(xintercept=as.numeric(MatchingEndDate), linetype=2) +
scale_y_continuous(labels = scales::comma, limits=c(ymin, ymax)) +
ggtitle(paste0("Test Market: ",test_market))
avp$test_market <- NULL
## create cumulative lift plots
plotdf <- cbind.data.frame(as.Date(row.names(data.frame(impact$series))), data.frame(impact$series)[,c("cum.effect", "cum.effect.lower", "cum.effect.upper")])
names(plotdf) <- c("Date", "Cumulative", "lower_bound", "upper_bound")
results[[11]] <- ggplot(data=plotdf, aes(x=Date, y=Cumulative)) + geom_line(size=1.2) + theme_bw() +
scale_y_continuous(labels = scales::comma) + ylab("Cumulative Effect") + xlab("") +
geom_vline(xintercept=as.numeric(MatchingEndDate), linetype=2) +
geom_ribbon(aes(ymin=lower_bound, ymax=upper_bound), fill="grey", alpha=0.3)
## create plots of the actual data
plotdf <- data[data$id_var %in% c(test_market, control_market),]
results[[12]] <- ggplot(data=plotdf, aes(x=date_var, y=match_var, colour=id_var)) +
geom_line() +
theme_bw() + theme(legend.title = element_blank(), axis.title.x = element_blank()) + ylab("") + xlab("Date") +
geom_vline(xintercept=as.numeric(MatchingEndDate), linetype=2) +
scale_y_continuous(labels = scales::comma, limits=c(ymin, ymax))
## plot betas at various local level SDs
results[[13]] <- ggplot(data=betas, aes(x=SD, y=Beta)) +
geom_line() +
theme_bw() + theme(legend.title = element_blank()) +
geom_vline(xintercept=as.numeric(prior_level_sd), linetype=2) + xlab("Local Level Prior SD")
## plot DWs and MAPEs at different SDs
plotdf <- melt(data=betas, id="SD")
results[[14]] <- ggplot(data=plotdf, aes(x=SD, y=value, colour=variable)) + geom_line() +
theme_bw() + theme(legend.title = element_blank()) +
geom_vline(xintercept=as.numeric(prior_level_sd), linetype=2) + xlab("Local Level Prior SD") +
facet_grid(variable ~ ., scales="free") + ylab("") + guides(colour=FALSE)
burn <- SuggestBurn(0.1, impact$model$bsts.model)
plotdf <- cbind.data.frame(date, colMeans(impact$model$bsts.model$state.contributions[-(1:burn), "trend", ])) %>% filter(date<=as.Date(MatchingEndDate))
names(plotdf) <- c("Date", "LocalLevel")
results[[15]] <- ggplot(data=plotdf, aes(x=Date, y=LocalLevel)) +
geom_line() +
theme_bw() + theme(legend.title = element_blank()) +
ylab("Local Level") + xlab("")
plotdf <- cbind.data.frame(date, data.frame(impact$series)[,c("response", "point.pred")]) %>% dplyr::filter(date<=as.Date(MatchingEndDate))
names(plotdf) <- c("Date", "y", "yhat")
plotdf$Residuals <- plotdf$y - plotdf$yhat
results[[16]] <- ggplot(data=plotdf, aes(x=Date, y=Residuals)) +
geom_line() +
theme_bw() + theme(legend.title = element_blank()) +
xlab("")
## create cumulative lift plots
plotdf <- cbind.data.frame(as.Date(row.names(data.frame(impact$series))), data.frame(impact$series)[,c("point.effect", "point.effect.lower", "point.effect.upper")])
names(plotdf) <- c("Date", "Pointwise", "lower_bound", "upper_bound")
results[[17]] <- ggplot(data=plotdf, aes(x=Date, y=Pointwise)) + geom_line(size=1.2) + theme_bw() +
scale_y_continuous(labels = scales::comma) + ylab("Point Effect") + xlab("") +
geom_vline(xintercept=as.numeric(MatchingEndDate), linetype=2) +
geom_ribbon(aes(ymin=lower_bound, ymax=upper_bound), fill="grey", alpha=0.3)
### print results
cat("\t------------- Effect Analysis -------------\n")
cat(paste0("\tAbsolute Effect: ", round(results[[1]],2), " [", round(results[[2]],2), ", ", round(results[[3]],2), "]\n"))
cat(paste0("\tRelative Effect: ", paste0(round(100*results[[4]],2), "%"), " [", paste0(round(100*results[[5]],2), "%"), ", ", paste0(round(100*results[[6]],2), "%"), "]\n"))
cat(paste0("\tProbability of a causal impact: ", paste0(round(100*(1-results[[7]]),4), "%\n")))
### return the results
object <- list(AbsoluteEffect=results[[1]], AbsoluteEffectLower=results[[2]], AbsoluteEffectUpper=results[[3]],
RelativeEffect=results[[4]], RelativeEffectLower=results[[5]], RelativeEffectUpper=results[[6]],
TailProb=results[[7]], PrePeriodMAPE=results[[8]], DW=results[[9]],
PlotActualVersusExpected=results[[10]], PlotCumulativeEffect=results[[11]], PlotPointEffect=results[[17]],
PlotActuals=results[[12]], PlotPriorLevelSdAnalysis=results[[14]],
PlotLocalLevel=results[[15]], TestData=y, ControlData=ref, PlotResiduals=results[[16]],
TestName=test_market, ControlName=control_market, ZooData=ts, Predictions=avp,
CausalImpactObject=impact, Coefficients=avg_coeffs)
class(object) <- "matched_market_inference"
return (object)
}
| /R/functions.R | permissive | BrianMiner/MarketMatching | R | false | false | 25,297 | r | lagp <- function(x, p){
return(c(rep(0,p), x[1:(length(x)-p)]))
}
CMean <- function(b) {
b <- b[b != 0]
if (length(b) > 0)
return(mean(b))
return(0)
}
calculate_distances <- function(all_markets, data, id, i, warping_limit, matches, dtw_emphasis){
row <- 1
ThisMarket <- all_markets[i]
distances <- data.frame(matrix(nrow=length(all_markets), ncol=5))
names(distances) <- c(id, "BestControl", "RelativeDistance", "Correlation", "Length")
messages <- 0
for (j in 1:length(all_markets)){
ThatMarket <- all_markets[j]
distances[row, id] <- ThisMarket
distances[row, "BestControl"] <- ThatMarket
mkts <- create_market_vectors(data, ThisMarket, ThatMarket)
test <- mkts[[1]]
ref <- mkts[[2]]
dates <- mkts[[3]]
if ((var(test)==0 | length(test)<=2*warping_limit+1) & messages==0){
print(paste0("NOTE: test market ", ThisMarket, " has insufficient data or no variance and hence will be excluded"))
messages <- messages + 1
}
if (ThisMarket != ThatMarket & messages==0 & var(ref)>0 & length(test)>2*warping_limit){
if (dtw_emphasis>0){
dist <- dtw(test, ref, window.type=sakoeChibaWindow, window.size=warping_limit)$distance / abs(sum(test))
} else{
dist <- 0
}
distances[row, "Correlation"] <- cor(test, ref)
distances[row, "RelativeDistance"] <- dist
distances[row, "Skip"] <- FALSE
distances[row, "Length"] <- length(ref)
} else{
distances[row, "Skip"] <- TRUE
distances[row, "RelativeDistance"] <- NA
distances[row, "Correlation"] <- NA
distances[row, "Length"] <- NA
}
row <- row + 1
}
distances$matches <- matches
distances$w <- dtw_emphasis
distances <- dplyr::filter(distances, Skip==FALSE) %>%
dplyr::mutate(dist_rank=rank(RelativeDistance)) %>%
dplyr::mutate(corr_rank=rank(-Correlation)) %>%
dplyr::mutate(combined_rank=w*dist_rank+(1-w)*corr_rank) %>%
dplyr::arrange(combined_rank) %>%
dplyr::select(-dist_rank, -Skip, -combined_rank, -corr_rank) %>%
dplyr::mutate(rank=row_number()) %>%
dplyr::filter(rank<=matches) %>%
dplyr::select(-matches, -w)
distances$MatchingStartDate <- min(dates)
distances$MatchingEndDate <- max(dates)
return(distances)
}
stopif <- function(value, clause, message){
if (value==clause){
stop(message)
}
}
check_inputs <- function(data=NULL, id=NULL, matching_variable=NULL, date_variable=NULL){
stopif(is.null(data), TRUE, "ERROR: No data is provided")
stopif(is.null(id), TRUE, "ERROR: No ID is provided")
stopif(is.null(matching_variable), TRUE, "ERROR: No matching metric is provided")
stopif(is.null(date_variable), TRUE, "ERROR: No date variable is provided")
stopif(id %in% names(data), FALSE, "ERROR: ID variable not found in input data")
stopif(date_variable %in% names(data), FALSE, "ERROR: date variable not found in input data")
stopif(matching_variable %in% names(data), FALSE, "ERROR: matching metric not found in input data")
stopif(length(unique(data[[id]]))>2, FALSE, "ERROR: Need at least 3 unique markets")
}
#' @importFrom reshape2 melt dcast
create_market_vectors <- function(data, test_market, ref_market){
d <- subset(data, !is.na(match_var))
test <- subset(d, id_var==test_market)[,c("date_var", "match_var")]
names(test)[2] <- "y"
if (length(ref_market)==1){
ref <- subset(d, id_var == ref_market[1])[,c("date_var", "match_var")]
names(ref)[2] <- "x1"
f <- dplyr::inner_join(test, ref, by="date_var")
return(list(as.numeric(f$y), as.numeric(f$x1), as.Date(f$date_var)))
} else if (length(ref_market)>1){
ref <- reshape2::dcast(subset(d, id_var %in% ref_market), date_var ~ id_var, value.var="match_var")
names(ref) <- c("date_var", paste0("x", seq(1:length(ref_market))))
f <- data.frame(dplyr::inner_join(test, ref, by="date_var"))
return(list(as.numeric(f$y), dplyr::select(f, num_range("x", 1:length(ref_market))), as.Date(f$date_var)))
}
}
mape_no_zeros <- function(test, ref){
d <- cbind.data.frame(test, ref)
d <- subset(d, abs(test)>0)
return(mean(abs(lm(test ~ ref, data=d)$residuals)/d$test))
}
dw <- function(y, yhat){
res <- y - yhat
lagres <- lagp(res, 1)
r <- cor(res[2:length(res)], lagres[2:length(lagres)])
return(2*(1-r))
}
#' For each market, find the best matching control market
#'
#' \code{best_matches} finds the best matching control markets for each market in the dataset
#' using dynamic time warping (\code{dtw} package). The algorithm simply loops through all viable candidates for each
#' market in a parallel fashion, and then ranks by distance and/or correlation.
#'
#' @param data input data.frame for analysis. The dataset should be structured as "stacked" time series (i.e., a panel dataset).
#' In other words, markets are rows and not columns -- we have a unique row for each area/time combination.
#' @param id_variable the name of the variable that identifies the markets
#' @param date_variable the time stamp variable
#' @param matching_variable the variable (metric) used to match the markets. For example, this could be sales or new customers
#' @param parallel set to TRUE for parallel processing. Default is TRUE
#' @param warping_limit the warping limit used for matching. Default is 1,
#' which means that a single query value can be mapped to at most 2 reference values.
#' @param start_match_period the start date of the matching period (pre period).
#' Must be a character of format "YYYY-MM-DD" -- e.g., "2015-01-01"
#' @param end_match_period the end date of the matching period (pre period).
#' Must be a character of format "YYYY-MM-DD" -- e.g., "2015-10-01"
#' @param matches Number of matching markets to keep in the output
#' @param dtw_emphasis Number from 0 to 1. The amount of emphasis placed on dtw distances, versus correlation, when ranking markets.
#' Default is 1 (all emphasis on dtw). If emphasis is set to 0, all emphasis would be put on correlation.
#' An emphasis of 0.5 would yield equal weighting.
#'
#' @import foreach
#' @importFrom parallel detectCores
#' @importFrom data.table rbindlist
#' @import dplyr
#' @import iterators
#' @import utils
#' @import dtw
#' @importFrom doParallel registerDoParallel stopImplicitCluster
#'
#' @export best_matches
#' @examples
#' ##-----------------------------------------------------------------------
#' ## Find best matches for each airport time series
#' ##-----------------------------------------------------------------------
#' library(MarketMatching)
#' data(weather, package="MarketMatching")
#' mm <- best_matches(data=weather, id="Area",
#' date_variable="Date",
#' matching_variable="Mean_TemperatureF",
#' parallel=FALSE,
#' start_match_period="2014-01-01",
#' end_match_period="2014-10-01")
#' head(mm$BestMatches)
#'
#' @usage
#' best_matches(data=NULL,
#' id_variable=NULL,
#' date_variable=NULL,
#' matching_variable=NULL,
#' warping_limit=1,
#' parallel=TRUE,
#' start_match_period=NULL,
#' end_match_period=NULL,
#' matches=5)
#'
#' @return Returns an object of type \code{market_matching}. The object has the
#' following elements:
#'
#' \item{\code{BestMatches}}{A data.frame that contains the best matches for each market in the input dataset}
#' \item{\code{Data}}{The raw data used to do the matching}
#' \item{\code{MarketID}}{The name of the market identifier}
#' \item{\code{MatchingMetric}}{The name of the matching variable}
#' \item{\code{DateVariable}}{The name of the date variable}
best_matches <- function(data=NULL, id_variable=NULL, date_variable=NULL, matching_variable=NULL, warping_limit=1, parallel=TRUE, start_match_period=NULL, end_match_period=NULL, matches=5, dtw_emphasis=1){
## Check the start date and end dates
stopif(is.null(start_match_period), TRUE, "No start date provided")
stopif(is.null(end_match_period), TRUE, "No end date provided")
# Clean up the emphasis
if (is.null(dtw_emphasis)){
dtw_emphasis<-1
} else if (dtw_emphasis>1){
dtw_emphasis<-1
} else if(dtw_emphasis<0){
dtw_emphasis<-0
}
## check the inputs
check_inputs(data=data, id=id_variable, matching_variable=matching_variable, date_variable=date_variable)
data$date_var <- data[[date_variable]]
data$id_var <- data[[id_variable]]
data$match_var <- data[[matching_variable]]
data <- dplyr::arrange(data, id_var, date_var) %>% ungroup() %>% select(id_var, date_var, match_var)
## save a reduced version of the data
saved_data <- data
## get a vector of all markets
all_markets <- unique(data$id_var)
## set up a list to hold all distance matrices
all_distances <- list()
## filter the dates
data <- dplyr::filter(data, date_var>=as.Date(start_match_period) & date_var<=as.Date(end_match_period))
## check if any data is left
stopif(nrow(data)>0, FALSE, "ERROR: no data left after filter for dates")
## loop through markets and compute distances
if (parallel==FALSE){
for (i in 1:length(all_markets)){
all_distances[[i]] <- calculate_distances(all_markets, data, id_variable, i, warping_limit, matches, dtw_emphasis)
}
shortest_distances <- data.frame(rbindlist(all_distances))
} else{
ncore <- detectCores()-1
registerDoParallel(ncore)
loop_result <- foreach(i=1:length(all_markets)) %dopar% {
calculate_distances(all_markets, data, id_variable, i, warping_limit, matches, dtw_emphasis)
}
shortest_distances <- data.frame(rbindlist(loop_result))
stopImplicitCluster()
}
### Return the results
object <- list(BestMatches=shortest_distances, Data=as.data.frame(saved_data), MarketID=id_variable, MatchingMetric=matching_variable, DateVariable=date_variable)
class(object) <- "matched_market"
return (object)
}
#' Given a test market, analyze the impact of an intervention
#'
#' \code{inference} Analyzes the causal impact of an intervention using the CausalImpact package, given a test market and a matched_market object from the best_matches function.
#' The function returns an object of type "market_inference" which contains the estimated impact of the intervention (absolute and relative).
#'
#' @param matched_markets A matched_market object created by the market_matching function
#' @param test_market The name of the test market (character)
#' @param end_post_period The end date of the post period. Must be a character of format "YYYY-MM-DD" -- e.g., "2015-11-01"
#' @param alpha Desired tail-area probability for posterior intervals. For example, 0.05 yields 0.95 intervals
#' @param prior_level_sd Prior SD for the local level term (Gaussian random walk). Default is 0.01. The bigger this number is, the more wiggliness is allowed for the local level term.
#' Note that more wiggly local level terms also translate into larger posterior intervals.
#' @param control_matches Number of matching control markets to use in the analysis
#' @importFrom scales comma
#' @import ggplot2
#' @import zoo
#' @export inference
#' @examples
#' library(MarketMatching)
#' ##-----------------------------------------------------------------------
#' ## Analyze causal impact of a made-up weather intervention in Copenhagen
#' ## Since this is weather data it is a not a very meaningful example.
#' ## This is merely to demonstrate the function.
#' ##-----------------------------------------------------------------------
#' data(weather, package="MarketMatching")
#' mm <- best_matches(data=weather, id="Area",
#' date_variable="Date",
#' matching_variable="Mean_TemperatureF",
#' parallel=FALSE,
#' warping_limit=1, # warping limit=1
#' dtw_emphasis=1, # rely only on dtw for pre-screening
#' matches=5, # request 5 matches
#' start_match_period="2014-01-01",
#' end_match_period="2014-10-01")
#' library(CausalImpact)
#' results <- inference(matched_markets=mm,
#' test_market="CPH",
#' end_post_period="2015-12-15",
#' prior_level_sd=0.002)
#' @usage
#' inference(matched_markets=NULL,
#' test_market=NULL,
#' end_post_period=NULL,
#' alpha=0.05,
#' prior_level_sd=0.01,
#' control_matches=5)
#'
#' @return Returns an object of type \code{inference}. The object has the
#' following elements:
#' \item{\code{AbsoluteEffect}}{The estimated absolute effect of the intervention}
#' \item{\code{AbsoluteEffectLower}}{The lower limit of the estimated absolute effect of the intervention.
#' This is based on the posterior interval of the counterfactual predictions.
#' The width of the interval is determined by the \code{alpha} parameter.}
#' \item{\code{AbsoluteEffectUpper}}{The upper limit of the estimated absolute effect of the intervention.
#' This is based on the posterior interval of the counterfactual predictions.
#' The width of the interval is determined by the \code{alpha} parameter.}
#' \item{\code{RelativeEffectLower}}{Same as the above, just for relative (percentage) effects}
#' \item{\code{RelativeEffectUpper}}{Same as the above, just for relative (percentage) effects}
#' \item{\code{TailProb}}{Posterior probability of a non-zero effect}
#' \item{\code{PrePeriodMAPE}}{Pre-intervention period MAPE}
#' \item{\code{DW}}{Durbin-Watson statistic. Should be close to 2.}
#' \item{\code{PlotActualVersusExpected}}{Plot of actual versus expected using \code{ggplot2}}
#' \item{\code{PlotCumulativeEffect}}{Plot of the cumulative effect using \code{ggplot2}}
#' \item{\code{PlotPointEffect}}{Plot of the pointwise effect using \code{ggplot2}}
#' \item{\code{PlotActuals}}{Plot of the actual values for the test and control markets using \code{ggplot2}}
#' \item{\code{PlotPriorLevelSdAnalysis}}{Plot of DW and MAPE for different values of the local level SE using \code{ggplot2}}
#' \item{\code{PlotLocalLevel}}{Plot of the local level term using \code{ggplot2}}
#' \item{\code{TestData}}{A \code{data.frame} with the test market data}
#' \item{\code{TestData}}{A \code{data.frame} with the data for the control markets}
#' \item{\code{PlotResiduals}}{Plot of the residuals using \code{ggplot2}}
#' \item{\code{TestName}}{The name of the test market}
#' \item{\code{TestName}}{The name of the control market}
#' \item{\code{zooData}}{A \code{zoo} time series object with the test and control data}
#' \item{\code{Predictions}}{Actual versus predicted values}
#' \item{\code{CausalImpactObject}}{The CausalImpact object created}
#' \item{\code{Coefficients}}{The average posterior coefficients}
inference <- function(matched_markets=NULL, test_market=NULL, end_post_period=NULL, alpha=0.05, prior_level_sd=0.01, control_matches=5, nseasons=1){
## copy the distances
mm <- dplyr::filter(matched_markets$BestMatches, rank<=control_matches)
data <- matched_markets$Data
mm$id_var <- mm[[names(mm)[1]]]
mm <- dplyr::arrange(mm, id_var, BestControl)
## check if the test market exists
stopif(test_market %in% unique(data$id_var), FALSE, paste0("test market ", test_market, " does not exist"))
## if an end date has not been provided, then choose the max of the data
if (is.null(end_post_period)){
end_post_period <- as.Date(max(subset(data, id_var==test_market)$date_var))
}
# filter for dates
MatchingStartDate <- as.Date(subset(mm, id_var==test_market)$MatchingStartDate[1])
MatchingEndDate <- as.Date(subset(mm, id_var==test_market)$MatchingEndDate[1])
data <- dplyr::filter(data, date_var>=MatchingStartDate & date_var<=as.Date(end_post_period))
## get the control market name
control_market <- subset(mm, id_var==test_market)$BestControl
## get the test and ref markets
mkts <- create_market_vectors(data, test_market, control_market)
y <- mkts[[1]]
ref <- mkts[[2]]
date <- mkts[[3]]
end_post_period <- max(date)
post_period <- date[date > as.Date(mm[1, "MatchingEndDate"])]
stopif(length(post_period)==0, TRUE, "ERROR: no valid data in the post period")
post_period_start_date <- min(post_period)
post_period_end_date <- max(post_period)
ts <- zoo(cbind.data.frame(y, ref), date)
## print the settings
cat("\t------------- Inputs -------------\n")
cat(paste0("\tTest Market: ", test_market, "\n"))
for (i in 1:length(control_market)){
cat(paste0("\tControl Market ", i, ": ", control_market[i], "\n"))
}
cat(paste0("\tMarket ID: ", matched_markets$MarketID, "\n"))
cat(paste0("\tDate Variable: ", matched_markets$DateVariable, "\n"))
cat(paste0("\tMatching (pre) Period Start Date: ", MatchingStartDate, "\n"))
cat(paste0("\tMatching (pre) Period End Date: ", MatchingEndDate, "\n"))
cat(paste0("\tPost Period Start Date: ", post_period_start_date, "\n"))
cat(paste0("\tPost Period End Date: ", post_period_end_date, "\n"))
cat(paste0("\tMatching Metric: ", matched_markets$MatchingMetric, "\n"))
cat(paste0("\tLocal Level Prior SD: ", prior_level_sd, "\n"))
cat(paste0("\tPosterior Intervals Tail Area: ", 100*(1-alpha), "%\n"))
cat("\n")
cat("\n")
## run the inference
pre.period <- c(as.Date(MatchingStartDate), as.Date(MatchingEndDate))
post.period <- c(as.Date(post_period_start_date), as.Date(post_period_end_date))
set.seed(2015)
impact <- CausalImpact(ts, pre.period, post.period, alpha=alpha, model.args=list(prior.level.sd=prior_level_sd, nseasons=nseasons))
## estimate betas for different values of prior sd
betas <- data.frame(matrix(nrow=11, ncol=4))
names(betas) <- c("SD", "SumBeta", "DW", "MAPE")
for (i in 0:20){
step <- (max(0.1, prior_level_sd) - min(0.001, prior_level_sd))/20
sd <- min(0.001, prior_level_sd) + step*i
m <- CausalImpact(ts, pre.period, post.period, alpha=alpha, model.args=list(prior.level.sd=sd))
burn <- SuggestBurn(0.1, m$model$bsts.model)
b <- sum(apply(m$model$bsts.model$coefficients[-(1:burn),], 2, CMean))
betas[i+1, "SD"] <- sd
betas[i+1, "SumBeta"] <- b
preperiod <- subset(m$series, cum.effect == 0)
betas[i+1, "DW"] <- dw(preperiod$response, preperiod$point.pred)
betas[i+1, "MAPE"] <- mape_no_zeros(preperiod$response, preperiod$point.pred)
}
## create statistics
results <- list()
results[[1]] <- impact$summary$AbsEffect[2]
results[[2]] <- impact$summary$AbsEffect.lower[2]
results[[3]] <- impact$summary$AbsEffect.upper[2]
results[[4]] <- impact$summary$RelEffect[2]
results[[5]] <- impact$summary$RelEffect.lower[2]
results[[6]] <- impact$summary$RelEffect.upper[2]
results[[7]] <- impact$summary$p[2]
## compute mape
preperiod <- subset(impact$series, cum.effect == 0)
preperiod$res <- preperiod$response - preperiod$point.pred
results[[8]] <- mape_no_zeros(preperiod$response, preperiod$point.pred)
results[[9]] <- dw(preperiod$response, preperiod$point.pred)
cat("\t------------- Model Stats -------------\n")
cat(paste0("\tMatching (pre) Period MAPE: ", round(100*results[[8]], 2) , "%\n"))
avg_coeffs <- data.frame(nrow=dim(impact$model$bsts.model$coefficients)[2]-1, ncol=2)
names(avg_coeffs) <- c("Market", "AverageBeta")
for (i in 2:dim(impact$model$bsts.model$coefficients)[2]){
avg_coeffs[i-1, "Market"] <- control_market[i-1]
avg_coeffs[i-1, "AverageBeta"] <- apply(impact$model$bsts.model$coefficients[-(1:burn),], 2, CMean)[i]
cat(paste0("\tBeta ", i-1, " [", control_market[i-1], "]: ", round(avg_coeffs[i-1, "AverageBeta"], 4) , "\n"))
}
cat(paste0("\tDW: ", round(results[[9]], 2) , "\n"))
cat("\n")
cat("\n")
ymin <- min(min(impact$series$response), min(impact$series$point.pred.lower), min(ref), min(y))
ymax <- max(max(impact$series$response), max(impact$series$point.pred.upper), max(ref), max(y))
## create actual versus predicted plots
avp <- cbind.data.frame(date, data.frame(impact$series)[,c("response", "point.pred", "point.pred.lower", "point.pred.upper")])
names(avp) <- c("Date", "Response", "Predicted", "lower_bound", "upper_bound")
avp$test_market <- test_market
results[[10]] <- ggplot(data=avp, aes(x=Date)) +
geom_line(aes(y=Response, colour = "Observed"), size=1.2) +
geom_ribbon(aes(ymin=lower_bound, ymax=upper_bound), fill="grey", alpha=0.3) +
geom_line(aes(y=Predicted, colour = "Expected"), size=1.2) +
theme_bw() + theme(legend.title = element_blank()) + ylab("") + xlab("") +
geom_vline(xintercept=as.numeric(MatchingEndDate), linetype=2) +
scale_y_continuous(labels = scales::comma, limits=c(ymin, ymax)) +
ggtitle(paste0("Test Market: ",test_market))
avp$test_market <- NULL
## create cumulative lift plots
plotdf <- cbind.data.frame(as.Date(row.names(data.frame(impact$series))), data.frame(impact$series)[,c("cum.effect", "cum.effect.lower", "cum.effect.upper")])
names(plotdf) <- c("Date", "Cumulative", "lower_bound", "upper_bound")
results[[11]] <- ggplot(data=plotdf, aes(x=Date, y=Cumulative)) + geom_line(size=1.2) + theme_bw() +
scale_y_continuous(labels = scales::comma) + ylab("Cumulative Effect") + xlab("") +
geom_vline(xintercept=as.numeric(MatchingEndDate), linetype=2) +
geom_ribbon(aes(ymin=lower_bound, ymax=upper_bound), fill="grey", alpha=0.3)
## create plots of the actual data
plotdf <- data[data$id_var %in% c(test_market, control_market),]
results[[12]] <- ggplot(data=plotdf, aes(x=date_var, y=match_var, colour=id_var)) +
geom_line() +
theme_bw() + theme(legend.title = element_blank(), axis.title.x = element_blank()) + ylab("") + xlab("Date") +
geom_vline(xintercept=as.numeric(MatchingEndDate), linetype=2) +
scale_y_continuous(labels = scales::comma, limits=c(ymin, ymax))
## plot betas at various local level SDs
results[[13]] <- ggplot(data=betas, aes(x=SD, y=Beta)) +
geom_line() +
theme_bw() + theme(legend.title = element_blank()) +
geom_vline(xintercept=as.numeric(prior_level_sd), linetype=2) + xlab("Local Level Prior SD")
## plot DWs and MAPEs at different SDs
plotdf <- melt(data=betas, id="SD")
results[[14]] <- ggplot(data=plotdf, aes(x=SD, y=value, colour=variable)) + geom_line() +
theme_bw() + theme(legend.title = element_blank()) +
geom_vline(xintercept=as.numeric(prior_level_sd), linetype=2) + xlab("Local Level Prior SD") +
facet_grid(variable ~ ., scales="free") + ylab("") + guides(colour=FALSE)
burn <- SuggestBurn(0.1, impact$model$bsts.model)
plotdf <- cbind.data.frame(date, colMeans(impact$model$bsts.model$state.contributions[-(1:burn), "trend", ])) %>% filter(date<=as.Date(MatchingEndDate))
names(plotdf) <- c("Date", "LocalLevel")
results[[15]] <- ggplot(data=plotdf, aes(x=Date, y=LocalLevel)) +
geom_line() +
theme_bw() + theme(legend.title = element_blank()) +
ylab("Local Level") + xlab("")
plotdf <- cbind.data.frame(date, data.frame(impact$series)[,c("response", "point.pred")]) %>% dplyr::filter(date<=as.Date(MatchingEndDate))
names(plotdf) <- c("Date", "y", "yhat")
plotdf$Residuals <- plotdf$y - plotdf$yhat
results[[16]] <- ggplot(data=plotdf, aes(x=Date, y=Residuals)) +
geom_line() +
theme_bw() + theme(legend.title = element_blank()) +
xlab("")
## create cumulative lift plots
plotdf <- cbind.data.frame(as.Date(row.names(data.frame(impact$series))), data.frame(impact$series)[,c("point.effect", "point.effect.lower", "point.effect.upper")])
names(plotdf) <- c("Date", "Pointwise", "lower_bound", "upper_bound")
results[[17]] <- ggplot(data=plotdf, aes(x=Date, y=Pointwise)) + geom_line(size=1.2) + theme_bw() +
scale_y_continuous(labels = scales::comma) + ylab("Point Effect") + xlab("") +
geom_vline(xintercept=as.numeric(MatchingEndDate), linetype=2) +
geom_ribbon(aes(ymin=lower_bound, ymax=upper_bound), fill="grey", alpha=0.3)
### print results
cat("\t------------- Effect Analysis -------------\n")
cat(paste0("\tAbsolute Effect: ", round(results[[1]],2), " [", round(results[[2]],2), ", ", round(results[[3]],2), "]\n"))
cat(paste0("\tRelative Effect: ", paste0(round(100*results[[4]],2), "%"), " [", paste0(round(100*results[[5]],2), "%"), ", ", paste0(round(100*results[[6]],2), "%"), "]\n"))
cat(paste0("\tProbability of a causal impact: ", paste0(round(100*(1-results[[7]]),4), "%\n")))
### return the results
object <- list(AbsoluteEffect=results[[1]], AbsoluteEffectLower=results[[2]], AbsoluteEffectUpper=results[[3]],
RelativeEffect=results[[4]], RelativeEffectLower=results[[5]], RelativeEffectUpper=results[[6]],
TailProb=results[[7]], PrePeriodMAPE=results[[8]], DW=results[[9]],
PlotActualVersusExpected=results[[10]], PlotCumulativeEffect=results[[11]], PlotPointEffect=results[[17]],
PlotActuals=results[[12]], PlotPriorLevelSdAnalysis=results[[14]],
PlotLocalLevel=results[[15]], TestData=y, ControlData=ref, PlotResiduals=results[[16]],
TestName=test_market, ControlName=control_market, ZooData=ts, Predictions=avp,
CausalImpactObject=impact, Coefficients=avg_coeffs)
class(object) <- "matched_market_inference"
return (object)
}
|
#' SEC Filing Funds
#'
#' @param x URL to a SEC filing index page
#'
#' @return A dataframe with all the funds associated with a given filing
#'
#' @examples
#' \donttest{
#' # Typically you'd get the URL from one of the search functions
#' x <- paste0("https://www.sec.gov/Archives/edgar/data/",
#' "933691/000119312517247698/0001193125-17-247698-index.htm")
#' filing_funds(x)
#' }
#' @export
filing_funds <- function(x) {
UseMethod("filing_funds")
}
#' @rdname filing_funds
#' @export
filing_funds.character <- function(x) {
filing_funds(charToDoc(x))
}
#' @rdname filing_funds
#' @export
filing_funds.xml_node <- function(x) {
entries_xpath <- "//td[@class='classContract']"
info_pieces <- list(
"cik" = "preceding::td[@class='CIKname']/a",
"cik_href" = "preceding::td[@class='CIKname']/a/@href",
"series" = "preceding::td[@class='seriesName'][1]/a",
"series_href" = "preceding::td[@class='seriesName'][1]/a/@href",
"series_name" = "preceding::td[@class='seriesName'][1]/following-sibling::td[2]/text()",
"contract" = "a/text()",
"contract_href" = "a/@href",
"contract_name" = "following-sibling::td[2]/text()",
"ticker" = "following-sibling::td[3]/text()"
)
res <- map_xml(x, entries_xpath, info_pieces)
return(res)
}
| /R/filing_funds.R | permissive | braman09/edgarWebR | R | false | false | 1,292 | r | #' SEC Filing Funds
#'
#' @param x URL to a SEC filing index page
#'
#' @return A dataframe with all the funds associated with a given filing
#'
#' @examples
#' \donttest{
#' # Typically you'd get the URL from one of the search functions
#' x <- paste0("https://www.sec.gov/Archives/edgar/data/",
#' "933691/000119312517247698/0001193125-17-247698-index.htm")
#' filing_funds(x)
#' }
#' @export
filing_funds <- function(x) {
UseMethod("filing_funds")
}
#' @rdname filing_funds
#' @export
filing_funds.character <- function(x) {
filing_funds(charToDoc(x))
}
#' @rdname filing_funds
#' @export
filing_funds.xml_node <- function(x) {
entries_xpath <- "//td[@class='classContract']"
info_pieces <- list(
"cik" = "preceding::td[@class='CIKname']/a",
"cik_href" = "preceding::td[@class='CIKname']/a/@href",
"series" = "preceding::td[@class='seriesName'][1]/a",
"series_href" = "preceding::td[@class='seriesName'][1]/a/@href",
"series_name" = "preceding::td[@class='seriesName'][1]/following-sibling::td[2]/text()",
"contract" = "a/text()",
"contract_href" = "a/@href",
"contract_name" = "following-sibling::td[2]/text()",
"ticker" = "following-sibling::td[3]/text()"
)
res <- map_xml(x, entries_xpath, info_pieces)
return(res)
}
|
\name{nCycles}
\alias{nCycles}
\alias{nTicks}
\alias{nVariables}
\alias{nSeasons}
\title{
Basic information about periodic ts objects
}
\description{
Basic information about periodic periodic time series objects.
}
\usage{
nCycles(x, \dots)
nTicks(x)
nVariables(x, \dots)
nSeasons(object)
}
\arguments{
\item{x,object}{an object from a periodic time series class.}
\item{\dots}{further arguments for methods.}
}
\details{
% These are generic functions. The default methods will work for any
% objects for which \code{NROW} and \code{NCOL} are defined and have the
% conventional case by variables interpretation.
\code{nTicks} gives the number of time points, i.e. number of rows in
the matrix representation.
\code{nVariables} gives the number of variables in the time series.
\code{nSeasons} gives the number of seasons of time series and other
periodic objects.
\code{nCycles} gives the number of cycles available in the data,
e.g. number of years for monthly data. It always gives an integer
number. Currently, if the result is not an integer an error is
raised. \strong{TODO:} There is a case to round up or give the number of full
cycles available but this seems somewhat dangerous if done quietly. A
good alternative is to provide argument for control of this.
There are further functions to get or set the names of the units of
season and the seasons, see \code{\link{allSeasons}}.
}
\value{
an integer number
}
\author{Georgi N. Boshnakov}
%\note{
%%% ~~further notes~~
%}
%
%%% ~Make other sections like Warning with \section{Warning }{....} ~
%
\seealso{
\code{\link{allSeasons}}, \code{"\link{nSeasons-methods}"}
}
\examples{
ap <- pcts(AirPassengers)
nVariables(ap)
nTicks(ap)
nCycles(ap)
nSeasons(ap)
monthplot(ap)
boxplot(ap)
}
\keyword{pcts}
| /man/nCycles.Rd | no_license | GeoBosh/pcts | R | false | false | 1,817 | rd | \name{nCycles}
\alias{nCycles}
\alias{nTicks}
\alias{nVariables}
\alias{nSeasons}
\title{
Basic information about periodic ts objects
}
\description{
Basic information about periodic periodic time series objects.
}
\usage{
nCycles(x, \dots)
nTicks(x)
nVariables(x, \dots)
nSeasons(object)
}
\arguments{
\item{x,object}{an object from a periodic time series class.}
\item{\dots}{further arguments for methods.}
}
\details{
% These are generic functions. The default methods will work for any
% objects for which \code{NROW} and \code{NCOL} are defined and have the
% conventional case by variables interpretation.
\code{nTicks} gives the number of time points, i.e. number of rows in
the matrix representation.
\code{nVariables} gives the number of variables in the time series.
\code{nSeasons} gives the number of seasons of time series and other
periodic objects.
\code{nCycles} gives the number of cycles available in the data,
e.g. number of years for monthly data. It always gives an integer
number. Currently, if the result is not an integer an error is
raised. \strong{TODO:} There is a case to round up or give the number of full
cycles available but this seems somewhat dangerous if done quietly. A
good alternative is to provide argument for control of this.
There are further functions to get or set the names of the units of
season and the seasons, see \code{\link{allSeasons}}.
}
\value{
an integer number
}
\author{Georgi N. Boshnakov}
%\note{
%%% ~~further notes~~
%}
%
%%% ~Make other sections like Warning with \section{Warning }{....} ~
%
\seealso{
\code{\link{allSeasons}}, \code{"\link{nSeasons-methods}"}
}
\examples{
ap <- pcts(AirPassengers)
nVariables(ap)
nTicks(ap)
nCycles(ap)
nSeasons(ap)
monthplot(ap)
boxplot(ap)
}
\keyword{pcts}
|
#loading data
data = read.csv("DHS_Daily_Report.csv")
#Tranforming Date Variable
data$Date = strptime(data$Date, "%m/%d/%Y")
data$Date = format(data$Date, "%Y-%m-%d")
data$Date = as.Date(data$Date)
#selecting variables
library(dplyr)
data = data %>% select(Date,
Total.Individuals.in.Shelter,
Easter,
Thanksgiving,
Christmas)
#transforming Y variable
colnames(data)[2] = "y"
#creating dataframes
future <- subset(data, data$Date > '2020-11-11')
dataset <- subset(data, data$Date <= '2020-11-11')
#tranforming the Y variables into Timeseries
library(lubridate)
dataset$y <- ts(dataset$y,
frequency = 365,
start =c(2013, yday(head(dataset$Date, 1))))
#tranforming the Y variables into Timeseries
future$y <- ts(future$y,
frequency = 365,
start = c(2020, yday(head(future$Date, 1))))
#visualization
plot.ts(dataset$y,
ylab = "Demand")
##################################################################
#decomposition
decomposition = decompose(dataset$y, type = "additive")
plot(decomposition)
#other seasonality plot
library(ggplot2)
ggseasonplot(dataset$y)
| /2. Seasonal Decomposition/Seasonal Decomposition.R | no_license | chakrabortysubhadip/Time_Series | R | false | false | 1,274 | r | #loading data
data = read.csv("DHS_Daily_Report.csv")
#Tranforming Date Variable
data$Date = strptime(data$Date, "%m/%d/%Y")
data$Date = format(data$Date, "%Y-%m-%d")
data$Date = as.Date(data$Date)
#selecting variables
library(dplyr)
data = data %>% select(Date,
Total.Individuals.in.Shelter,
Easter,
Thanksgiving,
Christmas)
#transforming Y variable
colnames(data)[2] = "y"
#creating dataframes
future <- subset(data, data$Date > '2020-11-11')
dataset <- subset(data, data$Date <= '2020-11-11')
#tranforming the Y variables into Timeseries
library(lubridate)
dataset$y <- ts(dataset$y,
frequency = 365,
start =c(2013, yday(head(dataset$Date, 1))))
#tranforming the Y variables into Timeseries
future$y <- ts(future$y,
frequency = 365,
start = c(2020, yday(head(future$Date, 1))))
#visualization
plot.ts(dataset$y,
ylab = "Demand")
##################################################################
#decomposition
decomposition = decompose(dataset$y, type = "additive")
plot(decomposition)
#other seasonality plot
library(ggplot2)
ggseasonplot(dataset$y)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/oneBkp.R
\name{oneBkp}
\alias{oneBkp}
\title{Get best candidate change point}
\usage{
oneBkp(Y, weights = NULL, verbose = FALSE)
}
\arguments{
\item{Y}{A \code{n*p} matrix, \code{p} signals of length \code{n} to be
segmented (centered by column)}
\item{weights}{a \code{(n-1)*1} vector of weights for the candidate change
point positions. Default weights yield the likelihood ratio test (LRT)
statistic for the identification of a single change point.}
\item{verbose}{A \code{logical} value: should extra information be output ?
Defaults to \code{FALSE}.}
}
\description{
Get best candidate change point according to binary segmentation
}
\examples{
p <- 2
sim <- randomProfile(1e4, 1, 1, p)
Y <- sim$profile
bkp <- jointseg:::oneBkp(Y)
par(mfrow=c(p,1))
for (ii in 1:p) {
plot(Y[, ii], pch=19, cex=0.2)
abline(v=bkp, col=3)
abline(v=sim$bkp, col=8, lty=2)
}
}
\author{
Morgane Pierre-Jean and Pierre Neuvial
}
\keyword{internal}
| /man/oneBkp.Rd | no_license | cran/jointseg | R | false | true | 1,024 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/oneBkp.R
\name{oneBkp}
\alias{oneBkp}
\title{Get best candidate change point}
\usage{
oneBkp(Y, weights = NULL, verbose = FALSE)
}
\arguments{
\item{Y}{A \code{n*p} matrix, \code{p} signals of length \code{n} to be
segmented (centered by column)}
\item{weights}{a \code{(n-1)*1} vector of weights for the candidate change
point positions. Default weights yield the likelihood ratio test (LRT)
statistic for the identification of a single change point.}
\item{verbose}{A \code{logical} value: should extra information be output ?
Defaults to \code{FALSE}.}
}
\description{
Get best candidate change point according to binary segmentation
}
\examples{
p <- 2
sim <- randomProfile(1e4, 1, 1, p)
Y <- sim$profile
bkp <- jointseg:::oneBkp(Y)
par(mfrow=c(p,1))
for (ii in 1:p) {
plot(Y[, ii], pch=19, cex=0.2)
abline(v=bkp, col=3)
abline(v=sim$bkp, col=8, lty=2)
}
}
\author{
Morgane Pierre-Jean and Pierre Neuvial
}
\keyword{internal}
|
run_analysis <- function()
{
library(plyr)
library(dplyr)
#---------------------------------------------------------------------------------------------------
#During this section, I read in the Subject identifer labels table for the trained data and changed the column name to SUbject ID
subjecttrainedlabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//train//subject_train.txt")
subjecttrainedlabels <- rename(subjecttrainedlabels, SubjectID = V1)
# During this section, I read in the train set labels and changed the first columan name to activitys. I also set
# the column to a factor and maped the training labels name table to the values in the activity table first column
subjecttraineddatalabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//train//y_train.txt")
subjecttraineddatalabels <- rename(subjecttraineddatalabels, Activitys = V1)
subjecttraineddatalabels <- as.factor(subjecttraineddatalabels$Activitys)
subjecttraineddatalabels <- mapvalues(subjecttraineddatalabels, from = c("1","2","3","4","5","6"), to = c("WALKING","WALKING_UPSTAIRS","WALKING_DONSTAIRS","SITTING","STANDING","LAYING"))
# During this section, I read in the data for the training sets and the training sets columns label table. Afterwareds,
# I set the names of the features to the respective column in the training set tables
subjecttraineddata <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//train//X_train.txt")
featuredatalabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//features.txt")
names(subjecttraineddata) = featuredatalabels$V2
#Lastly, I combined subject table, label table, and data set table into one table
#and changed the second column name back to a activity
trainingdata <- cbind(subjecttrainedlabels,subjecttraineddatalabels,subjecttraineddata)
names(trainingdata)[2] = "Activity"
#--------------------------------------------------------------------------------------------------
#The steps to this section code is identical to the steps above. The only difference is that this is test data
# instead of training data. Refer to the above text for explaination.
subjecttestlabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//test//subject_test.txt")
subjecttestlabels <- rename(subjecttestlabels, SubjectID = V1)
subjecttestdatalabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//test//y_test.txt")
subjecttestdatalabels <- rename(subjecttestdatalabels, Activitys = V1)
subjecttestdatalabels <- as.factor(subjecttestdatalabels$Activitys)
subjecttestdatalabels <- mapvalues(subjecttestdatalabels, from = c("1","2","3","4","5","6"), to = c("WALKING","WALKING_UPSTAIRS","WALKING_DONSTAIRS","SITTING","STANDING","LAYING"))
subjecttestdata <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//test//X_test.txt")
names(subjecttestdata) = featuredatalabels$V2
testingdata <- cbind(subjecttestlabels,subjecttestdatalabels,subjecttestdata)
names(testingdata)[2] = "Activity"
#------------------------------------------------------------------------------------------------------
# This code combined the training and test data into one dataset
combineddataset <- rbind(trainingdata,testingdata)
#This code subsetted the data only keeping the columns that represent the mean and stds of each signal
reduced_dataset <- combineddataset[c(1:2,3:8,43:48,83:88,123:128,163:168,203:204,216:217,229:230,242:243,255:256,268:273,347:352,426:431,505:506,518:519,531:532,544:545)]
#-----------------This code is how I renamed the columns to useful names---------------------------
names(reduced_dataset)[3] = "tBodyAccMeanX"
names(reduced_dataset)[4] = "tBodyAccMeanY"
names(reduced_dataset)[5] = "tBodyAccMeanZ"
names(reduced_dataset)[6] = "tBodyAccStdX"
names(reduced_dataset)[7] = "tBodyAccStdY"
names(reduced_dataset)[8] = "tBodyAccStdZ"
names(reduced_dataset)[9] = "tGravityAccMeanX"
names(reduced_dataset)[10] = "tGravityAccMeanY"
names(reduced_dataset)[11] = "tGravityAccMeanZ"
names(reduced_dataset)[12] = "tGravityAccStdX"
names(reduced_dataset)[13] = "tGravityAccStdY"
names(reduced_dataset)[14] = "tGravityAccStdZ"
names(reduced_dataset)[15] = "tBodyAccJerkMeanX"
names(reduced_dataset)[16] = "tBodyAccJerkMeanY"
names(reduced_dataset)[17] = "tBodyAccJerkMeanZ"
names(reduced_dataset)[18] = "tBodyAccJerkStdX"
names(reduced_dataset)[19] = "tBodyAccJerkStdY"
names(reduced_dataset)[20] = "tBodyAccJerkStdZ"
names(reduced_dataset)[21] = "tBodyGyroMeanX"
names(reduced_dataset)[22] = "tBodyGyroMeanY"
names(reduced_dataset)[23] = "tBodyGyroMeanZ"
names(reduced_dataset)[24] = "tBodyGyroStdX"
names(reduced_dataset)[25] = "tBodyGyroStdY"
names(reduced_dataset)[26] = "tBodyGyroStdZ"
names(reduced_dataset)[27] = "tBodyGyroJerkMeanX"
names(reduced_dataset)[28] = "tBodyGyroJerkMeanY"
names(reduced_dataset)[29] = "tBodyGyroJerkMeanZ"
names(reduced_dataset)[30] = "tBodyGyroJerkStdX"
names(reduced_dataset)[31] = "tBodyGyroJerkStdY"
names(reduced_dataset)[32] = "tBodyGyroJerkStdZ"
names(reduced_dataset)[33] = "tBodyAccMagMean"
names(reduced_dataset)[34] = "tBodyAccMagStd"
names(reduced_dataset)[35] = "tGravityAccMagMean"
names(reduced_dataset)[36] = "tGravityAccMagStd"
names(reduced_dataset)[37] = "tBodyAccJerkMagMean"
names(reduced_dataset)[38] = "tBodyAccJerkMagStd"
names(reduced_dataset)[39] = "tBodyGyroMagMean"
names(reduced_dataset)[40] = "tBodyGyroMagStd"
names(reduced_dataset)[41] = "tBodyGyroJerkMagMean"
names(reduced_dataset)[42] = "tBodyGyroJerkMagStd"
names(reduced_dataset)[43] = "fBodyAccMeanX"
names(reduced_dataset)[44] = "fBodyAccMeanY"
names(reduced_dataset)[45] = "fBodyAccMeanZ"
names(reduced_dataset)[46] = "fBodyAccStdX"
names(reduced_dataset)[47] = "fBodyAccStdY"
names(reduced_dataset)[48] = "fBodyAccStdZ"
names(reduced_dataset)[49] = "fBodyAccJerkMeanX"
names(reduced_dataset)[50] = "fBodyAccJerkMeanY"
names(reduced_dataset)[51] = "fBodyAccJerkMeanZ"
names(reduced_dataset)[52] = "fBodyAccJerkStdX"
names(reduced_dataset)[53] = "fBodyAccJerkStdY"
names(reduced_dataset)[54] = "fBodyAccJerkStdZ"
names(reduced_dataset)[55] = "fBodyGyroMeanX"
names(reduced_dataset)[56] = "fBodyGyroMeanY"
names(reduced_dataset)[57] = "fBodyGyroMeanZ"
names(reduced_dataset)[58] = "fBodyGyroStdX"
names(reduced_dataset)[59] = "fBodyGyroStdY"
names(reduced_dataset)[60] = "fBodyGyroStdZ"
names(reduced_dataset)[61] = "fBodyAccMagMean"
names(reduced_dataset)[62] = "fBodyAccMagStd"
names(reduced_dataset)[63] = "fBodyAccJerkMagMean"
names(reduced_dataset)[64] = "fBodyAccJerkMagStd"
names(reduced_dataset)[65] = "fBodyGyroMagMean"
names(reduced_dataset)[66] = "fBodyGyroMagStd"
names(reduced_dataset)[67] = "fBodyGyroJerkMagMean"
names(reduced_dataset)[68] = "fBodyGyroJerkMagStd"
names(reduced_dataset)[2] = "Activity"
#----------------------------------------------------------------------------------------
#This code group the data by subject ID and Activity
subjectdatabygroup <- group_by(reduced_dataset,SubjectID,Activity)
#This code is used to get the avg and std for each subject by activity
subjectactivityavgtable <- summarize(subjectdatabygroup,
tBodyAccMeanX = mean(tBodyAccMeanX, na.rm = TRUE),
tBodyAccMeanY = mean(tBodyAccMeanY, na.rm = TRUE),
tBodyAccMeanZ = mean(tBodyAccMeanZ, na.rm = TRUE),
tBodyAccStdX = mean(tBodyAccStdX, na.rm = TRUE),
tBodyAccStdY = mean(tBodyAccStdY, na.rm = TRUE),
tBodyAccStdZ = mean(tBodyAccStdZ, na.rm = TRUE),
tGravityAccMeanX = mean(tGravityAccMeanX, na.rm = TRUE),
tGravityAccMeanY = mean(tGravityAccMeanY, na.rm = TRUE),
tGravityAccMeanZ = mean(tGravityAccMeanZ, na.rm = TRUE),
tGravityAccStdX = mean(tGravityAccStdX, na.rm = TRUE),
tGravityAccStdY = mean(tGravityAccStdY, na.rm = TRUE),
tGravityAccStdZ = mean(tGravityAccStdZ, na.rm = TRUE),
tBodyAccJerkMeanX = mean(tBodyAccJerkMeanX, na.rm = TRUE),
tBodyAccJerkMeanY = mean(tBodyAccJerkMeanY, na.rm = TRUE),
tBodyAccJerkMeanZ = mean(tBodyAccJerkMeanZ, na.rm = TRUE),
tBodyAccJerkStdX = mean(tBodyAccJerkStdX, na.rm = TRUE),
tBodyAccJerkStdY = mean(tBodyAccJerkStdY, na.rm = TRUE),
tBodyAccJerkStdZ = mean(tBodyAccJerkStdZ, na.rm = TRUE),
tBodyGyroMeanX = mean(tBodyGyroMeanX, na.rm = TRUE),
tBodyGyroMeanY = mean(tBodyGyroMeanY, na.rm = TRUE),
tBodyGyroMeanZ = mean(tBodyGyroMeanZ, na.rm = TRUE),
tBodyGyroStdX = mean(tBodyGyroStdX, na.rm = TRUE),
tBodyGyroStdY = mean(tBodyGyroStdY, na.rm = TRUE),
tBodyGyroStdZ = mean(tBodyGyroStdZ, na.rm = TRUE),
tBodyGyroJerkMeanX = mean(tBodyGyroJerkMeanX, na.rm = TRUE),
tBodyGyroJerkMeanY = mean(tBodyGyroJerkMeanY, na.rm = TRUE),
tBodyGyroJerkMeanZ = mean(tBodyGyroJerkMeanZ, na.rm = TRUE),
tBodyGyroJerkStdX = mean(tBodyGyroJerkStdX, na.rm = TRUE),
tBodyGyroJerkStdY = mean(tBodyGyroJerkStdY, na.rm = TRUE),
tBodyGyroJerkStdZ = mean(tBodyGyroJerkStdZ, na.rm = TRUE),
tBodyAccMagMean = mean(tBodyAccMagMean, na.rm = TRUE),
tBodyAccMagStd = mean(tBodyAccMagStd, na.rm = TRUE),
tGravityAccMagMean = mean(tGravityAccMagMean, na.rm = TRUE),
tGravityAccMagStd = mean(tGravityAccMagStd, na.rm = TRUE),
tBodyAccJerkMagMean = mean(tBodyAccJerkMagMean, na.rm = TRUE),
tBodyAccJerkMagStd = mean(tBodyAccJerkMagStd, na.rm = TRUE),
tBodyGyroMagMean = mean(tBodyGyroMagMean, na.rm = TRUE),
tBodyGyroMagStd = mean(tBodyGyroMagStd, na.rm = TRUE),
tBodyGyroJerkMagMean = mean(tBodyGyroJerkMagMean, na.rm = TRUE),
tBodyGyroJerkMagStd = mean(tBodyGyroJerkMagStd, na.rm = TRUE),
fBodyAccMeanX = mean(fBodyAccMeanX, na.rm = TRUE),
fBodyAccMeanY = mean(fBodyAccMeanY, na.rm = TRUE),
fBodyAccMeanZ = mean(fBodyAccMeanZ, na.rm = TRUE),
fBodyAccStdX = mean(fBodyAccStdX, na.rm = TRUE),
fBodyAccStdY = mean(fBodyAccStdY, na.rm = TRUE),
fBodyAccStdZ = mean(fBodyAccStdZ, na.rm = TRUE),
fBodyAccJerkMeanX = mean(fBodyAccJerkMeanX, na.rm = TRUE),
fBodyAccJerkMeanY = mean(fBodyAccJerkMeanY, na.rm = TRUE),
fBodyAccJerkMeanZ = mean(fBodyAccJerkMeanZ, na.rm = TRUE),
fBodyAccJerkStdX = mean(fBodyAccJerkStdX, na.rm = TRUE),
fBodyAccJerkStdY = mean(fBodyAccJerkStdY, na.rm = TRUE),
fBodyAccJerkStdZ = mean(fBodyAccJerkStdZ, na.rm = TRUE),
fBodyGyroMeanX = mean(fBodyGyroMeanX, na.rm = TRUE),
fBodyGyroMeanY = mean(fBodyGyroMeanY, na.rm = TRUE),
fBodyGyroMeanZ = mean(fBodyGyroMeanZ, na.rm = TRUE),
fBodyGyroStdX = mean(fBodyGyroStdX, na.rm = TRUE),
fBodyGyroStdY = mean(fBodyGyroStdY, na.rm = TRUE),
fBodyGyroStdZ = mean(fBodyGyroStdZ, na.rm = TRUE),
fBodyAccMagMean = mean(fBodyAccMagMean, na.rm = TRUE),
fBodyAccMagStd = mean(fBodyAccMagStd, na.rm = TRUE),
fBodyAccJerkMagMean = mean(fBodyAccJerkMagMean, na.rm = TRUE),
fBodyAccJerkMagStd = mean(fBodyAccJerkMagStd, na.rm = TRUE),
fBodyGyroMagMean = mean(fBodyGyroMagMean, na.rm = TRUE),
fBodyGyroMagStd = mean(fBodyGyroMagStd, na.rm = TRUE),
fBodyGyroJerkMagMean = mean(fBodyGyroJerkMagMean, na.rm = TRUE),
fBodyGyroJerkMagStd = mean(fBodyGyroJerkMagStd, na.rm = TRUE),
tBodyAccMeanX = mean(tBodyAccMeanX, na.rm = TRUE),
tBodyAccMeanX = mean(tBodyAccMeanX, na.rm = TRUE))
#This represents the output table with the resultant table
subjectactivityavgtable
} | /run_analysis.R | no_license | mhami018/CleaningDataAssignment | R | false | false | 12,264 | r | run_analysis <- function()
{
library(plyr)
library(dplyr)
#---------------------------------------------------------------------------------------------------
#During this section, I read in the Subject identifer labels table for the trained data and changed the column name to SUbject ID
subjecttrainedlabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//train//subject_train.txt")
subjecttrainedlabels <- rename(subjecttrainedlabels, SubjectID = V1)
# During this section, I read in the train set labels and changed the first columan name to activitys. I also set
# the column to a factor and maped the training labels name table to the values in the activity table first column
subjecttraineddatalabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//train//y_train.txt")
subjecttraineddatalabels <- rename(subjecttraineddatalabels, Activitys = V1)
subjecttraineddatalabels <- as.factor(subjecttraineddatalabels$Activitys)
subjecttraineddatalabels <- mapvalues(subjecttraineddatalabels, from = c("1","2","3","4","5","6"), to = c("WALKING","WALKING_UPSTAIRS","WALKING_DONSTAIRS","SITTING","STANDING","LAYING"))
# During this section, I read in the data for the training sets and the training sets columns label table. Afterwareds,
# I set the names of the features to the respective column in the training set tables
subjecttraineddata <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//train//X_train.txt")
featuredatalabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//features.txt")
names(subjecttraineddata) = featuredatalabels$V2
#Lastly, I combined subject table, label table, and data set table into one table
#and changed the second column name back to a activity
trainingdata <- cbind(subjecttrainedlabels,subjecttraineddatalabels,subjecttraineddata)
names(trainingdata)[2] = "Activity"
#--------------------------------------------------------------------------------------------------
#The steps to this section code is identical to the steps above. The only difference is that this is test data
# instead of training data. Refer to the above text for explaination.
subjecttestlabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//test//subject_test.txt")
subjecttestlabels <- rename(subjecttestlabels, SubjectID = V1)
subjecttestdatalabels <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//test//y_test.txt")
subjecttestdatalabels <- rename(subjecttestdatalabels, Activitys = V1)
subjecttestdatalabels <- as.factor(subjecttestdatalabels$Activitys)
subjecttestdatalabels <- mapvalues(subjecttestdatalabels, from = c("1","2","3","4","5","6"), to = c("WALKING","WALKING_UPSTAIRS","WALKING_DONSTAIRS","SITTING","STANDING","LAYING"))
subjecttestdata <- read.table("C://Users//DarkHorse//Desktop//CleanData//UCI HAR Dataset//test//X_test.txt")
names(subjecttestdata) = featuredatalabels$V2
testingdata <- cbind(subjecttestlabels,subjecttestdatalabels,subjecttestdata)
names(testingdata)[2] = "Activity"
#------------------------------------------------------------------------------------------------------
# This code combined the training and test data into one dataset
combineddataset <- rbind(trainingdata,testingdata)
#This code subsetted the data only keeping the columns that represent the mean and stds of each signal
reduced_dataset <- combineddataset[c(1:2,3:8,43:48,83:88,123:128,163:168,203:204,216:217,229:230,242:243,255:256,268:273,347:352,426:431,505:506,518:519,531:532,544:545)]
#-----------------This code is how I renamed the columns to useful names---------------------------
names(reduced_dataset)[3] = "tBodyAccMeanX"
names(reduced_dataset)[4] = "tBodyAccMeanY"
names(reduced_dataset)[5] = "tBodyAccMeanZ"
names(reduced_dataset)[6] = "tBodyAccStdX"
names(reduced_dataset)[7] = "tBodyAccStdY"
names(reduced_dataset)[8] = "tBodyAccStdZ"
names(reduced_dataset)[9] = "tGravityAccMeanX"
names(reduced_dataset)[10] = "tGravityAccMeanY"
names(reduced_dataset)[11] = "tGravityAccMeanZ"
names(reduced_dataset)[12] = "tGravityAccStdX"
names(reduced_dataset)[13] = "tGravityAccStdY"
names(reduced_dataset)[14] = "tGravityAccStdZ"
names(reduced_dataset)[15] = "tBodyAccJerkMeanX"
names(reduced_dataset)[16] = "tBodyAccJerkMeanY"
names(reduced_dataset)[17] = "tBodyAccJerkMeanZ"
names(reduced_dataset)[18] = "tBodyAccJerkStdX"
names(reduced_dataset)[19] = "tBodyAccJerkStdY"
names(reduced_dataset)[20] = "tBodyAccJerkStdZ"
names(reduced_dataset)[21] = "tBodyGyroMeanX"
names(reduced_dataset)[22] = "tBodyGyroMeanY"
names(reduced_dataset)[23] = "tBodyGyroMeanZ"
names(reduced_dataset)[24] = "tBodyGyroStdX"
names(reduced_dataset)[25] = "tBodyGyroStdY"
names(reduced_dataset)[26] = "tBodyGyroStdZ"
names(reduced_dataset)[27] = "tBodyGyroJerkMeanX"
names(reduced_dataset)[28] = "tBodyGyroJerkMeanY"
names(reduced_dataset)[29] = "tBodyGyroJerkMeanZ"
names(reduced_dataset)[30] = "tBodyGyroJerkStdX"
names(reduced_dataset)[31] = "tBodyGyroJerkStdY"
names(reduced_dataset)[32] = "tBodyGyroJerkStdZ"
names(reduced_dataset)[33] = "tBodyAccMagMean"
names(reduced_dataset)[34] = "tBodyAccMagStd"
names(reduced_dataset)[35] = "tGravityAccMagMean"
names(reduced_dataset)[36] = "tGravityAccMagStd"
names(reduced_dataset)[37] = "tBodyAccJerkMagMean"
names(reduced_dataset)[38] = "tBodyAccJerkMagStd"
names(reduced_dataset)[39] = "tBodyGyroMagMean"
names(reduced_dataset)[40] = "tBodyGyroMagStd"
names(reduced_dataset)[41] = "tBodyGyroJerkMagMean"
names(reduced_dataset)[42] = "tBodyGyroJerkMagStd"
names(reduced_dataset)[43] = "fBodyAccMeanX"
names(reduced_dataset)[44] = "fBodyAccMeanY"
names(reduced_dataset)[45] = "fBodyAccMeanZ"
names(reduced_dataset)[46] = "fBodyAccStdX"
names(reduced_dataset)[47] = "fBodyAccStdY"
names(reduced_dataset)[48] = "fBodyAccStdZ"
names(reduced_dataset)[49] = "fBodyAccJerkMeanX"
names(reduced_dataset)[50] = "fBodyAccJerkMeanY"
names(reduced_dataset)[51] = "fBodyAccJerkMeanZ"
names(reduced_dataset)[52] = "fBodyAccJerkStdX"
names(reduced_dataset)[53] = "fBodyAccJerkStdY"
names(reduced_dataset)[54] = "fBodyAccJerkStdZ"
names(reduced_dataset)[55] = "fBodyGyroMeanX"
names(reduced_dataset)[56] = "fBodyGyroMeanY"
names(reduced_dataset)[57] = "fBodyGyroMeanZ"
names(reduced_dataset)[58] = "fBodyGyroStdX"
names(reduced_dataset)[59] = "fBodyGyroStdY"
names(reduced_dataset)[60] = "fBodyGyroStdZ"
names(reduced_dataset)[61] = "fBodyAccMagMean"
names(reduced_dataset)[62] = "fBodyAccMagStd"
names(reduced_dataset)[63] = "fBodyAccJerkMagMean"
names(reduced_dataset)[64] = "fBodyAccJerkMagStd"
names(reduced_dataset)[65] = "fBodyGyroMagMean"
names(reduced_dataset)[66] = "fBodyGyroMagStd"
names(reduced_dataset)[67] = "fBodyGyroJerkMagMean"
names(reduced_dataset)[68] = "fBodyGyroJerkMagStd"
names(reduced_dataset)[2] = "Activity"
#----------------------------------------------------------------------------------------
#This code group the data by subject ID and Activity
subjectdatabygroup <- group_by(reduced_dataset,SubjectID,Activity)
#This code is used to get the avg and std for each subject by activity
subjectactivityavgtable <- summarize(subjectdatabygroup,
tBodyAccMeanX = mean(tBodyAccMeanX, na.rm = TRUE),
tBodyAccMeanY = mean(tBodyAccMeanY, na.rm = TRUE),
tBodyAccMeanZ = mean(tBodyAccMeanZ, na.rm = TRUE),
tBodyAccStdX = mean(tBodyAccStdX, na.rm = TRUE),
tBodyAccStdY = mean(tBodyAccStdY, na.rm = TRUE),
tBodyAccStdZ = mean(tBodyAccStdZ, na.rm = TRUE),
tGravityAccMeanX = mean(tGravityAccMeanX, na.rm = TRUE),
tGravityAccMeanY = mean(tGravityAccMeanY, na.rm = TRUE),
tGravityAccMeanZ = mean(tGravityAccMeanZ, na.rm = TRUE),
tGravityAccStdX = mean(tGravityAccStdX, na.rm = TRUE),
tGravityAccStdY = mean(tGravityAccStdY, na.rm = TRUE),
tGravityAccStdZ = mean(tGravityAccStdZ, na.rm = TRUE),
tBodyAccJerkMeanX = mean(tBodyAccJerkMeanX, na.rm = TRUE),
tBodyAccJerkMeanY = mean(tBodyAccJerkMeanY, na.rm = TRUE),
tBodyAccJerkMeanZ = mean(tBodyAccJerkMeanZ, na.rm = TRUE),
tBodyAccJerkStdX = mean(tBodyAccJerkStdX, na.rm = TRUE),
tBodyAccJerkStdY = mean(tBodyAccJerkStdY, na.rm = TRUE),
tBodyAccJerkStdZ = mean(tBodyAccJerkStdZ, na.rm = TRUE),
tBodyGyroMeanX = mean(tBodyGyroMeanX, na.rm = TRUE),
tBodyGyroMeanY = mean(tBodyGyroMeanY, na.rm = TRUE),
tBodyGyroMeanZ = mean(tBodyGyroMeanZ, na.rm = TRUE),
tBodyGyroStdX = mean(tBodyGyroStdX, na.rm = TRUE),
tBodyGyroStdY = mean(tBodyGyroStdY, na.rm = TRUE),
tBodyGyroStdZ = mean(tBodyGyroStdZ, na.rm = TRUE),
tBodyGyroJerkMeanX = mean(tBodyGyroJerkMeanX, na.rm = TRUE),
tBodyGyroJerkMeanY = mean(tBodyGyroJerkMeanY, na.rm = TRUE),
tBodyGyroJerkMeanZ = mean(tBodyGyroJerkMeanZ, na.rm = TRUE),
tBodyGyroJerkStdX = mean(tBodyGyroJerkStdX, na.rm = TRUE),
tBodyGyroJerkStdY = mean(tBodyGyroJerkStdY, na.rm = TRUE),
tBodyGyroJerkStdZ = mean(tBodyGyroJerkStdZ, na.rm = TRUE),
tBodyAccMagMean = mean(tBodyAccMagMean, na.rm = TRUE),
tBodyAccMagStd = mean(tBodyAccMagStd, na.rm = TRUE),
tGravityAccMagMean = mean(tGravityAccMagMean, na.rm = TRUE),
tGravityAccMagStd = mean(tGravityAccMagStd, na.rm = TRUE),
tBodyAccJerkMagMean = mean(tBodyAccJerkMagMean, na.rm = TRUE),
tBodyAccJerkMagStd = mean(tBodyAccJerkMagStd, na.rm = TRUE),
tBodyGyroMagMean = mean(tBodyGyroMagMean, na.rm = TRUE),
tBodyGyroMagStd = mean(tBodyGyroMagStd, na.rm = TRUE),
tBodyGyroJerkMagMean = mean(tBodyGyroJerkMagMean, na.rm = TRUE),
tBodyGyroJerkMagStd = mean(tBodyGyroJerkMagStd, na.rm = TRUE),
fBodyAccMeanX = mean(fBodyAccMeanX, na.rm = TRUE),
fBodyAccMeanY = mean(fBodyAccMeanY, na.rm = TRUE),
fBodyAccMeanZ = mean(fBodyAccMeanZ, na.rm = TRUE),
fBodyAccStdX = mean(fBodyAccStdX, na.rm = TRUE),
fBodyAccStdY = mean(fBodyAccStdY, na.rm = TRUE),
fBodyAccStdZ = mean(fBodyAccStdZ, na.rm = TRUE),
fBodyAccJerkMeanX = mean(fBodyAccJerkMeanX, na.rm = TRUE),
fBodyAccJerkMeanY = mean(fBodyAccJerkMeanY, na.rm = TRUE),
fBodyAccJerkMeanZ = mean(fBodyAccJerkMeanZ, na.rm = TRUE),
fBodyAccJerkStdX = mean(fBodyAccJerkStdX, na.rm = TRUE),
fBodyAccJerkStdY = mean(fBodyAccJerkStdY, na.rm = TRUE),
fBodyAccJerkStdZ = mean(fBodyAccJerkStdZ, na.rm = TRUE),
fBodyGyroMeanX = mean(fBodyGyroMeanX, na.rm = TRUE),
fBodyGyroMeanY = mean(fBodyGyroMeanY, na.rm = TRUE),
fBodyGyroMeanZ = mean(fBodyGyroMeanZ, na.rm = TRUE),
fBodyGyroStdX = mean(fBodyGyroStdX, na.rm = TRUE),
fBodyGyroStdY = mean(fBodyGyroStdY, na.rm = TRUE),
fBodyGyroStdZ = mean(fBodyGyroStdZ, na.rm = TRUE),
fBodyAccMagMean = mean(fBodyAccMagMean, na.rm = TRUE),
fBodyAccMagStd = mean(fBodyAccMagStd, na.rm = TRUE),
fBodyAccJerkMagMean = mean(fBodyAccJerkMagMean, na.rm = TRUE),
fBodyAccJerkMagStd = mean(fBodyAccJerkMagStd, na.rm = TRUE),
fBodyGyroMagMean = mean(fBodyGyroMagMean, na.rm = TRUE),
fBodyGyroMagStd = mean(fBodyGyroMagStd, na.rm = TRUE),
fBodyGyroJerkMagMean = mean(fBodyGyroJerkMagMean, na.rm = TRUE),
fBodyGyroJerkMagStd = mean(fBodyGyroJerkMagStd, na.rm = TRUE),
tBodyAccMeanX = mean(tBodyAccMeanX, na.rm = TRUE),
tBodyAccMeanX = mean(tBodyAccMeanX, na.rm = TRUE))
#This represents the output table with the resultant table
subjectactivityavgtable
} |
---
title: "R Notebook"
output: html_notebook
---
This is an [R Markdown](http://rmarkdown.rstudio.com) Notebook. When you execute code within the notebook, the results appear beneath the code.
Try executing this chunk by clicking the *Run* button within the chunk or by placing your cursor inside it and pressing *Ctrl+Shift+Enter*.
```{r}
library(tidyverse)
library(lubridate)
library(ggplot2)
```
# The lcData6m.csv file contains data on 3 year loans issues in the first 6 months of 2015, which we will use for this analyses
```{r}
lcdf <- read.csv("C:/Users/LENOVO/Desktop/2018 vansh industrial/data mining/lcData6m.csv")
View(lcdf)
dim(lcdf)
```
#Data Exploration
```{r}
#How does loan status vary by loan grade
lcdf %>% group_by(loan_status, grade) %>% tally()
table(lcdf$loan_status, lcdf$grade)
#Filtering out the loans with 'Current' Status
lcdf <- lcdf %>% filter(loan_status !="Current")
#How does loan status vary by loan sub grade
lcdf %>% group_by(loan_status, sub_grade) %>% tally()
table(lcdf$loan_status, lcdf$sub_grade)
#Default loans are the loans that are Charged off.
#Plot for Variation by Grade for Default Loans
lcdf %>% group_by(grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt))
ggplot(lcdf,aes(x = grade, fill = loan_status))+geom_bar()+geom_text(aes(label=..count..),stat="count",position=position_stack())+ggtitle("Variation by Grade for Default Loans")+theme(plot.title = element_text(hjust = 0.5))
ggsave("Variation by Grade for Default Loans.png", width = 5, height = 5)
#Plot for Variation by Subgrade for Default Loans
lcdf %>% group_by(sub_grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt))
ggplot(lcdf,aes(x = sub_grade, fill = loan_status))+geom_bar()+ggtitle("Variation by Subgrade for Default Loans")+theme(plot.title = element_text(hjust = 0.5))
ggsave("Variation by Subgrade for Default Loans.png", width = 5, height = 5)
#Number of loans for each category of loans
lcdf %>% group_by(grade) %>% tally()
ggplot(lcdf,aes(x = grade, fill = grade))+geom_bar()+geom_text(aes(label=..count..),stat="count",position=position_stack())+ggtitle("No. of loans for each category of grade")+theme(plot.title = element_text(hjust = 0.5))
ggsave("No. of loans for each category of grade.png", width = 5, height = 5)
#Relationship between Loan Amount and Grade
lcdf %>% group_by(grade) %>% summarise(sum(loan_amnt))
lcdf %>% group_by(grade) %>% summarise(mean(loan_amnt))
ggplot(lcdf, aes(x=grade, y=loan_amnt ,fill=grade)) + geom_boxplot() + ggtitle("Variation of loan amount with grade")+theme(plot.title = element_text(hjust = 0.5))
ggsave("Variation of loan amount with grade.png", width = 5, height = 5)
ggplot(lcdf, aes( x = loan_amnt)) + geom_histogram(aes(fill=grade))
ggplot(lcdf, aes( x = loan_amnt)) + geom_histogram() + facet_wrap(~loan_status)
#Relationship between Grade and Interest Rate
lcdf %>% group_by(grade) %>% summarise(mean(int_rate))
ggplot(lcdf, aes( x = int_rate)) + geom_histogram()
ggsave("Histogram Plot for interest rate variation with grade.png", width = 5 , height = 5)
#Relationship between Subgrade and Interest Rate
lcdf %>% group_by(sub_grade) %>% summarise(mean(int_rate))
#Indentifying the purpose for which borrowers are taking the loans
#For exploration lets use the table function to get a rough estimate
table(lcdf$purpose)
#Formulating the result in a better tabulated format
lcdf %>% group_by(purpose) %>% tally()
ggplot(lcdf,aes(x = purpose, fill = loan_status))+geom_bar()+ggtitle("Variation of loans by purpose")+theme(plot.title = element_text(hjust = 0.5))
ggsave("Variation of loans by purpose.png", height = 5, width = 5)
#Relationship between Defaults and Purpose
lcdf %>% group_by(purpose) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt))
#calculate the annualized percentage return
lcdf$annRet <- ((lcdf$total_pymnt -lcdf$funded_amnt)/lcdf$funded_amnt)*(12/36)*100
lcdf %>% group_by(grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgRet=mean(annRet), stdRet=sd(annRet), minRet=min(annRet), maxRet=max(annRet))
#For loans that are paid back early - find out the actual loan term in months
# Since last_pymnt_d is a chr variable, we need to convert it to a date variable
lcdf$last_pymnt_d<-paste(lcdf$last_pymnt_d, "-01", sep = "")
lcdf$last_pymnt_d<-parse_date_time(lcdf$last_pymnt_d, "myd")
lcdf$actualTerm <- ifelse(lcdf$loan_status=="Fully Paid", as.duration(lcdf$issue_d %--% lcdf$last_pymnt_d)/dyears(1), 3)
#Then, considering this actual term, we can calculate the actual annual return
lcdf$actualReturn <-(((lcdf$total_pymnt-lcdf$funded_amnt)/lcdf$funded_amnt)/lcdf$actualTerm)*(12/36)*100
#For cost-based performance, we want to see the average interest rate, and the average of proportion of loan amount paid back, grouped by loan_status
lcdf%>% group_by(loan_status) %>% summarise(intRate=mean(int_rate), totRet=mean((total_pymnt-funded_amnt)/funded_amnt))
# Notice that the totRet on Charged Off loans as -0.366, so, for every dollar invested, there is a loss of .366 cents. The totRet seems less than what we may expected because we assume that the borrowers will use the full loan term to pay back, however some borrowers paid back much faster and much before time than what was utilised to calculate their interest rate. Thus since some loans were paid before time, their expected interest rate will differ from the total return
#summary of actualReturn by Grade
lcdf %>% group_by(grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), default_rate = (sum(loan_status=="Charged Off")/n()), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgactualRet=mean(actualReturn), stdactualRet=sd(actualReturn), minactualRet=min(actualReturn),maxactualRet=max(actualReturn))
#summary of actualReturn by Subgrade
lcdf %>% group_by(sub_grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), default_rate = (sum(loan_status=="Charged Off")/n()), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgactualRet=mean(actualReturn), stdactualRet=sd(actualReturn), minactualRet=min(actualReturn), maxactualRet=max(actualReturn))
#Tabulated from of actualTerm and actualReturn
lcdf %>% select(loan_status, loan_amnt, funded_amnt, total_pymnt, int_rate, actualTerm, actualReturn) %>% View()
lcdf %>% group_by(grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), defaultRate=defaults/nLoans)
#convert emp_length to factor -- can order the factors in a meaningful way
lcdf$emp_length <- factor(lcdf$emp_length, levels=c("n/a", "< 1 year","1 year","2 years", "3 years" , "4 years", "5 years", "6 years", "7 years" , "8 years", "9 years", "10+ years" ))
#Note - character variables can cause a problem with some model packages, so better to convert all of these to factors
lcdf= lcdf %>% mutate_if(is.character, as.factor)
```
#Deriving new attributes
```{r}
dim(lcdf)
#We generate some derived attributes that may be useful for predicting default
#The first derived attribute is the proportion of satisfactory bankcard accounts
lcdf$propSatisBankcardAccts <- ifelse(lcdf$num_bc_tl>0, lcdf$num_bc_sats/lcdf$num_bc_tl, 0)
#The second derived attribute is to calculate the length of borrower's history with LC
# i.e time between earliest_cr_line and issue_d
lcdf$earliest_cr_line<-paste(lcdf$earliest_cr_line, "-01", sep = "")
lcdf$earliest_cr_line<-parse_date_time(lcdf$earliest_cr_line, "myd")
tail(lcdf$earliest_cr_line)
tail(lcdf$issue_d)
as.Date(lcdf$issue_d)
lcdf$issue_d <- as.Date(lcdf$issue_d)
#or we can use the lubridate functions to precidely handle date-times durations
lcdf$borrHistory <- as.duration(lcdf$earliest_cr_line %--% lcdf$issue_d) /365
tail(lcdf$borrHistory)
#Another new attribute: ratio of openAccounts to totalAccounts
lcdf$ratio_open_to_totalac<-c(lcdf$open_acc/lcdf$total_acc)
tail(lcdf$ratio_open_to_totalac)
# Another new attribute: proportion of funded_amnt to installments
lcdf$prop_funded_install <- amnt <- lcdf$funded_amnt/lcdf$installment
tail(lcdf$prop_funded_install)
# Another new attribute: current balance per active account
lcdf$cur_bal_open_acc <- lcdf$tot_cur_bal/lcdf$open_acc
tail(lcdf$cur_bal_open_acc)
# Another new attribute: proportion of funded_amnt to installments
lcdf$per_install_amnt <- lcdf$funded_amnt/lcdf$installment
tail(lcdf$per_install_amnt)
dim(lcdf)
colnames(lcdf)
```
#Understanding the missing values
```{r}
#Step 1: Dropping all variables wih empty values
lcdf <- lcdf %>% select_if(function(x){!all(is.na(x))})
#missing value proportions in each column
colMeans(is.na(lcdf))
#Step 2: Dropping only those columns where there are missing values
colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0]
#Step 3: Dropping variables which have more than 60% missing values
nm<-names(lcdf)[colMeans(is.na(lcdf))>0.6]
lcdf <- lcdf %>% select(-nm)
#Step 4: Evaluating which remaining columns have missing values
missing_value_col <- names(colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0])
missing_value_col
#Step 5: Removing two variables popping up
drop <- c("emp_title","last_credit_pull_d")
lcdf = lcdf[,!(names(lcdf) %in% drop)]
missing_value_col <- names(colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0])
length(missing_value_col)
#Step 6: Replace the remaining variables popping up
#Summarise each remaining variable and replace with suitable replacements like mean or median depending on judgement
summary(lcdf$mths_since_last_delinq)
summary(lcdf$bc_util)
summary(lcdf$revol_util)
summary(lcdf$bc_open_to_buy)
summary(lcdf$mo_sin_old_il_acct)
summary(lcdf$mths_since_recent_bc)
summary(lcdf$mths_since_recent_inq)
summary(lcdf$num_tl_120dpd_2m)
summary(lcdf$percent_bc_gt_7)
lcdf<- lcdf %>% replace_na(list(mths_since_last_delinq=250, bc_util=median(lcdf$bc_util, na.rm=TRUE), revol_util=median(lcdf$revol_util, na.rm=TRUE), bc_open_to_buy=median(lcdf$bc_open_to_buy, na.rm = TRUE), mo_sin_old_il_acct=0, mths_since_recent_bc=0, mths_since_recent_inq=0, num_tl_120dpd_2m=0, percent_bc_gt_75=50))
```
#Tackling Data Leakage
```{r}
varstoremove1 <- c("funded_amnt_inv", "term", "emp_title","issue_d", "earliest_cr_line", "application_type", "hardship_flag", "home_ownership", "pymnt_plan", "out_prncp", "out_prncp_inv", "last_credit_pull_d", "policy_code", "disbursement_method", "debt_settlement_flag", "pub_rec", "pub_rec_bankruptcies", "tax_liens", "delinq_amnt", "collections_12_mths_ex_med", "mths_since_last_major_derog", "acc_now_delinq", "total_il_high_credit_limit", "tot_cur_bal", "collection_recovery_fee", "recoveries","total_pymnt", "acc_open_past_24mths","total_bc_limit", "total_rec_prncp", "bc_open_to_buy", "bc_util", "num_bc_tl", "num_rev_tl_bal_gt_0", "num_il_tl", "num_sats", "num_tl_op_past_12m", "num_op_rev_tl","num_actv_rev_tl", "last_pymnt_d", "actualReturn", "actualTerm", "mths_since_recent_revol_delinq", "zip_code", "title", "addr_state", "total_rev_hi_lim","total_rec_int", "last_pymnt_amnt","mths_since_recent_bc_dlq","annRet", "totRet","chargeoff_within_12_mths", "total_rec_late_fee", "pct_tl_nvr_dlq" , "cur_bal_open_acc", "prop_funded_install", "ratio_open_to_totalac")
lcdf <- lcdf %>% select(-one_of(varstoremove1))
dim(lcdf)
#converting emp_length to appropriate format
lcdf$emp_length <- as.numeric(gsub("\\D", "", lcdf$emp_length))
summary(lcdf$emp_length)
#imputing missing value
lcdf <- lcdf %>% replace_na(list(emp_length=median(lcdf$emp_length, na.rm=TRUE)))
summary(lcdf$emp_length)
```
#Adding certain variables back
```{r}
library(caret)
dcorplot <- c("initial_list_status","loan_status","purpose","verification_status","sub_grade","grade")
mvcol <- names(colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0]) #mths_since_recent_revol_delinq
length(mvcol)
lcdfn <- lcdf[,!(names(lcdf) %in% dcorplot)]
sapply(lcdfn, is.factor)
correlation_matrix <- cor(lcdfn)
#cor(lcdfn[sapply(lcdfn, function(x) !is.factor(x))])
corr_var <- findCorrelation(correlation_matrix, cutoff = 0.8, verbose = TRUE, names = TRUE, exact = ncol(correlation_matrix) < 100)
#drop_for_corplot_dataframe <- data.frame(lcdf$debt_settlement_flag,lcdf$initial_list_status)
#Adding back the dcorplot variables for model
lcdfn <- lcdfn[,!(names(lcdfn) %in% corr_var)]
lcdf1 <- data.frame(lcdfn,lcdf[, dcorplot])
colnames(lcdf)
```
#Rpart Decision Tree
```{r}
library(rpart)
library(rpart.plot)
library(RColorBrewer)
library(rattle)
library(C50)
#It can be useful to convert the target variable, loan_status to a factor variable. If we dont then it can give us trouble later on
lcdf1$loan_status <- factor(lcdf$loan_status, levels=c("Fully Paid", "Charged Off"))
sapply(lcdf1,class)
#Changing categorical variables into factors
lcdf1$initial_list_status = as.factor(lcdf1$initial_list_status)
lcdf1$loan_status = as.factor(lcdf1$loan_status)
lcdf1$purpose = as.factor(lcdf1$purpose)
lcdf1$verification_status = as.factor(lcdf1$verification_status)
lcdf1$sub_grade = as.factor(lcdf1$sub_grade)
lcdf1$grade = as.factor(lcdf1$grade)
#split the data into Training = trn, Testing = tst subsets. We have taken a split of 70-30.
set.seed(6746)
nr<-nrow(lcdf1)
trnIndex<- sample(1:nr, size = round(0.7*nr), replace=FALSE)
lcdf1Trn <- lcdf1[trnIndex, ]
lcdf1Tst <- lcdf1[-trnIndex, ]
#testing dataset split
tail(lcdf1)
dim(lcdf1Tst)
tail(lcdf1Tst)
dim(lcdf1Trn)
tail(lcdf1Trn)
#For Information gain
library(rattle)
lcDT1 <- rpart(loan_status ~., data=lcdf1Trn, method="class", parms = list(split = "information"), control = rpart.control(cp=0.0001, minsplit = 50))
fancyRpartPlot(lcDT1)
rpart.plot(lcDT1)
pdf("dtree.pdf")
#Do we want to prune the tree -- check for performance with dfferent cp levels
printcp(lcDT1)
lcDT1$cptable[which.min(lcDT1$cptable[,"xerror"]),"CP"]
plotcp(lcDT1)
lcDT1p<- prune.rpart(lcDT1, cp=0.0001)
fancyRpartPlot(lcDT1p)
predTrn=predict(lcDT1,lcdf1Trn, type='class')
table(pred = predTrn, true=lcdf1Trn$loan_status)
predTst <- predict(lcDT1,lcdf1Tst, type='class')
table(pred = predict(lcDT1,lcdf1Tst, type='class'), true=lcdf1Tst$loan_status)
#With a different classsification threshold
CTHRESH=0.6
predProbTrn=predict(lcDT1,lcdf1Trn, type='prob')
predTrnCT = ifelse(predProbTrn[, 'Charged Off'] > CTHRESH, 'Charged Off', 'Fully Paid')
table(predTrnCT , true=lcdf1Trn$loan_status)
predProbTrn<-cbind(predProbTrn, lcdf1Trn$loan_status)
predProbTrn[1:50,]
predProbTst<-cbind(predProbTst, lcdf1Tst$loan_status)
predProbTst[1:50,]
confusionMatrix(predTrn, lcdf1Trn$loan_status, positive="Charged Off")
confusionMatrix(predTst, lcdf1Tst$loan_status, positive="Charged Off")
#ROC plot
library(ROCR)
score=predict(lcDT1,lcdf1Tst, type="prob")[,"Charged Off"]
pred_2=prediction(score, lcdf1Tst$loan_status, label.ordering = c("Fully Paid", "Charged Off"))
#label.ordering here specifies the 'negative', 'positive' class labels
#ROC curve
aucPerf <-performance(pred_2, "tpr", "fpr")
plot(aucPerf)
abline(a=0, b= 1)
#AUC value
aucPerf=performance(pred_2, "auc")
aucPerf@y.values
#Lift curve
liftPerf <-performance(pred_2, "lift", "rpp")
plot(liftPerf)
dim(lcdf1)
#library(ROSE)
#loans.oversampled <- ovun.sample(loan_status~., data=lcdf1Trn, method = "over", seed = 15)$data
#table(loans.oversampled$loan_status)
#tune <- data.frame(0.001)
#colnames(tune) <- "cp"
#tr_control <- trainControl(method = "cv",number = 10, verboseIter = TRUE)
#loans.rpart.oversampled <- train(loan_status ~., data = loans.oversampled, method = "rpart", trControl = tr_control, #tuneGrid = tune, control=rpart.control(minsplit=10, minbucket = 3))
#fancyRpartPlot(loans.rpart.oversampled$finalModel)
#confusionMatrix(predict(loans.rpart.oversampled, lcdf1Tst), lcdf1Tst$loan_status)
library(RColorBrewer)
library(rpart.plot)
library(rpart)
install.packages("rattle", repos="https://rattle.togaware.com", type="source")
library(rattle)
```
#C50 Decision Tree
```{r}
#Building decision tree model using c50
library(C50)
#It can be useful to convert the target variable, loan_status to a factor variable
lcdf1Trn$loan_status <- factor(lcdf1Trn$loan_status, levels=c("Fully Paid", "Charged Off"))
lcdf1Tst$loan_status <- factor(lcdf1Tst$loan_status, levels=c("Fully Paid", "Charged Off"))
lcdf1Trn$loan_status <-as.factor(lcdf1Trn$loan_status)
lcdf1Tst$loan_status <- as.factor(lcdf1Tst$loan_status)
class(lcdf1Trn$loan_status)
colnames(lcdf1Trn)
lcdf_Trn_c50<- C5.0(x=lcdf1Trn~., data =lcdf1Trn, method="class", parms= list(split='information'))
lcdf_Trn_c50<- C5.0(x=lcdf1Trn, y=lcdf1Trn$loan_status, weights = 100)
str(lcdf_Trn_c50)
levels(lcdf_Trn_c50$)[1] = "missing"
summary(lcdf1Trn)
#Replace rpart function by C5.0 to build the tree
plot(lcdf_Trn_c50,subtree=1)
#Making Predictions
predictions=predict(lcdf_Trn_c50, data = lcdf1Trn, type='class')
#Summarizing the accuracy train
table(predictions, lcdf1Trn$loan_status)
plot(lcdf_Trn_c50)
confusionMatrix( table(predictions, lcdf1Trn$loan_status) )
table(pred = predTrn_whole, true=lcdf1Trn$lcdf1Trn~.)
confusionMatrix( table(predictions_tst, lcdf1Tst$loan_status) )
#Accuracy
mean(predictions==lcdf1Trn$lcdf1Trn~.)
library(ROCR)
#score test
lcdf1Trn$score<-predict(lcdf_Trn_c50,type='prob',lcdf1Tst)
pred <-prediction(lcdf1Trn$score[,2],lcdf1Trn$lcdf1Trn~.)
perf <- performance(pred,"tpr","fpr")
plot(perf, main="ROC Curve")
```
#Modelling Random Forest
```{r}
#Building random forest model
library('randomForest')
#for reproducible results, set a specific value for the random number seed
set.seed(900)
lcdfRF <- lcdf1
levels(lcdfRF$loan_status) <- c(0,1)
#dividing in training n testing
set.seed(1784)
nr<-nrow(lcdfRF)
trnIndex<- sample(1:nr, size = round(0.7*nr), replace=FALSE)
lcdfRF_Trn <- lcdfRF[trnIndex, ]
lcdfRF_Tst <- lcdfRF[-trnIndex, ]
#Developing Model1 with 200 Trees
rfM1 = randomForest(loan_status~., data=lcdfRF_Trn, ntree=200, importance=TRUE )
rfM1
# Predicting on Validation set
PV1 <- predict(rfM1, lcdfRF_Tst, type = "class")
# Looking for classification accuracy for Model 1
Acc1 <- mean(PV1 == lcdfRF_Tst$loan_status)
table(PV1,lcdfRF_Tst$loan_status)
#Developing Model2 with 200 Trees with additional condition
rfM2 = randomForest(loan_status~., data=lcdfRF_Trn, ntree=200, mtry = 6, importance=TRUE )
rfM2
# Predicting on Validation set
PV2 <- predict(rfM2, lcdfRF_Tst, type = "class")
# Looking for classification accuracy for Model 2
Acc2 <- mean(PV2 == lcdf_rf_Tst$loan_status)
table(PV2,lcdfRF_Tst$loan_status)
#Developing Model3 with 100 Trees with additional condition
rfM3 = randomForest(loan_status~., data=lcdfRF_Trn, ntree=100, importance=TRUE )
# Predicting on Validation set
PV3 <- predict(rfM3, lcdfRF_Tst, type = "class")
# Looking for classification accuracy for Model 3
Acc3 <- mean(PV3 == lcdfRF_Tst$loan_status)
table(PV3,lcdfRF_Tst$loan_status)
# To check important variables
importance(rfM1)
varImpPlot(rfM1)
importance(rfM2)
varImpPlot(rfM2)
importance(rfM3)
varImpPlot(rfM3)
#Draw the ROC curve for the randomForest model
perfROC_rfTst=performance(prediction(predict(rfM2,lcdfRF_Tst, type="prob")[,2], lcdfRF_Tst$loan_status), "tpr", "fpr")
plot(perfROC_rfTst)
#Draw the lift curve fr the random forest model
perfLift_rfTst=performance(prediction(predict(rfM2,lcdfRF_Tst, type="prob")[,2], lcdfRF_Tst$loan_status), "lift", "rpp")
plot(perfLift_rfTst)
#ROC curves for the decision-tree model and the random forest model in the same plot
perfROC_dt1Tst=performance(prediction(predict(lcDT1,lcdf1Tst, type="prob")[,2], lcdf1Tst$loan_status), "tpr", "fpr")
perfRoc_rfTst=performance(prediction(predict(rfM3,lcdfRF_Tst, type="prob")[,2], lcdfRF_Tst$loan_status), "tpr", "fpr")
plot(perfROC_dt1Tst, col='red')
plot(perfRoc_rfTst, col='green', add=TRUE)
legend('bottomright', c('DecisionTree', 'RandomForest'), lty=1, col=c('red', 'green'))
```
#Modelling for GBM
```{r}
instlall.packages(gbm)
#Dividing the Training and Testing models
set.seed(8945)
head(lcdf1$loan_status)
levels(lcdf1$loan_status)
dim(lcdf1)
colnames(lcdf1)
#Variable has 1 for Fully Paid and 0 for Charged off
head(unclass(lcdf1$loan_status))
head(unclass(lcdf$loan_status)-1)
lcdfgbm <- lcdf1
nr<-nrow(lcdfgbm)
trnIndex<- sample(1:nr, size = round(0.7*nr), replace=FALSE)
lcdfgbmTrn <- lcdf1[trnIndex, ]
lcdfgbmTst <- lcdf1[-trnIndex, ]
lcdfgbmTrn <- lcdfgbmTrn[,-41]
lcdfgbmTst <- lcdfgbmTst[,-41]
lcdf$annRet <- ((lcdf$total_pymnt -lcdf$funded_amnt)/lcdf$funded_amnt)*(12/36)*100
lcdfgbm1<- gbm(formula = unclass(loan_status)-1 ~ .,data = subset(lcdfgbmTrn, select= -c(annRet)), distribution = "gaussian", n.trees = 4000, interaction.depth = 1, shrinkage = 0.001, cv.folds = 5, n.cores = NULL,verbose = FALSE)
print(lcdfgbm1)
# find index for n trees with minimum CV error
min_MSE <- which.min(lcdfgbm1$cv.error)
min_MSE
#calculating minimum RMSE
sqrt(min(lcdfgbm1$cv.error))
# plot loss function as a result of n trees added to the ensemble
gbm.perf(lcdfgbm1, method = 'cv')
Bestler <- gbm.perf(lcdfgbm1, method='cv')
summary(lcdfgbm1)
summary(lcdfgbm1, method=permutation.test.gbm)
Plot(lcdfgbm1, i="int_rate")
```
```{r}
#Incorporating profits & costs
library(dplyr)
PROFITVAL=100 #profit (on $100) from accurately identifying Fully_paid loans
COSTVAL=-500 # loss (on $100) from incorrectly predicting a Charged_Off loan as Full_paid
scoreTst=predict(lcDT1,lcdf1Tst, type="prob")[,"Fully Paid"]
#Identifying those loans wth high probability for being Fully Paid
prPerf=data.frame(scoreTst)
prPerf=cbind(prPerf, status=lcdf1Tst$loan_status)
#Sorting in descending order of probability (fully_paid)
prPerf=prPerf[order(-scoreTst) ,]
prPerf1=prPerf%>%mutate(profit=ifelse(prPerf$status == 'Fully Paid', PROFITVAL, COSTVAL))
cumProfit=cumsum(prPerf$profit)
#Comparing against the default approach of investing in CD with 2% int (i.e. $6 profit out of $100 in 3 years)
prPerf$cdRet <- 6
na.omit(prPerf)
na.omit(prPerf1)
prPerf$cumCDRet <- cumsum(prPerf$cdRet)
plot(cumProfit)
lines(prPerf1$cumCDRet, col='purple')
#Or, we really do not need to have the cdRet and cumCDRet columns, since cdRet is $6 for every row
plot(prPerf1$cumProfit)
abline(a=0, b=6)
#Finding the score coresponding to the max profit
maxProfit= max(prPerf1$cumProfit)
maxProfit_Ind = which.max(prPerf1$cumProfit)
maxProfit_score = prPerf1$scoreTst[maxProfit_Ind]
print(c(maxProfit = maxProfit, scoreTst = maxProfit_score))
```
```{r}
library(gbm)
#annRet<-((lcdf$total_pymnt -lcdf$funded_amnt)/lcdf$funded_amnt)*(12/36)*100
#actualTerm<-((lcdf$loan_status=="Fully Paid", as.duration(lcdf$issue_d %--% lcdf$last_pymnt_d)/dyears(1), 3))
#actualReturn
#total_pymnt
rfModelGp<-ranger(loan_status~., data=subset(lcdfTrn, select=-c(annRet, actualTerm, actualReturn, total_pymnt)), num.trees=200,importance='permutation')
gbm_M2 <-gbm(formula=unclass(loan_status)-1 ~., data=subset(lcdfTrn, select=-c(annRet, actualTerm, actualReturn)), distribution = "bernoulli", n.trees=2000, shrinkage=0.01, interaction.depth= 4, bag.fraction=0.5, cv.folds= 5, n.cores=16)
bestIter<-gbm.perf(gbm_M2, method='cv')
scores_gbmM2<-predict(gbm_M2, newdata=lcdfTst, n.tree= bestIter, type="response") pred_gbmM2=prediction(scores_gbmM2, lcdfTst$loan_status, label.ordering= c("Charged Off", "Fully Paid"))
#label.orderinghere specifies the 'negative', 'positive' class labels
aucPerf_gbmM2 <-performance(pred_gbmM2, "tpr", "fpr")
plot(aucPerf_gbmM2)
abline(a=0, b= 1)
rfModelGp<-ranger(loan_status~., data=subset(lcdfTrn, select=-c(annRet, actualTerm, actualReturn, total_pymnt)), num.trees=200, importance='permutation')
scoreTstRF<-predict(rfModel1,lcdfTst, type="prob")[,"Fully Paid"]
predRF=prediction(scoreTstRF, lcdfTst$loan_status, label.ordering= c("Charged Off", "Fully Paid"))
aucPerfRF<-performance(predRF, "tpr", "fpr")
plot(aucPref_gbmM2, col='red', add=TRUE)
legend('bottomright', c('RandomForest', 'gbm'), lty=1, col=c('black', 'red'))
```
| /updated_file_lending cub with gbm.R | no_license | vanshdeepsingh1/Lending_Club | R | false | false | 26,293 | r | ---
title: "R Notebook"
output: html_notebook
---
This is an [R Markdown](http://rmarkdown.rstudio.com) Notebook. When you execute code within the notebook, the results appear beneath the code.
Try executing this chunk by clicking the *Run* button within the chunk or by placing your cursor inside it and pressing *Ctrl+Shift+Enter*.
```{r}
library(tidyverse)
library(lubridate)
library(ggplot2)
```
# The lcData6m.csv file contains data on 3 year loans issues in the first 6 months of 2015, which we will use for this analyses
```{r}
lcdf <- read.csv("C:/Users/LENOVO/Desktop/2018 vansh industrial/data mining/lcData6m.csv")
View(lcdf)
dim(lcdf)
```
#Data Exploration
```{r}
#How does loan status vary by loan grade
lcdf %>% group_by(loan_status, grade) %>% tally()
table(lcdf$loan_status, lcdf$grade)
#Filtering out the loans with 'Current' Status
lcdf <- lcdf %>% filter(loan_status !="Current")
#How does loan status vary by loan sub grade
lcdf %>% group_by(loan_status, sub_grade) %>% tally()
table(lcdf$loan_status, lcdf$sub_grade)
#Default loans are the loans that are Charged off.
#Plot for Variation by Grade for Default Loans
lcdf %>% group_by(grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt))
ggplot(lcdf,aes(x = grade, fill = loan_status))+geom_bar()+geom_text(aes(label=..count..),stat="count",position=position_stack())+ggtitle("Variation by Grade for Default Loans")+theme(plot.title = element_text(hjust = 0.5))
ggsave("Variation by Grade for Default Loans.png", width = 5, height = 5)
#Plot for Variation by Subgrade for Default Loans
lcdf %>% group_by(sub_grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt))
ggplot(lcdf,aes(x = sub_grade, fill = loan_status))+geom_bar()+ggtitle("Variation by Subgrade for Default Loans")+theme(plot.title = element_text(hjust = 0.5))
ggsave("Variation by Subgrade for Default Loans.png", width = 5, height = 5)
#Number of loans for each category of loans
lcdf %>% group_by(grade) %>% tally()
ggplot(lcdf,aes(x = grade, fill = grade))+geom_bar()+geom_text(aes(label=..count..),stat="count",position=position_stack())+ggtitle("No. of loans for each category of grade")+theme(plot.title = element_text(hjust = 0.5))
ggsave("No. of loans for each category of grade.png", width = 5, height = 5)
#Relationship between Loan Amount and Grade
lcdf %>% group_by(grade) %>% summarise(sum(loan_amnt))
lcdf %>% group_by(grade) %>% summarise(mean(loan_amnt))
ggplot(lcdf, aes(x=grade, y=loan_amnt ,fill=grade)) + geom_boxplot() + ggtitle("Variation of loan amount with grade")+theme(plot.title = element_text(hjust = 0.5))
ggsave("Variation of loan amount with grade.png", width = 5, height = 5)
ggplot(lcdf, aes( x = loan_amnt)) + geom_histogram(aes(fill=grade))
ggplot(lcdf, aes( x = loan_amnt)) + geom_histogram() + facet_wrap(~loan_status)
#Relationship between Grade and Interest Rate
lcdf %>% group_by(grade) %>% summarise(mean(int_rate))
ggplot(lcdf, aes( x = int_rate)) + geom_histogram()
ggsave("Histogram Plot for interest rate variation with grade.png", width = 5 , height = 5)
#Relationship between Subgrade and Interest Rate
lcdf %>% group_by(sub_grade) %>% summarise(mean(int_rate))
#Indentifying the purpose for which borrowers are taking the loans
#For exploration lets use the table function to get a rough estimate
table(lcdf$purpose)
#Formulating the result in a better tabulated format
lcdf %>% group_by(purpose) %>% tally()
ggplot(lcdf,aes(x = purpose, fill = loan_status))+geom_bar()+ggtitle("Variation of loans by purpose")+theme(plot.title = element_text(hjust = 0.5))
ggsave("Variation of loans by purpose.png", height = 5, width = 5)
#Relationship between Defaults and Purpose
lcdf %>% group_by(purpose) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt))
#calculate the annualized percentage return
lcdf$annRet <- ((lcdf$total_pymnt -lcdf$funded_amnt)/lcdf$funded_amnt)*(12/36)*100
lcdf %>% group_by(grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgRet=mean(annRet), stdRet=sd(annRet), minRet=min(annRet), maxRet=max(annRet))
#For loans that are paid back early - find out the actual loan term in months
# Since last_pymnt_d is a chr variable, we need to convert it to a date variable
lcdf$last_pymnt_d<-paste(lcdf$last_pymnt_d, "-01", sep = "")
lcdf$last_pymnt_d<-parse_date_time(lcdf$last_pymnt_d, "myd")
lcdf$actualTerm <- ifelse(lcdf$loan_status=="Fully Paid", as.duration(lcdf$issue_d %--% lcdf$last_pymnt_d)/dyears(1), 3)
#Then, considering this actual term, we can calculate the actual annual return
lcdf$actualReturn <-(((lcdf$total_pymnt-lcdf$funded_amnt)/lcdf$funded_amnt)/lcdf$actualTerm)*(12/36)*100
#For cost-based performance, we want to see the average interest rate, and the average of proportion of loan amount paid back, grouped by loan_status
lcdf%>% group_by(loan_status) %>% summarise(intRate=mean(int_rate), totRet=mean((total_pymnt-funded_amnt)/funded_amnt))
# Notice that the totRet on Charged Off loans as -0.366, so, for every dollar invested, there is a loss of .366 cents. The totRet seems less than what we may expected because we assume that the borrowers will use the full loan term to pay back, however some borrowers paid back much faster and much before time than what was utilised to calculate their interest rate. Thus since some loans were paid before time, their expected interest rate will differ from the total return
#summary of actualReturn by Grade
lcdf %>% group_by(grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), default_rate = (sum(loan_status=="Charged Off")/n()), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgactualRet=mean(actualReturn), stdactualRet=sd(actualReturn), minactualRet=min(actualReturn),maxactualRet=max(actualReturn))
#summary of actualReturn by Subgrade
lcdf %>% group_by(sub_grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), default_rate = (sum(loan_status=="Charged Off")/n()), avgInterest= mean(int_rate), stdInterest=sd(int_rate), avgLoanAMt=mean(loan_amnt), avgPmnt=mean(total_pymnt), avgactualRet=mean(actualReturn), stdactualRet=sd(actualReturn), minactualRet=min(actualReturn), maxactualRet=max(actualReturn))
#Tabulated from of actualTerm and actualReturn
lcdf %>% select(loan_status, loan_amnt, funded_amnt, total_pymnt, int_rate, actualTerm, actualReturn) %>% View()
lcdf %>% group_by(grade) %>% summarise(nLoans=n(), defaults=sum(loan_status=="Charged Off"), defaultRate=defaults/nLoans)
#convert emp_length to factor -- can order the factors in a meaningful way
lcdf$emp_length <- factor(lcdf$emp_length, levels=c("n/a", "< 1 year","1 year","2 years", "3 years" , "4 years", "5 years", "6 years", "7 years" , "8 years", "9 years", "10+ years" ))
#Note - character variables can cause a problem with some model packages, so better to convert all of these to factors
lcdf= lcdf %>% mutate_if(is.character, as.factor)
```
#Deriving new attributes
```{r}
dim(lcdf)
#We generate some derived attributes that may be useful for predicting default
#The first derived attribute is the proportion of satisfactory bankcard accounts
lcdf$propSatisBankcardAccts <- ifelse(lcdf$num_bc_tl>0, lcdf$num_bc_sats/lcdf$num_bc_tl, 0)
#The second derived attribute is to calculate the length of borrower's history with LC
# i.e time between earliest_cr_line and issue_d
lcdf$earliest_cr_line<-paste(lcdf$earliest_cr_line, "-01", sep = "")
lcdf$earliest_cr_line<-parse_date_time(lcdf$earliest_cr_line, "myd")
tail(lcdf$earliest_cr_line)
tail(lcdf$issue_d)
as.Date(lcdf$issue_d)
lcdf$issue_d <- as.Date(lcdf$issue_d)
#or we can use the lubridate functions to precidely handle date-times durations
lcdf$borrHistory <- as.duration(lcdf$earliest_cr_line %--% lcdf$issue_d) /365
tail(lcdf$borrHistory)
#Another new attribute: ratio of openAccounts to totalAccounts
lcdf$ratio_open_to_totalac<-c(lcdf$open_acc/lcdf$total_acc)
tail(lcdf$ratio_open_to_totalac)
# Another new attribute: proportion of funded_amnt to installments
lcdf$prop_funded_install <- amnt <- lcdf$funded_amnt/lcdf$installment
tail(lcdf$prop_funded_install)
# Another new attribute: current balance per active account
lcdf$cur_bal_open_acc <- lcdf$tot_cur_bal/lcdf$open_acc
tail(lcdf$cur_bal_open_acc)
# Another new attribute: proportion of funded_amnt to installments
lcdf$per_install_amnt <- lcdf$funded_amnt/lcdf$installment
tail(lcdf$per_install_amnt)
dim(lcdf)
colnames(lcdf)
```
#Understanding the missing values
```{r}
#Step 1: Dropping all variables wih empty values
lcdf <- lcdf %>% select_if(function(x){!all(is.na(x))})
#missing value proportions in each column
colMeans(is.na(lcdf))
#Step 2: Dropping only those columns where there are missing values
colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0]
#Step 3: Dropping variables which have more than 60% missing values
nm<-names(lcdf)[colMeans(is.na(lcdf))>0.6]
lcdf <- lcdf %>% select(-nm)
#Step 4: Evaluating which remaining columns have missing values
missing_value_col <- names(colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0])
missing_value_col
#Step 5: Removing two variables popping up
drop <- c("emp_title","last_credit_pull_d")
lcdf = lcdf[,!(names(lcdf) %in% drop)]
missing_value_col <- names(colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0])
length(missing_value_col)
#Step 6: Replace the remaining variables popping up
#Summarise each remaining variable and replace with suitable replacements like mean or median depending on judgement
summary(lcdf$mths_since_last_delinq)
summary(lcdf$bc_util)
summary(lcdf$revol_util)
summary(lcdf$bc_open_to_buy)
summary(lcdf$mo_sin_old_il_acct)
summary(lcdf$mths_since_recent_bc)
summary(lcdf$mths_since_recent_inq)
summary(lcdf$num_tl_120dpd_2m)
summary(lcdf$percent_bc_gt_7)
lcdf<- lcdf %>% replace_na(list(mths_since_last_delinq=250, bc_util=median(lcdf$bc_util, na.rm=TRUE), revol_util=median(lcdf$revol_util, na.rm=TRUE), bc_open_to_buy=median(lcdf$bc_open_to_buy, na.rm = TRUE), mo_sin_old_il_acct=0, mths_since_recent_bc=0, mths_since_recent_inq=0, num_tl_120dpd_2m=0, percent_bc_gt_75=50))
```
#Tackling Data Leakage
```{r}
varstoremove1 <- c("funded_amnt_inv", "term", "emp_title","issue_d", "earliest_cr_line", "application_type", "hardship_flag", "home_ownership", "pymnt_plan", "out_prncp", "out_prncp_inv", "last_credit_pull_d", "policy_code", "disbursement_method", "debt_settlement_flag", "pub_rec", "pub_rec_bankruptcies", "tax_liens", "delinq_amnt", "collections_12_mths_ex_med", "mths_since_last_major_derog", "acc_now_delinq", "total_il_high_credit_limit", "tot_cur_bal", "collection_recovery_fee", "recoveries","total_pymnt", "acc_open_past_24mths","total_bc_limit", "total_rec_prncp", "bc_open_to_buy", "bc_util", "num_bc_tl", "num_rev_tl_bal_gt_0", "num_il_tl", "num_sats", "num_tl_op_past_12m", "num_op_rev_tl","num_actv_rev_tl", "last_pymnt_d", "actualReturn", "actualTerm", "mths_since_recent_revol_delinq", "zip_code", "title", "addr_state", "total_rev_hi_lim","total_rec_int", "last_pymnt_amnt","mths_since_recent_bc_dlq","annRet", "totRet","chargeoff_within_12_mths", "total_rec_late_fee", "pct_tl_nvr_dlq" , "cur_bal_open_acc", "prop_funded_install", "ratio_open_to_totalac")
lcdf <- lcdf %>% select(-one_of(varstoremove1))
dim(lcdf)
#converting emp_length to appropriate format
lcdf$emp_length <- as.numeric(gsub("\\D", "", lcdf$emp_length))
summary(lcdf$emp_length)
#imputing missing value
lcdf <- lcdf %>% replace_na(list(emp_length=median(lcdf$emp_length, na.rm=TRUE)))
summary(lcdf$emp_length)
```
#Adding certain variables back
```{r}
library(caret)
dcorplot <- c("initial_list_status","loan_status","purpose","verification_status","sub_grade","grade")
mvcol <- names(colMeans(is.na(lcdf))[colMeans(is.na(lcdf))>0]) #mths_since_recent_revol_delinq
length(mvcol)
lcdfn <- lcdf[,!(names(lcdf) %in% dcorplot)]
sapply(lcdfn, is.factor)
correlation_matrix <- cor(lcdfn)
#cor(lcdfn[sapply(lcdfn, function(x) !is.factor(x))])
corr_var <- findCorrelation(correlation_matrix, cutoff = 0.8, verbose = TRUE, names = TRUE, exact = ncol(correlation_matrix) < 100)
#drop_for_corplot_dataframe <- data.frame(lcdf$debt_settlement_flag,lcdf$initial_list_status)
#Adding back the dcorplot variables for model
lcdfn <- lcdfn[,!(names(lcdfn) %in% corr_var)]
lcdf1 <- data.frame(lcdfn,lcdf[, dcorplot])
colnames(lcdf)
```
#Rpart Decision Tree
```{r}
library(rpart)
library(rpart.plot)
library(RColorBrewer)
library(rattle)
library(C50)
#It can be useful to convert the target variable, loan_status to a factor variable. If we dont then it can give us trouble later on
lcdf1$loan_status <- factor(lcdf$loan_status, levels=c("Fully Paid", "Charged Off"))
sapply(lcdf1,class)
#Changing categorical variables into factors
lcdf1$initial_list_status = as.factor(lcdf1$initial_list_status)
lcdf1$loan_status = as.factor(lcdf1$loan_status)
lcdf1$purpose = as.factor(lcdf1$purpose)
lcdf1$verification_status = as.factor(lcdf1$verification_status)
lcdf1$sub_grade = as.factor(lcdf1$sub_grade)
lcdf1$grade = as.factor(lcdf1$grade)
#split the data into Training = trn, Testing = tst subsets. We have taken a split of 70-30.
set.seed(6746)
nr<-nrow(lcdf1)
trnIndex<- sample(1:nr, size = round(0.7*nr), replace=FALSE)
lcdf1Trn <- lcdf1[trnIndex, ]
lcdf1Tst <- lcdf1[-trnIndex, ]
#testing dataset split
tail(lcdf1)
dim(lcdf1Tst)
tail(lcdf1Tst)
dim(lcdf1Trn)
tail(lcdf1Trn)
#For Information gain
library(rattle)
lcDT1 <- rpart(loan_status ~., data=lcdf1Trn, method="class", parms = list(split = "information"), control = rpart.control(cp=0.0001, minsplit = 50))
fancyRpartPlot(lcDT1)
rpart.plot(lcDT1)
pdf("dtree.pdf")
#Do we want to prune the tree -- check for performance with dfferent cp levels
printcp(lcDT1)
lcDT1$cptable[which.min(lcDT1$cptable[,"xerror"]),"CP"]
plotcp(lcDT1)
lcDT1p<- prune.rpart(lcDT1, cp=0.0001)
fancyRpartPlot(lcDT1p)
predTrn=predict(lcDT1,lcdf1Trn, type='class')
table(pred = predTrn, true=lcdf1Trn$loan_status)
predTst <- predict(lcDT1,lcdf1Tst, type='class')
table(pred = predict(lcDT1,lcdf1Tst, type='class'), true=lcdf1Tst$loan_status)
#With a different classsification threshold
CTHRESH=0.6
predProbTrn=predict(lcDT1,lcdf1Trn, type='prob')
predTrnCT = ifelse(predProbTrn[, 'Charged Off'] > CTHRESH, 'Charged Off', 'Fully Paid')
table(predTrnCT , true=lcdf1Trn$loan_status)
predProbTrn<-cbind(predProbTrn, lcdf1Trn$loan_status)
predProbTrn[1:50,]
predProbTst<-cbind(predProbTst, lcdf1Tst$loan_status)
predProbTst[1:50,]
confusionMatrix(predTrn, lcdf1Trn$loan_status, positive="Charged Off")
confusionMatrix(predTst, lcdf1Tst$loan_status, positive="Charged Off")
#ROC plot
library(ROCR)
score=predict(lcDT1,lcdf1Tst, type="prob")[,"Charged Off"]
pred_2=prediction(score, lcdf1Tst$loan_status, label.ordering = c("Fully Paid", "Charged Off"))
#label.ordering here specifies the 'negative', 'positive' class labels
#ROC curve
aucPerf <-performance(pred_2, "tpr", "fpr")
plot(aucPerf)
abline(a=0, b= 1)
#AUC value
aucPerf=performance(pred_2, "auc")
aucPerf@y.values
#Lift curve
liftPerf <-performance(pred_2, "lift", "rpp")
plot(liftPerf)
dim(lcdf1)
#library(ROSE)
#loans.oversampled <- ovun.sample(loan_status~., data=lcdf1Trn, method = "over", seed = 15)$data
#table(loans.oversampled$loan_status)
#tune <- data.frame(0.001)
#colnames(tune) <- "cp"
#tr_control <- trainControl(method = "cv",number = 10, verboseIter = TRUE)
#loans.rpart.oversampled <- train(loan_status ~., data = loans.oversampled, method = "rpart", trControl = tr_control, #tuneGrid = tune, control=rpart.control(minsplit=10, minbucket = 3))
#fancyRpartPlot(loans.rpart.oversampled$finalModel)
#confusionMatrix(predict(loans.rpart.oversampled, lcdf1Tst), lcdf1Tst$loan_status)
library(RColorBrewer)
library(rpart.plot)
library(rpart)
install.packages("rattle", repos="https://rattle.togaware.com", type="source")
library(rattle)
```
#C50 Decision Tree
```{r}
#Building decision tree model using c50
library(C50)
#It can be useful to convert the target variable, loan_status to a factor variable
lcdf1Trn$loan_status <- factor(lcdf1Trn$loan_status, levels=c("Fully Paid", "Charged Off"))
lcdf1Tst$loan_status <- factor(lcdf1Tst$loan_status, levels=c("Fully Paid", "Charged Off"))
lcdf1Trn$loan_status <-as.factor(lcdf1Trn$loan_status)
lcdf1Tst$loan_status <- as.factor(lcdf1Tst$loan_status)
class(lcdf1Trn$loan_status)
colnames(lcdf1Trn)
lcdf_Trn_c50<- C5.0(x=lcdf1Trn~., data =lcdf1Trn, method="class", parms= list(split='information'))
lcdf_Trn_c50<- C5.0(x=lcdf1Trn, y=lcdf1Trn$loan_status, weights = 100)
str(lcdf_Trn_c50)
levels(lcdf_Trn_c50$)[1] = "missing"
summary(lcdf1Trn)
#Replace rpart function by C5.0 to build the tree
plot(lcdf_Trn_c50,subtree=1)
#Making Predictions
predictions=predict(lcdf_Trn_c50, data = lcdf1Trn, type='class')
#Summarizing the accuracy train
table(predictions, lcdf1Trn$loan_status)
plot(lcdf_Trn_c50)
confusionMatrix( table(predictions, lcdf1Trn$loan_status) )
table(pred = predTrn_whole, true=lcdf1Trn$lcdf1Trn~.)
confusionMatrix( table(predictions_tst, lcdf1Tst$loan_status) )
#Accuracy
mean(predictions==lcdf1Trn$lcdf1Trn~.)
library(ROCR)
#score test
lcdf1Trn$score<-predict(lcdf_Trn_c50,type='prob',lcdf1Tst)
pred <-prediction(lcdf1Trn$score[,2],lcdf1Trn$lcdf1Trn~.)
perf <- performance(pred,"tpr","fpr")
plot(perf, main="ROC Curve")
```
#Modelling Random Forest
```{r}
#Building random forest model
library('randomForest')
#for reproducible results, set a specific value for the random number seed
set.seed(900)
lcdfRF <- lcdf1
levels(lcdfRF$loan_status) <- c(0,1)
#dividing in training n testing
set.seed(1784)
nr<-nrow(lcdfRF)
trnIndex<- sample(1:nr, size = round(0.7*nr), replace=FALSE)
lcdfRF_Trn <- lcdfRF[trnIndex, ]
lcdfRF_Tst <- lcdfRF[-trnIndex, ]
#Developing Model1 with 200 Trees
rfM1 = randomForest(loan_status~., data=lcdfRF_Trn, ntree=200, importance=TRUE )
rfM1
# Predicting on Validation set
PV1 <- predict(rfM1, lcdfRF_Tst, type = "class")
# Looking for classification accuracy for Model 1
Acc1 <- mean(PV1 == lcdfRF_Tst$loan_status)
table(PV1,lcdfRF_Tst$loan_status)
#Developing Model2 with 200 Trees with additional condition
rfM2 = randomForest(loan_status~., data=lcdfRF_Trn, ntree=200, mtry = 6, importance=TRUE )
rfM2
# Predicting on Validation set
PV2 <- predict(rfM2, lcdfRF_Tst, type = "class")
# Looking for classification accuracy for Model 2
Acc2 <- mean(PV2 == lcdf_rf_Tst$loan_status)
table(PV2,lcdfRF_Tst$loan_status)
#Developing Model3 with 100 Trees with additional condition
rfM3 = randomForest(loan_status~., data=lcdfRF_Trn, ntree=100, importance=TRUE )
# Predicting on Validation set
PV3 <- predict(rfM3, lcdfRF_Tst, type = "class")
# Looking for classification accuracy for Model 3
Acc3 <- mean(PV3 == lcdfRF_Tst$loan_status)
table(PV3,lcdfRF_Tst$loan_status)
# To check important variables
importance(rfM1)
varImpPlot(rfM1)
importance(rfM2)
varImpPlot(rfM2)
importance(rfM3)
varImpPlot(rfM3)
#Draw the ROC curve for the randomForest model
perfROC_rfTst=performance(prediction(predict(rfM2,lcdfRF_Tst, type="prob")[,2], lcdfRF_Tst$loan_status), "tpr", "fpr")
plot(perfROC_rfTst)
#Draw the lift curve fr the random forest model
perfLift_rfTst=performance(prediction(predict(rfM2,lcdfRF_Tst, type="prob")[,2], lcdfRF_Tst$loan_status), "lift", "rpp")
plot(perfLift_rfTst)
#ROC curves for the decision-tree model and the random forest model in the same plot
perfROC_dt1Tst=performance(prediction(predict(lcDT1,lcdf1Tst, type="prob")[,2], lcdf1Tst$loan_status), "tpr", "fpr")
perfRoc_rfTst=performance(prediction(predict(rfM3,lcdfRF_Tst, type="prob")[,2], lcdfRF_Tst$loan_status), "tpr", "fpr")
plot(perfROC_dt1Tst, col='red')
plot(perfRoc_rfTst, col='green', add=TRUE)
legend('bottomright', c('DecisionTree', 'RandomForest'), lty=1, col=c('red', 'green'))
```
#Modelling for GBM
```{r}
instlall.packages(gbm)
#Dividing the Training and Testing models
set.seed(8945)
head(lcdf1$loan_status)
levels(lcdf1$loan_status)
dim(lcdf1)
colnames(lcdf1)
#Variable has 1 for Fully Paid and 0 for Charged off
head(unclass(lcdf1$loan_status))
head(unclass(lcdf$loan_status)-1)
lcdfgbm <- lcdf1
nr<-nrow(lcdfgbm)
trnIndex<- sample(1:nr, size = round(0.7*nr), replace=FALSE)
lcdfgbmTrn <- lcdf1[trnIndex, ]
lcdfgbmTst <- lcdf1[-trnIndex, ]
lcdfgbmTrn <- lcdfgbmTrn[,-41]
lcdfgbmTst <- lcdfgbmTst[,-41]
lcdf$annRet <- ((lcdf$total_pymnt -lcdf$funded_amnt)/lcdf$funded_amnt)*(12/36)*100
lcdfgbm1<- gbm(formula = unclass(loan_status)-1 ~ .,data = subset(lcdfgbmTrn, select= -c(annRet)), distribution = "gaussian", n.trees = 4000, interaction.depth = 1, shrinkage = 0.001, cv.folds = 5, n.cores = NULL,verbose = FALSE)
print(lcdfgbm1)
# find index for n trees with minimum CV error
min_MSE <- which.min(lcdfgbm1$cv.error)
min_MSE
#calculating minimum RMSE
sqrt(min(lcdfgbm1$cv.error))
# plot loss function as a result of n trees added to the ensemble
gbm.perf(lcdfgbm1, method = 'cv')
Bestler <- gbm.perf(lcdfgbm1, method='cv')
summary(lcdfgbm1)
summary(lcdfgbm1, method=permutation.test.gbm)
Plot(lcdfgbm1, i="int_rate")
```
```{r}
#Incorporating profits & costs
library(dplyr)
PROFITVAL=100 #profit (on $100) from accurately identifying Fully_paid loans
COSTVAL=-500 # loss (on $100) from incorrectly predicting a Charged_Off loan as Full_paid
scoreTst=predict(lcDT1,lcdf1Tst, type="prob")[,"Fully Paid"]
#Identifying those loans wth high probability for being Fully Paid
prPerf=data.frame(scoreTst)
prPerf=cbind(prPerf, status=lcdf1Tst$loan_status)
#Sorting in descending order of probability (fully_paid)
prPerf=prPerf[order(-scoreTst) ,]
prPerf1=prPerf%>%mutate(profit=ifelse(prPerf$status == 'Fully Paid', PROFITVAL, COSTVAL))
cumProfit=cumsum(prPerf$profit)
#Comparing against the default approach of investing in CD with 2% int (i.e. $6 profit out of $100 in 3 years)
prPerf$cdRet <- 6
na.omit(prPerf)
na.omit(prPerf1)
prPerf$cumCDRet <- cumsum(prPerf$cdRet)
plot(cumProfit)
lines(prPerf1$cumCDRet, col='purple')
#Or, we really do not need to have the cdRet and cumCDRet columns, since cdRet is $6 for every row
plot(prPerf1$cumProfit)
abline(a=0, b=6)
#Finding the score coresponding to the max profit
maxProfit= max(prPerf1$cumProfit)
maxProfit_Ind = which.max(prPerf1$cumProfit)
maxProfit_score = prPerf1$scoreTst[maxProfit_Ind]
print(c(maxProfit = maxProfit, scoreTst = maxProfit_score))
```
```{r}
library(gbm)
#annRet<-((lcdf$total_pymnt -lcdf$funded_amnt)/lcdf$funded_amnt)*(12/36)*100
#actualTerm<-((lcdf$loan_status=="Fully Paid", as.duration(lcdf$issue_d %--% lcdf$last_pymnt_d)/dyears(1), 3))
#actualReturn
#total_pymnt
rfModelGp<-ranger(loan_status~., data=subset(lcdfTrn, select=-c(annRet, actualTerm, actualReturn, total_pymnt)), num.trees=200,importance='permutation')
gbm_M2 <-gbm(formula=unclass(loan_status)-1 ~., data=subset(lcdfTrn, select=-c(annRet, actualTerm, actualReturn)), distribution = "bernoulli", n.trees=2000, shrinkage=0.01, interaction.depth= 4, bag.fraction=0.5, cv.folds= 5, n.cores=16)
bestIter<-gbm.perf(gbm_M2, method='cv')
scores_gbmM2<-predict(gbm_M2, newdata=lcdfTst, n.tree= bestIter, type="response") pred_gbmM2=prediction(scores_gbmM2, lcdfTst$loan_status, label.ordering= c("Charged Off", "Fully Paid"))
#label.orderinghere specifies the 'negative', 'positive' class labels
aucPerf_gbmM2 <-performance(pred_gbmM2, "tpr", "fpr")
plot(aucPerf_gbmM2)
abline(a=0, b= 1)
rfModelGp<-ranger(loan_status~., data=subset(lcdfTrn, select=-c(annRet, actualTerm, actualReturn, total_pymnt)), num.trees=200, importance='permutation')
scoreTstRF<-predict(rfModel1,lcdfTst, type="prob")[,"Fully Paid"]
predRF=prediction(scoreTstRF, lcdfTst$loan_status, label.ordering= c("Charged Off", "Fully Paid"))
aucPerfRF<-performance(predRF, "tpr", "fpr")
plot(aucPref_gbmM2, col='red', add=TRUE)
legend('bottomright', c('RandomForest', 'gbm'), lty=1, col=c('black', 'red'))
```
|
# _________________________________________________________________________
#### Data handling ####
# _________________________________________________________________________
# loads data from input directory, stores them in a list
# and assigns a name (filename)
load_data <- function(path, pattern){
files <- list.files(path = path, pattern = pattern)
data <- lapply(files, function(y) readRDS(file = file.path(path, y)))
data <- setNames(data, files)
data
}
# Helper function for dcast calls
# Add to fun.aggregate argument for assigning a 1 to casted values when there length
# is greater than 0
fun_binary_length <- function(y) {
as.numeric(ifelse(length(y) == 0, 0, 1))
}
# In case for subsetting (currently only for one variable can be subsetted)
subset_trait_data <- function(data, trait, trait_value){
data <- data[get(trait) == trait_value, ]
data
}
# check if columnNR of elements in a list is the same
check_columnNr <- function(x){
ck <- lapply(x, length) %>% unlist()
if(abs(max(ck) - min(ck)) == 0){
print("Files have the same number of columns")
}
}
# check if colnames of data.frames stored in a list are the same
# TODO: Improve output, but message when colnames differ
check_colNames <- function(x) {
col_names_first_element <- lapply(x, names)[[1]]
lapply(x, function(y) {
all(names(y) %in% col_names_first_element)
})
}
# create individual pattern of trait name (not category!)
# i.e. feed_herbivore, feed_shredder -> feed
create_pattern_ind <- function(x, non_trait_cols) {
if (missing(non_trait_cols)) {
trait_names_pattern <- sub("\\_.*|\\..*", "", names(x)) %>%
unigooque() %>%
paste0("^", .)
} else{
pat <- paste0(non_trait_cols, collapse = "|")
# get trait names & create pattern for subset
trait_names_pattern <-
grep(pat, names(x), value = TRUE, invert = TRUE) %>%
sub("\\_.*|\\..*", "", .) %>%
unique() %>%
paste0("^", .)
}
trait_names_pattern
}
# check for completeness of trait datasets
completeness_trait_data <- function(x, non_trait_cols) {
trait_names_pattern <- create_pattern_ind(
x = x,
non_trait_cols = non_trait_cols
)
# test how complete trait sets are
output <- matrix(ncol = 2, nrow = length(trait_names_pattern))
for (i in seq_along(trait_names_pattern)) {
# vector containing either 0 (no NAs) or a number (> 0) meaning that all
# entries for this trait contained NA
vec <-
x[, apply(.SD, 1, function(y) {
base::sum(is.na(y))
}),
.SDcols = names(x) %like% trait_names_pattern[[i]]
]
# How complete is the dataset for each individual trait?
output[i, ] <-
c(
(length(vec[vec == 0]) / nrow(x)) %>%
`*`(100) %>%
round(),
trait_names_pattern[[i]]
)
}
return(as.data.frame(output))
}
# Normalization of trait scores
# All trait states of one trait are divided by their row sum
# Hence, trait affinities are represented as "%" or ratios
normalize_by_rowSum <- function(x,
non_trait_cols,
na.rm = TRUE) {
# get trait names & create pattern for subset
trait_names_pattern <- create_pattern_ind(x = x,
non_trait_cols = non_trait_cols)
# loop for normalization (trait categories for each trait sum up to 1)
for (cols in trait_names_pattern) {
# get row sum for a specific trait
x[, rowSum := apply(.SD, 1, sum, na.rm = na.rm),
.SDcols = names(x) %like% cols]
# get column names for assignment
col_name <- names(x)[names(x) %like% cols]
# divide values for each trait state by
# the sum of trait state values
x[, (col_name) := lapply(.SD, function(y) {
y / rowSum
}),
.SDcols = names(x) %like% cols]
}
# del rowSum column
x[, rowSum := NULL]
return(x)
}
# _________________________________________________________________________
#### Data extraction ####
# _________________________________________________________________________
# Helper FUN: most important traits to distinguish TPGs
extract_vi <- function(data) {
lapply(data, function(y)
y$rf_permutation$variable.importance) %>%
lapply(., function(y)
names(y[order(-y)])[1:5])
}
# Helper FUN: change in prediction error
extract_test_error <- function(data) {
lapply(data, function(y)
y$pred_test$overall[["Accuracy"]]) %>%
unlist()
}
# Helper FUN: change in training error
extract_train_error <- function(data) {
lapply(data, function(y)
y$pred_train$overall[["Accuracy"]]) %>%
unlist()
}
# __________________________________________________________________________________________________
#### Clustering ####
# __________________________________________________________________________________________________
mycluster_hc <- function(x, k) {
list(cluster = cutree(hclust(as.dist(x),
method = "ward.D2"),
k = k))
}
# __________________________________________________________________________________________________
#### RF Analysis ####
# __________________________________________________________________________________________________
# Custom prediction function
custom_pred <- function(object, newdata) {
pred <- predict(object, newdata)$predictions
avg <- purrr::map_df(as.data.frame(pred), mean)
return(avg)
}
# Meta rf function with hyperparameter tuning
# old, now with mlr3
meta_rf <- function(train,
test) {
# Number of features
n_features <- length(setdiff(names(train), "group"))
# Grid for different hyperparameters
hyper_grid <- expand.grid(
mtry = c(1, 5, 10, 15, 20, n_features - 1),
node_size = seq(1, 10, by = 3),
sample_size = c(.632, .80),
num_trees = 100,
OOB_error = NA,
rmse = NA
)
# RF
for (j in seq_len(nrow(hyper_grid))) {
# train model
model <- ranger(
formula = group ~ .,
data = train,
seed = 123,
verbose = FALSE,
num.trees = hyper_grid$num_trees[[j]],
mtry = hyper_grid$mtry[j],
min.node.size = hyper_grid$node_size[j],
sample.fraction = hyper_grid$sample_size[j]
)
# add OOB error to grid
hyper_grid$OOB_error[j] <- model$prediction.error
}
# Feature importance
# Use best tuning parameters
best_set <- hyper_grid[order(hyper_grid$OOB_error), ][1, ]
# Re-run model with impurity-based variable importance
m3_ranger_impurity <- ranger(
formula = group ~ .,
data = train,
num.trees = best_set$num_trees,
mtry = best_set$mtry,
min.node.size = best_set$node_size,
sample.fraction = best_set$sample_size,
importance = "impurity",
verbose = FALSE,
seed = 123
)
# Re-run model with permutation-based variable importance
m3_ranger_permutation <- ranger(
formula = group ~ .,
data = train,
num.trees = best_set$num_trees,
mtry = best_set$mtry,
min.node.size = best_set$node_size,
sample.fraction = best_set$sample_size,
importance = "permutation",
verbose = FALSE,
seed = 123
)
# Predictions
# Training data
res_train <- predict(m3_ranger_impurity, train)
pred_train <- confusionMatrix(res_train$predictions, train$group)
# Test data
res_test <- predict(m3_ranger_impurity, test)
u <- union(res_test$predictions, test$group)
tab <- table(
factor(res_test$predictions, u),
factor(test$group, u)
)
pred_test <- confusionMatrix(tab)
list(
"rf_impurity" = m3_ranger_impurity,
"rf_permutation" = m3_ranger_permutation,
"pred_train" = pred_train,
"pred_test" = pred_test)
}
# __________________________________________________________________________________________________
### Multivariate Welch-Test ####
# https://github.com/alekseyenko/WdStar
# __________________________________________________________________________________________________
dist.ss2 = function(dm2, f){ #dm2 is matrix of square distances; f factor
K = sapply(levels(f), function(lev) f==lev)
t(K)%*%dm2%*%K/2
}
generic.distance.permutation.test <-
function(test.statistic,
dm,
f,
nrep = 999,
strata = NULL) {
N = length(f)
generate.permutation = function() {
f[sample(N)]
}
if (!is.null(strata)) {
# map elements of each strata back to their positions in the factor variable
strata.map = order(unlist(tapply(seq_along(f), strata, identity)))
generate.permutation = function() {
p = unlist(tapply(f, strata, sample)) # permute within strata
p[strata.map]
}
}
stats = c(test.statistic(dm, f),
replicate(nrep,
test.statistic(dm, generate.permutation())))
p.value = sum(stats >= stats[1]) / (nrep + 1)
statistic = stats[1]
list(p.value = p.value,
statistic = statistic,
nrep = nrep)
}
WdS <- function(dm, f) {
# This method computes Wd* statistic for distance matrix dm and factor f
ns = table(f)
SS2 = dist.ss2(as.matrix(dm) ^ 2, f)
s2 = diag(SS2) / ns / (ns - 1)
W = sum(ns / s2)
idxs = apply(combn(levels(f), 2), 2, function(idx)
levels(f) %in% idx)
Ws = sum(apply(idxs, 2,
function(idx)
sum(ns[idx]) / prod(s2[idx]) *
(sum(SS2[idx, idx]) / sum(ns[idx]) - sum(diag(
SS2[idx, idx]
) / ns[idx]))))
k = nlevels(f)
h = sum((1 - ns / s2 / W) ^ 2 / (ns - 1))
Ws / W / (k - 1) / (1 + (2 * (k - 2) / (k ^ 2 - 1)) * h)
}
WdS.test <- function(dm, f, nrep = 999, strata = NULL) {
generic.distance.permutation.test(
WdS,
dm = dm,
f = f,
nrep = nrep,
strata = strata
)
}
# _________________________________________________________________________
#### Plotting ####
# _________________________________________________________________________
##### Dendrogram plot ####
fun_dendrog_pl <- function(hc,
optimal_nog,
labels,
hang_height = 0.001) {
hc %>%
as.dendrogram() %>%
color_branches(k = optimal_nog) %>%
hang.dendrogram(hang_height = hang_height) %>%
set("labels_cex", 0.7) %>%
dendextend::ladderize() %>%
set("labels", labels)
}
##### Heatmap plot ####
# Create heatmap with ggplot for TPGs and Grouping features for each continent
# Columns of data are hardcoded, maybe change in the future
fun_heatmap_single_cont <- function(data) {
ggplot(data, aes(x = family,
y = trait,
fill = affinity)) +
geom_tile() +
facet_grid(
factor(grouping_feature) ~ group,
scales = "free",
space = "free",
labeller = as_labeller(grouping_feature_names)
) +
scale_fill_gradient(name = "Trait affinity",
low = "#FFFFF1",
high = "#012345") +
labs(x = "Family", y = "Trait") +
theme_bw() +
theme(
axis.title = element_text(size = 22),
axis.text.x = element_text(
family = "Roboto Mono",
size = 16,
angle = 90,
hjust = 1,
vjust = 0.2
),
axis.text.y = element_text(family = "Roboto Mono",
size = 16),
legend.title = element_text(family = "Roboto Mono",
size = 16),
legend.text = element_text(family = "Roboto Mono",
size = 16),
strip.text = element_text(family = "Roboto Mono",
size = 16),
plot.title = element_text(family = "Roboto Mono",
size = 20),
panel.grid = element_blank()
)
}
# Plotting function for tpg that occur across the tested continents
fun_heatmap_tpg <- function(data,
facet_names) {
ggplot(data, aes(x = family,
y = trait,
fill = affinity)) +
geom_tile() +
facet_grid(
. ~ continent,
scales = "free",
space = "free",
labeller = as_labeller(facet_names)
) +
scale_fill_gradient(name = "Trait affinity",
low = "#FFFFF1",
high = "#012345") +
labs(x = "Family", y = "Trait") +
theme_bw() +
theme(
axis.title = element_text(size = 20),
axis.text.x = element_text(
family = "Roboto Mono",
size = 16,
angle = 90,
hjust = 1,
vjust = 0.2
),
axis.text.y = element_text(family = "Roboto Mono",
size = 16),
legend.title = element_text(family = "Roboto Mono",
size = 16),
legend.text = element_text(family = "Roboto Mono",
size = 16),
strip.text = element_text(family = "Roboto Mono",
size = 15),
plot.title = element_text(family = "Roboto Mono",
size = 16),
panel.grid = element_blank()
)
}
##### Helper function to plot boruta results ####
# Does require data.table
# Takes as input a result from attStats() on an object created by boruta()
fun_boruta_results <- function(data) {
data$traits <- rownames(data)
setDT(data)
data[, traits := reorder(traits, meanImp)]
data[, decision := factor(decision, levels = c("Confirmed", "Tentative", "Rejected"))]
ggplot(data,
aes(
x = as.factor(traits),
y = meanImp,
color = decision
)) +
geom_point(size = 2.5) +
scale_color_brewer(palette = "Dark2") +
labs(x = "Traits", y = "Mean permutation importance score",
color = "Decision") +
theme_bw() +
theme(
axis.title = element_text(size = 16),
axis.text.x = element_text(
family = "Roboto Mono",
size = 14,
angle = 45,
hjust = 1
),
axis.text.y = element_text(family = "Roboto Mono",
size = 14),
legend.title = element_text(family = "Roboto Mono",
size = 16),
legend.text = element_text(family = "Roboto Mono",
size = 14),
strip.text = element_text(family = "Roboto Mono",
size = 14),
plot.title = element_text(family = "Roboto Mono",
size = 16),
panel.grid = element_blank()
)
}
# __________________________________________________________________________________________________
#### Trait aggregation ####
# __________________________________________________________________________________________________
# Direct aggregation to specified taxonomic level
direct_agg <- function(trait_data,
non_trait_cols,
method,
taxon_lvl,
na.rm = TRUE) {
# get names of trait columns
pat <- paste0(non_trait_cols, collapse = "|")
trait_col <- grep(pat, names(trait_data), value = TRUE, invert = TRUE)
# aggregate to specified taxon lvl
# Before applying this function, subset that no NA values occur in data
# (otherwise all NA entries are viewed as a group & aggregated as well)
agg_data <- trait_data[,
lapply(.SD, method, na.rm = na.rm),
.SDcols = trait_col,
by = taxon_lvl
]
agg_data
}
# __________________________________________________________________________________________________
#### Null Models ####
# __________________________________________________________________________________________________
# Calculate pcoa for simulated datasets
# id column should be created before
calc_pcoa <-
function(x,
traits = c("feed", "resp", "volt", "locom", "size", "bf")) {
trait_patterns <- paste0(traits, collapse = ".*|")
x <- x[, .SD, .SDcols = patterns(paste0(trait_patterns, "|id"))]
setDF(x)
taxa_reg_names <- x$id
row.names(x) <- taxa_reg_names
x$id <- NULL
# Konvert to ktab object
vec <- sub("\\_.*", "\\1", names(x))
blocks <- rle(vec)$lengths
x <- prep.fuzzy(x, blocks)
x <- ktab.list.df(list(x))
dist <- dist.ktab(x, type = "F")
# PcOA
pcoa <- dudi.pco(dist, scannf = FALSE, nf = 25)
}
# Transform pcoa element obtained from "calc_pcoa" into a data.table
transf_pcoa_dt <- function(pcoa_obj){
pcoa_scores <- pcoa_obj$li[1:2]
pcoa_scores$id <- rownames(pcoa_scores)
setDT(pcoa_scores)
}
# Calculate convex hull for first two PCoA axes
# and subsequently overlap between the continents/regions
calc_cnx_hull <- function(scores) {
hull <- scores %>%
group_by(continent) %>%
slice(chull(A1, A2))
setDT(hull)
hull_split <- split(hull[, .(A1, A2)], f = hull$continent)
list(
"Overlap" = Overlap(hull_split),
"Overlap_symmetric" = Overlap(hull_split, symmetric = TRUE)
)
}
# Calculate ellipses for first two PCoA axes
# Maximum likelihood approach
calc_ellipses <- function(scores,
ellipses = c("1.AUS",
"1.EU",
"1.NOA",
"1.NZ",
"1.SA")) {
# we just have one community
pcoa_siber <- createSiberObject(scores[, .(
iso1 = A1,
iso2 = A2,
group = continent,
community = 1
)])
# Calculate all possible permutations of ellipses
perm_ellipses <- gtools::permutations(n = 5,
r = 2,
v = ellipses)
perm_ellipses <- as.data.frame(perm_ellipses)
rownames(perm_ellipses) <- paste0(perm_ellipses$V1,
"_",
perm_ellipses$V2)
# Calc overlap
ellipse95_overlap <- list()
for (i in 1:nrow(perm_ellipses)) {
ellipse95_overlap[[i]] <- maxLikOverlap(
perm_ellipses[i, "V1"],
perm_ellipses[i, "V2"],
pcoa_siber,
p.interval = 0.95,
n = 100
)
}
names(ellipse95_overlap) <- rownames(perm_ellipses)
ellipse95_overlap
}
# Hierarchical clustering & optimal number of groups
# method is ward.D2
# uses funciton mycluster_hc
calc_clustering <-
function(x,
traits = c("feed", "resp", "volt", "locom", "size", "bf")) {
trait_patterns <- paste0(traits, collapse = ".*|")
x <- x[, .SD, .SDcols = patterns(paste0(trait_patterns, "|id"))]
setDF(x)
taxa_reg_names <- x$id
row.names(x) <- taxa_reg_names
x$id <- NULL
# Konvert to ktab object
vec <- sub("\\_.*", "\\1", names(x))
blocks <- rle(vec)$lengths
x <- prep.fuzzy(x, blocks)
x <- ktab.list.df(list(x))
dist <- dist.ktab(x, type = "F")
# HC & optimal number of clusters
hc <- hclust(dist, method = "ward.D2")
dend <- as.dendrogram(hc)
gap <- clusGap(
x = as.matrix(dist),
FUN = mycluster_hc,
K.max = 15,
B = 500
)
optimal_nog <- maxSE(gap$Tab[, "gap"],
gap$Tab[, "SE.sim"],
method = "Tibs2001SEmax")
list("hc" = hc,
"dend" = dend,
"optimal_nog" = optimal_nog)
}
# Add TPGs to simulated datasets
add_tpgs_td <- function(cl_obj) {
results <- list()
for (i in names(cl_obj)) {
results[[i]] <-
data.table(
family = names(
cutree(
cl_obj[[i]]$dend,
k = cl_obj[[i]]$optimal_nog,
order_clusters_as_data = FALSE
)
),
group = cutree(
cl_obj[[i]]$dend,
k = cl_obj[[i]]$optimal_nog,
order_clusters_as_data = FALSE
)
)
}
results <- rbindlist(results, idcol = "continent")
}
# Calculate dbrda for mean trait profiles
calc_dbrda <-
function(t_data,
traits = c("feed", "resp", "volt", "locom", "size", "bf")) {
trait_patterns <- paste0(traits, collapse = ".*|")
x <- t_data[, .SD, .SDcols = patterns(paste0(trait_patterns, "|id"))]
setDF(x)
taxa_reg_names <- x$id
row.names(x) <- taxa_reg_names
x$id <- NULL
# Convert to ktab object
vec <- sub("\\_.*", "\\1", names(x))
blocks <- rle(vec)$lengths
x <- prep.fuzzy(x, blocks)
x <- ktab.list.df(list(x))
dist <- dist.ktab(x, type = "F")
# dbrda with continents
dbrda_res <- dbrda(formula = dist ~ continent, data = t_data)
dbrda_res <- summary(dbrda_res)
expl_var <- dbrda_res$constr.chi / dbrda_res$tot.chi
}
# RF with tpgs as dependent variable
calc_rf_tpgs <- function(x,
traits = c("feed", "resp", "volt", "locom", "size", "bf")) {
most_imp_vars <- list()
# ls_instance <- list()
# scores_test <- list()
# scores_train <- list()
trait_pat <- paste0(traits, collapse = ".*|")
for (cont in unique(x$continent)) {
set.seed(1234)
dat <- x[continent == cont, ]
dat <-
dat[, .SD, .SDcols = patterns(paste0(trait_pat, "|group"))]
# Split in train and test data (stratified)
ind <- createDataPartition(dat$group, p = 0.7)
train <- dat[ind[[1]],]
test <- dat[-ind[[1]],]
# Create tasks
task_train <- TaskClassif$new(
id = paste0(cont, "_train"),
backend = train,
target = "group"
)
# Specify stratification for CV
task_train$col_roles$stratum <- "group"
# Create random forest learner
# list of possible learners: mlr3learners
rf_learner <- lrn("classif.ranger",
predict_type = "prob",
importance = "permutation")
# Set up search space
# rf_learner$param_set
search_space <- ps(
mtry = p_int(lower = 1, upper = length(task_train$data()) - 1),
min.node.size = p_int(lower = 1, upper = 10)#,
# sample.fraction = p_dbl(lower = 0.632, upper = 0.8)
)
# Resampling
resampling <- rsmp("cv",
folds = 5L)
# Performance measure for resampling (multivariate Brier score)
mbrier_metric <- mlr3::msr("classif.mbrier")
# When to terminate tuning
evals <- trm("evals", n_evals = 100)
instance = TuningInstanceSingleCrit$new(
task = task_train,
learner = rf_learner,
resampling = resampling,
measure = mbrier_metric,
search_space = search_space,
terminator = evals
)
# Optimization via grid search
tuner <- tnr("grid_search", resolution = 10)
tuner$optimize(instance)
# ls_instance[[cont]] <- instance
# Train rf on train dataset with optimized parameters
rf_learner$param_set$values <-
instance$result_learner_param_vals
rf_learner$train(task_train)
pred_train <- rf_learner$predict_newdata(newdata = train)
# scores_train[[cont]] <- pred_train$score(mlr3::msr("classif.mbrier"))
# Check model on test dataset
pred_test <- rf_learner$predict_newdata(newdata = test)
# scores_test[[cont]] <- pred_test$score(mlr3::msr("classif.mbrier"))
# Retrieve most important variables
most_imp_vars[[cont]] <- rf_learner$importance()
}
list("most_imp_vars" = most_imp_vars)
}
# Functions for distance calculations ----
## Overlap index manly ----
fun_overlap_ind <-
function(p, q) {
1 - sum(p * q) / sqrt(sum(p * p)) / sqrt(sum(q * q))
}
| /R/functions_used.R | no_license | KunzstLD/Convergence-trait-profiles | R | false | false | 23,608 | r | # _________________________________________________________________________
#### Data handling ####
# _________________________________________________________________________
# loads data from input directory, stores them in a list
# and assigns a name (filename)
load_data <- function(path, pattern){
files <- list.files(path = path, pattern = pattern)
data <- lapply(files, function(y) readRDS(file = file.path(path, y)))
data <- setNames(data, files)
data
}
# Helper function for dcast calls
# Add to fun.aggregate argument for assigning a 1 to casted values when there length
# is greater than 0
fun_binary_length <- function(y) {
as.numeric(ifelse(length(y) == 0, 0, 1))
}
# In case for subsetting (currently only for one variable can be subsetted)
subset_trait_data <- function(data, trait, trait_value){
data <- data[get(trait) == trait_value, ]
data
}
# check if columnNR of elements in a list is the same
check_columnNr <- function(x){
ck <- lapply(x, length) %>% unlist()
if(abs(max(ck) - min(ck)) == 0){
print("Files have the same number of columns")
}
}
# check if colnames of data.frames stored in a list are the same
# TODO: Improve output, but message when colnames differ
check_colNames <- function(x) {
col_names_first_element <- lapply(x, names)[[1]]
lapply(x, function(y) {
all(names(y) %in% col_names_first_element)
})
}
# create individual pattern of trait name (not category!)
# i.e. feed_herbivore, feed_shredder -> feed
create_pattern_ind <- function(x, non_trait_cols) {
if (missing(non_trait_cols)) {
trait_names_pattern <- sub("\\_.*|\\..*", "", names(x)) %>%
unigooque() %>%
paste0("^", .)
} else{
pat <- paste0(non_trait_cols, collapse = "|")
# get trait names & create pattern for subset
trait_names_pattern <-
grep(pat, names(x), value = TRUE, invert = TRUE) %>%
sub("\\_.*|\\..*", "", .) %>%
unique() %>%
paste0("^", .)
}
trait_names_pattern
}
# check for completeness of trait datasets
completeness_trait_data <- function(x, non_trait_cols) {
trait_names_pattern <- create_pattern_ind(
x = x,
non_trait_cols = non_trait_cols
)
# test how complete trait sets are
output <- matrix(ncol = 2, nrow = length(trait_names_pattern))
for (i in seq_along(trait_names_pattern)) {
# vector containing either 0 (no NAs) or a number (> 0) meaning that all
# entries for this trait contained NA
vec <-
x[, apply(.SD, 1, function(y) {
base::sum(is.na(y))
}),
.SDcols = names(x) %like% trait_names_pattern[[i]]
]
# How complete is the dataset for each individual trait?
output[i, ] <-
c(
(length(vec[vec == 0]) / nrow(x)) %>%
`*`(100) %>%
round(),
trait_names_pattern[[i]]
)
}
return(as.data.frame(output))
}
# Normalization of trait scores
# All trait states of one trait are divided by their row sum
# Hence, trait affinities are represented as "%" or ratios
normalize_by_rowSum <- function(x,
non_trait_cols,
na.rm = TRUE) {
# get trait names & create pattern for subset
trait_names_pattern <- create_pattern_ind(x = x,
non_trait_cols = non_trait_cols)
# loop for normalization (trait categories for each trait sum up to 1)
for (cols in trait_names_pattern) {
# get row sum for a specific trait
x[, rowSum := apply(.SD, 1, sum, na.rm = na.rm),
.SDcols = names(x) %like% cols]
# get column names for assignment
col_name <- names(x)[names(x) %like% cols]
# divide values for each trait state by
# the sum of trait state values
x[, (col_name) := lapply(.SD, function(y) {
y / rowSum
}),
.SDcols = names(x) %like% cols]
}
# del rowSum column
x[, rowSum := NULL]
return(x)
}
# _________________________________________________________________________
#### Data extraction ####
# _________________________________________________________________________
# Helper FUN: most important traits to distinguish TPGs
extract_vi <- function(data) {
lapply(data, function(y)
y$rf_permutation$variable.importance) %>%
lapply(., function(y)
names(y[order(-y)])[1:5])
}
# Helper FUN: change in prediction error
extract_test_error <- function(data) {
lapply(data, function(y)
y$pred_test$overall[["Accuracy"]]) %>%
unlist()
}
# Helper FUN: change in training error
extract_train_error <- function(data) {
lapply(data, function(y)
y$pred_train$overall[["Accuracy"]]) %>%
unlist()
}
# __________________________________________________________________________________________________
#### Clustering ####
# __________________________________________________________________________________________________
mycluster_hc <- function(x, k) {
list(cluster = cutree(hclust(as.dist(x),
method = "ward.D2"),
k = k))
}
# __________________________________________________________________________________________________
#### RF Analysis ####
# __________________________________________________________________________________________________
# Custom prediction function
custom_pred <- function(object, newdata) {
pred <- predict(object, newdata)$predictions
avg <- purrr::map_df(as.data.frame(pred), mean)
return(avg)
}
# Meta rf function with hyperparameter tuning
# old, now with mlr3
meta_rf <- function(train,
test) {
# Number of features
n_features <- length(setdiff(names(train), "group"))
# Grid for different hyperparameters
hyper_grid <- expand.grid(
mtry = c(1, 5, 10, 15, 20, n_features - 1),
node_size = seq(1, 10, by = 3),
sample_size = c(.632, .80),
num_trees = 100,
OOB_error = NA,
rmse = NA
)
# RF
for (j in seq_len(nrow(hyper_grid))) {
# train model
model <- ranger(
formula = group ~ .,
data = train,
seed = 123,
verbose = FALSE,
num.trees = hyper_grid$num_trees[[j]],
mtry = hyper_grid$mtry[j],
min.node.size = hyper_grid$node_size[j],
sample.fraction = hyper_grid$sample_size[j]
)
# add OOB error to grid
hyper_grid$OOB_error[j] <- model$prediction.error
}
# Feature importance
# Use best tuning parameters
best_set <- hyper_grid[order(hyper_grid$OOB_error), ][1, ]
# Re-run model with impurity-based variable importance
m3_ranger_impurity <- ranger(
formula = group ~ .,
data = train,
num.trees = best_set$num_trees,
mtry = best_set$mtry,
min.node.size = best_set$node_size,
sample.fraction = best_set$sample_size,
importance = "impurity",
verbose = FALSE,
seed = 123
)
# Re-run model with permutation-based variable importance
m3_ranger_permutation <- ranger(
formula = group ~ .,
data = train,
num.trees = best_set$num_trees,
mtry = best_set$mtry,
min.node.size = best_set$node_size,
sample.fraction = best_set$sample_size,
importance = "permutation",
verbose = FALSE,
seed = 123
)
# Predictions
# Training data
res_train <- predict(m3_ranger_impurity, train)
pred_train <- confusionMatrix(res_train$predictions, train$group)
# Test data
res_test <- predict(m3_ranger_impurity, test)
u <- union(res_test$predictions, test$group)
tab <- table(
factor(res_test$predictions, u),
factor(test$group, u)
)
pred_test <- confusionMatrix(tab)
list(
"rf_impurity" = m3_ranger_impurity,
"rf_permutation" = m3_ranger_permutation,
"pred_train" = pred_train,
"pred_test" = pred_test)
}
# __________________________________________________________________________________________________
### Multivariate Welch-Test ####
# https://github.com/alekseyenko/WdStar
# __________________________________________________________________________________________________
dist.ss2 = function(dm2, f){ #dm2 is matrix of square distances; f factor
K = sapply(levels(f), function(lev) f==lev)
t(K)%*%dm2%*%K/2
}
generic.distance.permutation.test <-
function(test.statistic,
dm,
f,
nrep = 999,
strata = NULL) {
N = length(f)
generate.permutation = function() {
f[sample(N)]
}
if (!is.null(strata)) {
# map elements of each strata back to their positions in the factor variable
strata.map = order(unlist(tapply(seq_along(f), strata, identity)))
generate.permutation = function() {
p = unlist(tapply(f, strata, sample)) # permute within strata
p[strata.map]
}
}
stats = c(test.statistic(dm, f),
replicate(nrep,
test.statistic(dm, generate.permutation())))
p.value = sum(stats >= stats[1]) / (nrep + 1)
statistic = stats[1]
list(p.value = p.value,
statistic = statistic,
nrep = nrep)
}
WdS <- function(dm, f) {
# This method computes Wd* statistic for distance matrix dm and factor f
ns = table(f)
SS2 = dist.ss2(as.matrix(dm) ^ 2, f)
s2 = diag(SS2) / ns / (ns - 1)
W = sum(ns / s2)
idxs = apply(combn(levels(f), 2), 2, function(idx)
levels(f) %in% idx)
Ws = sum(apply(idxs, 2,
function(idx)
sum(ns[idx]) / prod(s2[idx]) *
(sum(SS2[idx, idx]) / sum(ns[idx]) - sum(diag(
SS2[idx, idx]
) / ns[idx]))))
k = nlevels(f)
h = sum((1 - ns / s2 / W) ^ 2 / (ns - 1))
Ws / W / (k - 1) / (1 + (2 * (k - 2) / (k ^ 2 - 1)) * h)
}
WdS.test <- function(dm, f, nrep = 999, strata = NULL) {
generic.distance.permutation.test(
WdS,
dm = dm,
f = f,
nrep = nrep,
strata = strata
)
}
# _________________________________________________________________________
#### Plotting ####
# _________________________________________________________________________
##### Dendrogram plot ####
fun_dendrog_pl <- function(hc,
optimal_nog,
labels,
hang_height = 0.001) {
hc %>%
as.dendrogram() %>%
color_branches(k = optimal_nog) %>%
hang.dendrogram(hang_height = hang_height) %>%
set("labels_cex", 0.7) %>%
dendextend::ladderize() %>%
set("labels", labels)
}
##### Heatmap plot ####
# Create heatmap with ggplot for TPGs and Grouping features for each continent
# Columns of data are hardcoded, maybe change in the future
fun_heatmap_single_cont <- function(data) {
ggplot(data, aes(x = family,
y = trait,
fill = affinity)) +
geom_tile() +
facet_grid(
factor(grouping_feature) ~ group,
scales = "free",
space = "free",
labeller = as_labeller(grouping_feature_names)
) +
scale_fill_gradient(name = "Trait affinity",
low = "#FFFFF1",
high = "#012345") +
labs(x = "Family", y = "Trait") +
theme_bw() +
theme(
axis.title = element_text(size = 22),
axis.text.x = element_text(
family = "Roboto Mono",
size = 16,
angle = 90,
hjust = 1,
vjust = 0.2
),
axis.text.y = element_text(family = "Roboto Mono",
size = 16),
legend.title = element_text(family = "Roboto Mono",
size = 16),
legend.text = element_text(family = "Roboto Mono",
size = 16),
strip.text = element_text(family = "Roboto Mono",
size = 16),
plot.title = element_text(family = "Roboto Mono",
size = 20),
panel.grid = element_blank()
)
}
# Plotting function for tpg that occur across the tested continents
fun_heatmap_tpg <- function(data,
facet_names) {
ggplot(data, aes(x = family,
y = trait,
fill = affinity)) +
geom_tile() +
facet_grid(
. ~ continent,
scales = "free",
space = "free",
labeller = as_labeller(facet_names)
) +
scale_fill_gradient(name = "Trait affinity",
low = "#FFFFF1",
high = "#012345") +
labs(x = "Family", y = "Trait") +
theme_bw() +
theme(
axis.title = element_text(size = 20),
axis.text.x = element_text(
family = "Roboto Mono",
size = 16,
angle = 90,
hjust = 1,
vjust = 0.2
),
axis.text.y = element_text(family = "Roboto Mono",
size = 16),
legend.title = element_text(family = "Roboto Mono",
size = 16),
legend.text = element_text(family = "Roboto Mono",
size = 16),
strip.text = element_text(family = "Roboto Mono",
size = 15),
plot.title = element_text(family = "Roboto Mono",
size = 16),
panel.grid = element_blank()
)
}
##### Helper function to plot boruta results ####
# Does require data.table
# Takes as input a result from attStats() on an object created by boruta()
fun_boruta_results <- function(data) {
data$traits <- rownames(data)
setDT(data)
data[, traits := reorder(traits, meanImp)]
data[, decision := factor(decision, levels = c("Confirmed", "Tentative", "Rejected"))]
ggplot(data,
aes(
x = as.factor(traits),
y = meanImp,
color = decision
)) +
geom_point(size = 2.5) +
scale_color_brewer(palette = "Dark2") +
labs(x = "Traits", y = "Mean permutation importance score",
color = "Decision") +
theme_bw() +
theme(
axis.title = element_text(size = 16),
axis.text.x = element_text(
family = "Roboto Mono",
size = 14,
angle = 45,
hjust = 1
),
axis.text.y = element_text(family = "Roboto Mono",
size = 14),
legend.title = element_text(family = "Roboto Mono",
size = 16),
legend.text = element_text(family = "Roboto Mono",
size = 14),
strip.text = element_text(family = "Roboto Mono",
size = 14),
plot.title = element_text(family = "Roboto Mono",
size = 16),
panel.grid = element_blank()
)
}
# __________________________________________________________________________________________________
#### Trait aggregation ####
# __________________________________________________________________________________________________
# Direct aggregation to specified taxonomic level
direct_agg <- function(trait_data,
non_trait_cols,
method,
taxon_lvl,
na.rm = TRUE) {
# get names of trait columns
pat <- paste0(non_trait_cols, collapse = "|")
trait_col <- grep(pat, names(trait_data), value = TRUE, invert = TRUE)
# aggregate to specified taxon lvl
# Before applying this function, subset that no NA values occur in data
# (otherwise all NA entries are viewed as a group & aggregated as well)
agg_data <- trait_data[,
lapply(.SD, method, na.rm = na.rm),
.SDcols = trait_col,
by = taxon_lvl
]
agg_data
}
# __________________________________________________________________________________________________
#### Null Models ####
# __________________________________________________________________________________________________
# Calculate pcoa for simulated datasets
# id column should be created before
calc_pcoa <-
function(x,
traits = c("feed", "resp", "volt", "locom", "size", "bf")) {
trait_patterns <- paste0(traits, collapse = ".*|")
x <- x[, .SD, .SDcols = patterns(paste0(trait_patterns, "|id"))]
setDF(x)
taxa_reg_names <- x$id
row.names(x) <- taxa_reg_names
x$id <- NULL
# Konvert to ktab object
vec <- sub("\\_.*", "\\1", names(x))
blocks <- rle(vec)$lengths
x <- prep.fuzzy(x, blocks)
x <- ktab.list.df(list(x))
dist <- dist.ktab(x, type = "F")
# PcOA
pcoa <- dudi.pco(dist, scannf = FALSE, nf = 25)
}
# Transform pcoa element obtained from "calc_pcoa" into a data.table
transf_pcoa_dt <- function(pcoa_obj){
pcoa_scores <- pcoa_obj$li[1:2]
pcoa_scores$id <- rownames(pcoa_scores)
setDT(pcoa_scores)
}
# Calculate convex hull for first two PCoA axes
# and subsequently overlap between the continents/regions
calc_cnx_hull <- function(scores) {
hull <- scores %>%
group_by(continent) %>%
slice(chull(A1, A2))
setDT(hull)
hull_split <- split(hull[, .(A1, A2)], f = hull$continent)
list(
"Overlap" = Overlap(hull_split),
"Overlap_symmetric" = Overlap(hull_split, symmetric = TRUE)
)
}
# Calculate ellipses for first two PCoA axes
# Maximum likelihood approach
calc_ellipses <- function(scores,
ellipses = c("1.AUS",
"1.EU",
"1.NOA",
"1.NZ",
"1.SA")) {
# we just have one community
pcoa_siber <- createSiberObject(scores[, .(
iso1 = A1,
iso2 = A2,
group = continent,
community = 1
)])
# Calculate all possible permutations of ellipses
perm_ellipses <- gtools::permutations(n = 5,
r = 2,
v = ellipses)
perm_ellipses <- as.data.frame(perm_ellipses)
rownames(perm_ellipses) <- paste0(perm_ellipses$V1,
"_",
perm_ellipses$V2)
# Calc overlap
ellipse95_overlap <- list()
for (i in 1:nrow(perm_ellipses)) {
ellipse95_overlap[[i]] <- maxLikOverlap(
perm_ellipses[i, "V1"],
perm_ellipses[i, "V2"],
pcoa_siber,
p.interval = 0.95,
n = 100
)
}
names(ellipse95_overlap) <- rownames(perm_ellipses)
ellipse95_overlap
}
# Hierarchical clustering & optimal number of groups
# method is ward.D2
# uses funciton mycluster_hc
calc_clustering <-
function(x,
traits = c("feed", "resp", "volt", "locom", "size", "bf")) {
trait_patterns <- paste0(traits, collapse = ".*|")
x <- x[, .SD, .SDcols = patterns(paste0(trait_patterns, "|id"))]
setDF(x)
taxa_reg_names <- x$id
row.names(x) <- taxa_reg_names
x$id <- NULL
# Konvert to ktab object
vec <- sub("\\_.*", "\\1", names(x))
blocks <- rle(vec)$lengths
x <- prep.fuzzy(x, blocks)
x <- ktab.list.df(list(x))
dist <- dist.ktab(x, type = "F")
# HC & optimal number of clusters
hc <- hclust(dist, method = "ward.D2")
dend <- as.dendrogram(hc)
gap <- clusGap(
x = as.matrix(dist),
FUN = mycluster_hc,
K.max = 15,
B = 500
)
optimal_nog <- maxSE(gap$Tab[, "gap"],
gap$Tab[, "SE.sim"],
method = "Tibs2001SEmax")
list("hc" = hc,
"dend" = dend,
"optimal_nog" = optimal_nog)
}
# Add TPGs to simulated datasets
add_tpgs_td <- function(cl_obj) {
results <- list()
for (i in names(cl_obj)) {
results[[i]] <-
data.table(
family = names(
cutree(
cl_obj[[i]]$dend,
k = cl_obj[[i]]$optimal_nog,
order_clusters_as_data = FALSE
)
),
group = cutree(
cl_obj[[i]]$dend,
k = cl_obj[[i]]$optimal_nog,
order_clusters_as_data = FALSE
)
)
}
results <- rbindlist(results, idcol = "continent")
}
# Calculate dbrda for mean trait profiles
calc_dbrda <-
function(t_data,
traits = c("feed", "resp", "volt", "locom", "size", "bf")) {
trait_patterns <- paste0(traits, collapse = ".*|")
x <- t_data[, .SD, .SDcols = patterns(paste0(trait_patterns, "|id"))]
setDF(x)
taxa_reg_names <- x$id
row.names(x) <- taxa_reg_names
x$id <- NULL
# Convert to ktab object
vec <- sub("\\_.*", "\\1", names(x))
blocks <- rle(vec)$lengths
x <- prep.fuzzy(x, blocks)
x <- ktab.list.df(list(x))
dist <- dist.ktab(x, type = "F")
# dbrda with continents
dbrda_res <- dbrda(formula = dist ~ continent, data = t_data)
dbrda_res <- summary(dbrda_res)
expl_var <- dbrda_res$constr.chi / dbrda_res$tot.chi
}
# RF with tpgs as dependent variable
calc_rf_tpgs <- function(x,
traits = c("feed", "resp", "volt", "locom", "size", "bf")) {
most_imp_vars <- list()
# ls_instance <- list()
# scores_test <- list()
# scores_train <- list()
trait_pat <- paste0(traits, collapse = ".*|")
for (cont in unique(x$continent)) {
set.seed(1234)
dat <- x[continent == cont, ]
dat <-
dat[, .SD, .SDcols = patterns(paste0(trait_pat, "|group"))]
# Split in train and test data (stratified)
ind <- createDataPartition(dat$group, p = 0.7)
train <- dat[ind[[1]],]
test <- dat[-ind[[1]],]
# Create tasks
task_train <- TaskClassif$new(
id = paste0(cont, "_train"),
backend = train,
target = "group"
)
# Specify stratification for CV
task_train$col_roles$stratum <- "group"
# Create random forest learner
# list of possible learners: mlr3learners
rf_learner <- lrn("classif.ranger",
predict_type = "prob",
importance = "permutation")
# Set up search space
# rf_learner$param_set
search_space <- ps(
mtry = p_int(lower = 1, upper = length(task_train$data()) - 1),
min.node.size = p_int(lower = 1, upper = 10)#,
# sample.fraction = p_dbl(lower = 0.632, upper = 0.8)
)
# Resampling
resampling <- rsmp("cv",
folds = 5L)
# Performance measure for resampling (multivariate Brier score)
mbrier_metric <- mlr3::msr("classif.mbrier")
# When to terminate tuning
evals <- trm("evals", n_evals = 100)
instance = TuningInstanceSingleCrit$new(
task = task_train,
learner = rf_learner,
resampling = resampling,
measure = mbrier_metric,
search_space = search_space,
terminator = evals
)
# Optimization via grid search
tuner <- tnr("grid_search", resolution = 10)
tuner$optimize(instance)
# ls_instance[[cont]] <- instance
# Train rf on train dataset with optimized parameters
rf_learner$param_set$values <-
instance$result_learner_param_vals
rf_learner$train(task_train)
pred_train <- rf_learner$predict_newdata(newdata = train)
# scores_train[[cont]] <- pred_train$score(mlr3::msr("classif.mbrier"))
# Check model on test dataset
pred_test <- rf_learner$predict_newdata(newdata = test)
# scores_test[[cont]] <- pred_test$score(mlr3::msr("classif.mbrier"))
# Retrieve most important variables
most_imp_vars[[cont]] <- rf_learner$importance()
}
list("most_imp_vars" = most_imp_vars)
}
# Functions for distance calculations ----
## Overlap index manly ----
fun_overlap_ind <-
function(p, q) {
1 - sum(p * q) / sqrt(sum(p * p)) / sqrt(sum(q * q))
}
|
\name{rectscale}
\alias{rectscale}
\alias{rectunscale}
\title{
Un/Scale data in a bounding rectangle
}
\description{
Scale data lying in an arbitrary rectangle to lie in
the unit rectangle, and back again
}
\usage{
rectscale(X, rect)
rectunscale(X, rect)
}
\arguments{
\item{X}{
a \code{matrix} or \code{data.frame} of real-valued covariates
}
\item{rect}{
a \code{matrix} describing a bounding rectangle for \code{X}
with 2 columns and \code{ncol(X)} rows
}
}
\value{
a \code{matrix} or \code{data.frame} with the same dimensions as
\code{X} scaled or un-scaled as appropriate
}
\author{
Robert B. Gramacy, \email{rbg@vt.edu}
}
\references{
\url{https://bobby.gramacy.com/r_packages/plgp/}
}
\examples{
X <- matrix(runif(10, 1, 3), ncol=2)
rect <- rbind(c(1,3), c(1,3))
Xs <- rectscale(X, rect)
rectunscale(Xs, rect)
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ utilities }
| /man/rectscale.Rd | no_license | cran/plgp | R | false | false | 971 | rd | \name{rectscale}
\alias{rectscale}
\alias{rectunscale}
\title{
Un/Scale data in a bounding rectangle
}
\description{
Scale data lying in an arbitrary rectangle to lie in
the unit rectangle, and back again
}
\usage{
rectscale(X, rect)
rectunscale(X, rect)
}
\arguments{
\item{X}{
a \code{matrix} or \code{data.frame} of real-valued covariates
}
\item{rect}{
a \code{matrix} describing a bounding rectangle for \code{X}
with 2 columns and \code{ncol(X)} rows
}
}
\value{
a \code{matrix} or \code{data.frame} with the same dimensions as
\code{X} scaled or un-scaled as appropriate
}
\author{
Robert B. Gramacy, \email{rbg@vt.edu}
}
\references{
\url{https://bobby.gramacy.com/r_packages/plgp/}
}
\examples{
X <- matrix(runif(10, 1, 3), ncol=2)
rect <- rbind(c(1,3), c(1,3))
Xs <- rectscale(X, rect)
rectunscale(Xs, rect)
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ utilities }
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/normScore.R
\name{dNormScore}
\alias{dNormScore}
\alias{NormScore}
\alias{pNormScore}
\alias{qNormScore}
\alias{rNormScore}
\alias{sNormScore}
\alias{normOrder}
\alias{pNormScore}
\alias{qNormScore}
\alias{rNormScore}
\alias{sNormScore}
\title{Normal Scores distribution.}
\usage{
dNormScore(x, c, N, U, log = FALSE)
pNormScore(q, c, N, U, lower.tail = TRUE, log.p = FALSE)
qNormScore(p, c, N, U, lower.tail = TRUE, log.p = FALSE)
rNormScore(n, c, N, U)
sNormScore(c, N, U)
}
\arguments{
\item{x, q}{vector of non-negative quantities}
\item{c}{vector number of treatments}
\item{N}{vector total number of observations}
\item{U}{vector sum of reciprocals of the number of the c sample sizes}
\item{log, log.p}{logical vector; if TRUE, probabilities p are given as log(p)}
\item{lower.tail}{logical vector; if TRUE (default), probabilities are \eqn{P[X <= x]}, otherwise, \eqn{P[X > x]}}
\item{p}{vector of probabilities}
\item{n}{number of values to generate. If n is a vector, length(n) values will be generated}
}
\value{
The output values conform to the output from other such functions in \R. \code{dNormScore()} gives the density, \code{pNormScore()} the distribution function and \code{qNormScore()} its inverse. \code{rNormScore()} generates random numbers. \code{sNormScore()} produces a list containing parameters corresponding to the arguments -- mean, median, mode, variance, sd, third cental moment, fourth central moment, Pearson's skewness, skewness, and kurtosis. \code{normOrder()} gives the expected values of the normal order statistics for a sample of size N.
}
\description{
Density, distribution function, quantile function, random generator and summary function for the normal scores test. A function to calculate expected values of normal order statistics is included.
}
\details{
This is the Kruskal-Wallis statistic with ranks replaced by the expected values of normal order statistics. There are c treatments with sample sizes \eqn{n_j, j=1 \dots c}{nj, j=1 \ldots c}. The total sample size is \eqn{N=\sum_1^c n_j}{N=Sum nj}. The distribution depends on c, N, and U, where \eqn{U=\sum_1^c (1/n_j)}{U=Sum (1/nj)}.
Let \eqn{e_N(k)}{eN(k)} be the expected value of the \eqn{k_{th}}{kth} smallest observation in a sample of N independent normal variates. Rank all observations together, and let \eqn{R_{ij}}{Rij} denote the rank of observation \eqn{X_{ij}}{Xij}, \eqn{i=1 \dots n_j}{i=1 \ldots nj} for treatment \eqn{j=1 \dots c}{j=1 \ldots c}, then the normal scores test statistic is
\deqn{x=(N-1)\frac{1}{\sum_{k=1}^{N} e_N(k)^2} \sum_{j=1}^{c}\frac{S_j^2}{n_j}}{x=(N-1)[1/Sum(1 \ldots N)(eN(k)^2)]Sum(1 \ldots c)[(Sj^2)/nj]}
where \eqn{S_j=\sum_{i=1}^{n_j}(e_N(R_{ij}))}{Sj=Sum(1 \ldots nj)(eN(Rij))}.
See Lu and Smith (1979) for a thorough discussion and some exact tables for small r and n. The calculations made here use an incomplete beta approximation -- the same one used for Kruskal-Wallis, only differing in the calculation of the variance of the statistic.
The expected values of the normal order statistics use a modification of M.Maechler's C version of the Fortran algorithm given by Royston (1982). Spot checking the values against Harter (1969) confirms the accuracy to 4 decimal places as claimed by Royston.
}
\examples{
#Assuming three treatments, each with a sample size of 5
pNormScore(2, 3, 15, 0.6)
pNormScore(c(0.11, 1.5, 5.6), 3, 15, 0.6) ## approximately 5\% 50\% and 95\%
sNormScore(3, 15, 0.6)
plot(function(x)dNormScore(x, c=5, N=15, U=0.6), 0, 5)
}
\references{
Harter, H.L. (1969).
\emph{Order statistics and their use in testing and estimation, volume 2.} U.S. Supp. of Doc.
Lu, H.T. and Smith, P.J. (1979) Distribution of normal scores statistic for nonparametric one-way analysis of variance.
\emph{Jour. Am Stat. Assoc.} \bold{74.} 715-722.
Royston, J.P. (1982). Expected normal order statistics (exact and approximate) AS 177.
\emph{Applied Statistics.} \bold{31.} 161-165.
}
\author{
Bob Wheeler \email{bwheelerg@gmail.com}
}
\keyword{distribution}
| /man/dNormScore.Rd | no_license | andrie/SuppDists | R | false | true | 4,109 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/normScore.R
\name{dNormScore}
\alias{dNormScore}
\alias{NormScore}
\alias{pNormScore}
\alias{qNormScore}
\alias{rNormScore}
\alias{sNormScore}
\alias{normOrder}
\alias{pNormScore}
\alias{qNormScore}
\alias{rNormScore}
\alias{sNormScore}
\title{Normal Scores distribution.}
\usage{
dNormScore(x, c, N, U, log = FALSE)
pNormScore(q, c, N, U, lower.tail = TRUE, log.p = FALSE)
qNormScore(p, c, N, U, lower.tail = TRUE, log.p = FALSE)
rNormScore(n, c, N, U)
sNormScore(c, N, U)
}
\arguments{
\item{x, q}{vector of non-negative quantities}
\item{c}{vector number of treatments}
\item{N}{vector total number of observations}
\item{U}{vector sum of reciprocals of the number of the c sample sizes}
\item{log, log.p}{logical vector; if TRUE, probabilities p are given as log(p)}
\item{lower.tail}{logical vector; if TRUE (default), probabilities are \eqn{P[X <= x]}, otherwise, \eqn{P[X > x]}}
\item{p}{vector of probabilities}
\item{n}{number of values to generate. If n is a vector, length(n) values will be generated}
}
\value{
The output values conform to the output from other such functions in \R. \code{dNormScore()} gives the density, \code{pNormScore()} the distribution function and \code{qNormScore()} its inverse. \code{rNormScore()} generates random numbers. \code{sNormScore()} produces a list containing parameters corresponding to the arguments -- mean, median, mode, variance, sd, third cental moment, fourth central moment, Pearson's skewness, skewness, and kurtosis. \code{normOrder()} gives the expected values of the normal order statistics for a sample of size N.
}
\description{
Density, distribution function, quantile function, random generator and summary function for the normal scores test. A function to calculate expected values of normal order statistics is included.
}
\details{
This is the Kruskal-Wallis statistic with ranks replaced by the expected values of normal order statistics. There are c treatments with sample sizes \eqn{n_j, j=1 \dots c}{nj, j=1 \ldots c}. The total sample size is \eqn{N=\sum_1^c n_j}{N=Sum nj}. The distribution depends on c, N, and U, where \eqn{U=\sum_1^c (1/n_j)}{U=Sum (1/nj)}.
Let \eqn{e_N(k)}{eN(k)} be the expected value of the \eqn{k_{th}}{kth} smallest observation in a sample of N independent normal variates. Rank all observations together, and let \eqn{R_{ij}}{Rij} denote the rank of observation \eqn{X_{ij}}{Xij}, \eqn{i=1 \dots n_j}{i=1 \ldots nj} for treatment \eqn{j=1 \dots c}{j=1 \ldots c}, then the normal scores test statistic is
\deqn{x=(N-1)\frac{1}{\sum_{k=1}^{N} e_N(k)^2} \sum_{j=1}^{c}\frac{S_j^2}{n_j}}{x=(N-1)[1/Sum(1 \ldots N)(eN(k)^2)]Sum(1 \ldots c)[(Sj^2)/nj]}
where \eqn{S_j=\sum_{i=1}^{n_j}(e_N(R_{ij}))}{Sj=Sum(1 \ldots nj)(eN(Rij))}.
See Lu and Smith (1979) for a thorough discussion and some exact tables for small r and n. The calculations made here use an incomplete beta approximation -- the same one used for Kruskal-Wallis, only differing in the calculation of the variance of the statistic.
The expected values of the normal order statistics use a modification of M.Maechler's C version of the Fortran algorithm given by Royston (1982). Spot checking the values against Harter (1969) confirms the accuracy to 4 decimal places as claimed by Royston.
}
\examples{
#Assuming three treatments, each with a sample size of 5
pNormScore(2, 3, 15, 0.6)
pNormScore(c(0.11, 1.5, 5.6), 3, 15, 0.6) ## approximately 5\% 50\% and 95\%
sNormScore(3, 15, 0.6)
plot(function(x)dNormScore(x, c=5, N=15, U=0.6), 0, 5)
}
\references{
Harter, H.L. (1969).
\emph{Order statistics and their use in testing and estimation, volume 2.} U.S. Supp. of Doc.
Lu, H.T. and Smith, P.J. (1979) Distribution of normal scores statistic for nonparametric one-way analysis of variance.
\emph{Jour. Am Stat. Assoc.} \bold{74.} 715-722.
Royston, J.P. (1982). Expected normal order statistics (exact and approximate) AS 177.
\emph{Applied Statistics.} \bold{31.} 161-165.
}
\author{
Bob Wheeler \email{bwheelerg@gmail.com}
}
\keyword{distribution}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/find_interaction_flows.R
\name{find_interaction_flows}
\alias{find_interaction_flows}
\title{Identifies flows with interactions among state variables}
\usage{
find_interaction_flows(mbmodel)
}
\arguments{
\item{mbmodel}{modelbuilder model structure, either as list object
or file name}
}
\value{
The function returns a data frame identifying the flows (and
their associated vars) with state variable interactions.
}
\description{
The model needs to adhere to the structure specified by
the modelbuilder package. Models built using the modelbuilder package
automatically have the right structure. A user can also build a
model list structure themselves following the modelbuilder
specifications. If the user provides a file name, this file needs to
be an RDS file and contain a valid modelbuilder model structure.
}
\details{
This function takes as input a modelbuilder model and
identifies the flows that have interactions among state variables.
This is an internal function used by the generate_stratified_model
function.
}
\author{
Andrew Tredennick and Andreas Handel
}
| /man/find_interaction_flows.Rd | no_license | atredennick/modelbuilder | R | false | true | 1,175 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/find_interaction_flows.R
\name{find_interaction_flows}
\alias{find_interaction_flows}
\title{Identifies flows with interactions among state variables}
\usage{
find_interaction_flows(mbmodel)
}
\arguments{
\item{mbmodel}{modelbuilder model structure, either as list object
or file name}
}
\value{
The function returns a data frame identifying the flows (and
their associated vars) with state variable interactions.
}
\description{
The model needs to adhere to the structure specified by
the modelbuilder package. Models built using the modelbuilder package
automatically have the right structure. A user can also build a
model list structure themselves following the modelbuilder
specifications. If the user provides a file name, this file needs to
be an RDS file and contain a valid modelbuilder model structure.
}
\details{
This function takes as input a modelbuilder model and
identifies the flows that have interactions among state variables.
This is an internal function used by the generate_stratified_model
function.
}
\author{
Andrew Tredennick and Andreas Handel
}
|
data("mtcars")
cars <- mtcars
View(mtcars)
library(dplyr)
library(ggplot2)
#install.packages("psych")
library(psych)
pairs.panels(cars[c("mpg", "hp")])
plot(cars[c("mpg" , "hp")])
summary(cars)
cor(cars[c("mpg", "hp")])
hist(cars$mpg) #it shows dependent variable is slightly skewed
shapiro.test(cars$mpg) #checking mpg column for normal distribution using shapiro wilk test
#here we can see that the correlation is not significant and
# there is negative corelation in hp and mpg i.e as hp increases mpg decreases
dev.off()
options(scipen = 0)
cars_model_1 <- lm(mpg ~ hp, data = cars)
summary(cars_model_1)
#find the confidence interval of the fit----
confint(cars_model_1)
#mpg = ????0 + ????1*hp
#As we can see that the F statistic - P value is very small i.e 0.05
#We will reject the null hypothesis that all ???? are zeros.
#????1 has some significant value
#Now we will see the p value of individual parameters
#The P value of hp is again less than 0.05 that means hp is statistically significant
#It has 3 astrics so it is highly significant
#Similarly intercept is also very significant
#By seeing the estimate we can say that with 1 unit increase in
#hp, the mpg decreases by 0.06 units
#By seeing the residuals we can state that
#The model has underpredicted mpg by 8 .23 units
#50% of the errors are between -2.112 and 1.5819
#Also the majority of the predictions were above 1st quartile(-2.112) and under 3rd quartile(1.5819)
plot(cars_model_1)
testdata <- data.frame(hp = c(126, 167, 189, 211 , 272, 312))
predictions<- predict(cars_model_1, newdata =testdata)
predictions
#Hence we have obtained the predicted values of mpg with the given values of hp
cor(cars[c("mpg", "hp", "wt")])
pairs.panels(cars[c("mpg", "hp", "wt")])
plot(cars[c("mpg" , "hp", "wt")])
dev.off()
options(scipen = 0)
cars_model_2 <- lm(mpg ~ hp + wt, data = cars)
summary(cars_model_2)
#Here we can see that the ????0 (Y - intercept) = 49.808 and it statistically significant
#The p values for ????1 , ????2(slope estimate) is less than 0.05. Therefore they are non zero
#Also the 3 stars indicate that the ????2 is most significant
#And the 2 stars indicate that ????1 is less significant than ????2
#The value of ????1 and ????2 are both negative i.e they both decrease with increase in mpg
#The value of R^2 is 82.68% which is good but can be made better using interaction technique
#find the confidence interval of the fit----
confint(cars_model_2)
cars_model_3 <- lm(mpg ~ hp + wt + wt*hp, data = cars)
summary(cars_model_3)
#find the confidence interval of the fit----
confint(cars_model_3)
# The ????1 has become more significant as it gets 3 stars
#The value of R^2 has increased from 82.68% to 88.48% which is good for the model
#Also the Adjusted R-squared value is increased
#The P value of F statistic has also decreased.
#HEnce the model with interaction is better than the normal model and will perform better
testdata1 <- data.frame( hp = c(126, 167, 189, 211 , 272, 312) , wt = c(1.5, 2.2, 2.9, 3.2, 3.8, 4.2))
predictions1<- predict(cars_model_3, newdata = testdata1)
predictions1
#Hence we obtain the predicted values
| /Using Psych library for prediction.R | no_license | kevalchheda/R-Codes | R | false | false | 3,266 | r | data("mtcars")
cars <- mtcars
View(mtcars)
library(dplyr)
library(ggplot2)
#install.packages("psych")
library(psych)
pairs.panels(cars[c("mpg", "hp")])
plot(cars[c("mpg" , "hp")])
summary(cars)
cor(cars[c("mpg", "hp")])
hist(cars$mpg) #it shows dependent variable is slightly skewed
shapiro.test(cars$mpg) #checking mpg column for normal distribution using shapiro wilk test
#here we can see that the correlation is not significant and
# there is negative corelation in hp and mpg i.e as hp increases mpg decreases
dev.off()
options(scipen = 0)
cars_model_1 <- lm(mpg ~ hp, data = cars)
summary(cars_model_1)
#find the confidence interval of the fit----
confint(cars_model_1)
#mpg = ????0 + ????1*hp
#As we can see that the F statistic - P value is very small i.e 0.05
#We will reject the null hypothesis that all ???? are zeros.
#????1 has some significant value
#Now we will see the p value of individual parameters
#The P value of hp is again less than 0.05 that means hp is statistically significant
#It has 3 astrics so it is highly significant
#Similarly intercept is also very significant
#By seeing the estimate we can say that with 1 unit increase in
#hp, the mpg decreases by 0.06 units
#By seeing the residuals we can state that
#The model has underpredicted mpg by 8 .23 units
#50% of the errors are between -2.112 and 1.5819
#Also the majority of the predictions were above 1st quartile(-2.112) and under 3rd quartile(1.5819)
plot(cars_model_1)
testdata <- data.frame(hp = c(126, 167, 189, 211 , 272, 312))
predictions<- predict(cars_model_1, newdata =testdata)
predictions
#Hence we have obtained the predicted values of mpg with the given values of hp
cor(cars[c("mpg", "hp", "wt")])
pairs.panels(cars[c("mpg", "hp", "wt")])
plot(cars[c("mpg" , "hp", "wt")])
dev.off()
options(scipen = 0)
cars_model_2 <- lm(mpg ~ hp + wt, data = cars)
summary(cars_model_2)
#Here we can see that the ????0 (Y - intercept) = 49.808 and it statistically significant
#The p values for ????1 , ????2(slope estimate) is less than 0.05. Therefore they are non zero
#Also the 3 stars indicate that the ????2 is most significant
#And the 2 stars indicate that ????1 is less significant than ????2
#The value of ????1 and ????2 are both negative i.e they both decrease with increase in mpg
#The value of R^2 is 82.68% which is good but can be made better using interaction technique
#find the confidence interval of the fit----
confint(cars_model_2)
cars_model_3 <- lm(mpg ~ hp + wt + wt*hp, data = cars)
summary(cars_model_3)
#find the confidence interval of the fit----
confint(cars_model_3)
# The ????1 has become more significant as it gets 3 stars
#The value of R^2 has increased from 82.68% to 88.48% which is good for the model
#Also the Adjusted R-squared value is increased
#The P value of F statistic has also decreased.
#HEnce the model with interaction is better than the normal model and will perform better
testdata1 <- data.frame( hp = c(126, 167, 189, 211 , 272, 312) , wt = c(1.5, 2.2, 2.9, 3.2, 3.8, 4.2))
predictions1<- predict(cars_model_3, newdata = testdata1)
predictions1
#Hence we obtain the predicted values
|
# extract seasonal stats from zip and save as raw tibbles
# source of zip file:
# https://www.kaggle.com/drgilermo/nba-players-stats
source("libraries.r")
source("functions/generic.r")
# create local data dir
dir.create("data/working/")
dir.create("data/raw/")
# zip file in data/raw
zip_sal = "data/raw/nba-players-stats.zip"
# to see files of zip:
# unzip(zip_sal, list=T)
# csv to get
csv_sal = "Seasons_Stats.csv"
# connect to file
file_sal = unz(zip_sal, csv_sal, open="rb")
# get raw tibble of salaries
raw_stats = read_delim(file_sal, delim=",", col_types=cols())
# save as rds
rdsinpath(raw_stats, "data/working/")
| /r/00-get_stats.R | no_license | fbetteo/fbetteo.github.io | R | false | false | 628 | r | # extract seasonal stats from zip and save as raw tibbles
# source of zip file:
# https://www.kaggle.com/drgilermo/nba-players-stats
source("libraries.r")
source("functions/generic.r")
# create local data dir
dir.create("data/working/")
dir.create("data/raw/")
# zip file in data/raw
zip_sal = "data/raw/nba-players-stats.zip"
# to see files of zip:
# unzip(zip_sal, list=T)
# csv to get
csv_sal = "Seasons_Stats.csv"
# connect to file
file_sal = unz(zip_sal, csv_sal, open="rb")
# get raw tibble of salaries
raw_stats = read_delim(file_sal, delim=",", col_types=cols())
# save as rds
rdsinpath(raw_stats, "data/working/")
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/metropolis.R
\name{metropolis.run}
\alias{metropolis.run}
\title{Run one metropolis chain}
\usage{
metropolis.run(log_prob, x0, iter, draw.prop)
}
\arguments{
\item{log_prob}{a function that takes input \code{x} and returns
a value that is proportional to the log probability density at \code{x}}
\item{x0}{initial value}
\item{iter}{number of iterations}
\item{draw.prop}{a function that takes input \code{x} and
draws a proposal \code{x_prop}}
}
\value{
a list
}
\description{
Run one metropolis chain
}
| /man/metropolis.run.Rd | no_license | jtimonen/mc2 | R | false | true | 587 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/metropolis.R
\name{metropolis.run}
\alias{metropolis.run}
\title{Run one metropolis chain}
\usage{
metropolis.run(log_prob, x0, iter, draw.prop)
}
\arguments{
\item{log_prob}{a function that takes input \code{x} and returns
a value that is proportional to the log probability density at \code{x}}
\item{x0}{initial value}
\item{iter}{number of iterations}
\item{draw.prop}{a function that takes input \code{x} and
draws a proposal \code{x_prop}}
}
\value{
a list
}
\description{
Run one metropolis chain
}
|
library(gistr)
### Name: commits
### Title: List gist commits
### Aliases: commits
### ** Examples
## Not run:
##D gists()[[1]] %>% commits()
##D gist(id = '1f399774e9ecc9153a6f') %>% commits(per_page = 5)
##D
##D # pass in a url
##D gist("https://gist.github.com/expersso/4ac33b9c00751fddc7f8") %>% commits
## End(Not run)
| /data/genthat_extracted_code/gistr/examples/commits.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 333 | r | library(gistr)
### Name: commits
### Title: List gist commits
### Aliases: commits
### ** Examples
## Not run:
##D gists()[[1]] %>% commits()
##D gist(id = '1f399774e9ecc9153a6f') %>% commits(per_page = 5)
##D
##D # pass in a url
##D gist("https://gist.github.com/expersso/4ac33b9c00751fddc7f8") %>% commits
## End(Not run)
|
# Extracting the content from a pdf file
# 1) Install Xpdf
# 2) Test the "pdftotext.exe" installation in a terminal mode
# 3) Run terminal mode command "pdftotext.exe" from R
# 3.1) Use R to implement terminal mode command
# 4) Use R to extract
rm(list=ls()); cat("\014") # Clear Workspace and Console
### --- Example 1: Convert to text single pdf files that is contained in a single folder. ----
exe.loc <- Sys.which("pdftotext") # location of "pdftotext.exe"
pdf.loc <- file.path(getwd(),"XPDF Files") # folder "PDF Files" with PDFs
myPDFfiles <- normalizePath(list.files(path = pdf.loc, pattern = "pdf", full.names = TRUE)) # Get the path (chr-vector) of PDF file names
# Using terminal window system comand:
# Convert single pdf file to text by placing "" around the chr-vector with PDF file names. Note: how ' is used as escape character arround "
system(paste(exe.loc, paste0('"', myPDFfiles[1], '"')), wait=FALSE)
### --- Example 3: # Convert to text several pdf files that are contained in a single folder.
# by calling the terminal window system comand:
#
# Use lapply with in line function to convert each PDF file indexed by "i" into a text file
lapply(myPDFfiles, function(i) system(paste(exe.loc, paste0('"', i, '"')), wait = FALSE))
| /Xpdf Exercise.R | no_license | shuyiz666/Web-Mining | R | false | false | 1,287 | r | # Extracting the content from a pdf file
# 1) Install Xpdf
# 2) Test the "pdftotext.exe" installation in a terminal mode
# 3) Run terminal mode command "pdftotext.exe" from R
# 3.1) Use R to implement terminal mode command
# 4) Use R to extract
rm(list=ls()); cat("\014") # Clear Workspace and Console
### --- Example 1: Convert to text single pdf files that is contained in a single folder. ----
exe.loc <- Sys.which("pdftotext") # location of "pdftotext.exe"
pdf.loc <- file.path(getwd(),"XPDF Files") # folder "PDF Files" with PDFs
myPDFfiles <- normalizePath(list.files(path = pdf.loc, pattern = "pdf", full.names = TRUE)) # Get the path (chr-vector) of PDF file names
# Using terminal window system comand:
# Convert single pdf file to text by placing "" around the chr-vector with PDF file names. Note: how ' is used as escape character arround "
system(paste(exe.loc, paste0('"', myPDFfiles[1], '"')), wait=FALSE)
### --- Example 3: # Convert to text several pdf files that are contained in a single folder.
# by calling the terminal window system comand:
#
# Use lapply with in line function to convert each PDF file indexed by "i" into a text file
lapply(myPDFfiles, function(i) system(paste(exe.loc, paste0('"', i, '"')), wait = FALSE))
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/reexport_raws_profile.R
\docType{import}
\name{aws_cli_install}
\alias{aws_cli_install}
\title{Install AWS CLI}
\description{
These objects are imported from other packages. Follow the links
below to see their documentation.
\describe{
\item{raws.profile}{\code{\link[raws.profile]{aws_cli_install}}}
}}
| /man/aws_cli_install.Rd | no_license | samuelmacedo83/raws.sns | R | false | true | 386 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/reexport_raws_profile.R
\docType{import}
\name{aws_cli_install}
\alias{aws_cli_install}
\title{Install AWS CLI}
\description{
These objects are imported from other packages. Follow the links
below to see their documentation.
\describe{
\item{raws.profile}{\code{\link[raws.profile]{aws_cli_install}}}
}}
|
library(shiny)
#nGramAll <- fread('predictionTableFull.csv')
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Next Word Prediction App"),
# Sidebar with a slider input for number of predicted words to return
sidebarLayout(
sidebarPanel(
strong('Introduction'),
p('This is the Shiny app for next word prediction for the Coursera Data Science Capstone Project'),
p("The algorithm is based on Katz's back-off model using 2-gram to 7-grams"),
strong('Instructions'),
p('The inputs are as follows'),
tags$ul(
tags$li('Query word/phrase: word or phrase for prediction'),
tags$li('Number of predicted next word: the number of predictions')
),
strong('Output'),
p('The predicted next word will show up in the order of most frequently used to less frequently used')
),
# Show a plot of the generated distribution
mainPanel(
h4('Query word/phrase:'),
tags$textarea(id = 'query', rows = 2, cols = 50),
HTML("<br>"), HTML("<br>"),
h4('Number of predictions:'),
sliderInput('wordN', '',
min = 1, max = 5, value = 1, step = 1),
HTML("<br>"), hr(), HTML("<br>"),
h4('Predicted next word'),
verbatimTextOutput('predicted')
)
)
)) | /word/ui.R | no_license | RJourney/Phys225L | R | false | false | 1,534 | r | library(shiny)
#nGramAll <- fread('predictionTableFull.csv')
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Next Word Prediction App"),
# Sidebar with a slider input for number of predicted words to return
sidebarLayout(
sidebarPanel(
strong('Introduction'),
p('This is the Shiny app for next word prediction for the Coursera Data Science Capstone Project'),
p("The algorithm is based on Katz's back-off model using 2-gram to 7-grams"),
strong('Instructions'),
p('The inputs are as follows'),
tags$ul(
tags$li('Query word/phrase: word or phrase for prediction'),
tags$li('Number of predicted next word: the number of predictions')
),
strong('Output'),
p('The predicted next word will show up in the order of most frequently used to less frequently used')
),
# Show a plot of the generated distribution
mainPanel(
h4('Query word/phrase:'),
tags$textarea(id = 'query', rows = 2, cols = 50),
HTML("<br>"), HTML("<br>"),
h4('Number of predictions:'),
sliderInput('wordN', '',
min = 1, max = 5, value = 1, step = 1),
HTML("<br>"), hr(), HTML("<br>"),
h4('Predicted next word'),
verbatimTextOutput('predicted')
)
)
)) |
testlist <- list(A = structure(c(1.38997190089718e-309, 8.88033396529973e-232, 3.81571422914747e-236), .Dim = c(1L, 3L)), B = structure(0, .Dim = c(1L, 1L)))
result <- do.call(multivariance:::match_rows,testlist)
str(result) | /multivariance/inst/testfiles/match_rows/AFL_match_rows/match_rows_valgrind_files/1613127154-test.R | no_license | akhikolla/updatedatatype-list3 | R | false | false | 226 | r | testlist <- list(A = structure(c(1.38997190089718e-309, 8.88033396529973e-232, 3.81571422914747e-236), .Dim = c(1L, 3L)), B = structure(0, .Dim = c(1L, 1L)))
result <- do.call(multivariance:::match_rows,testlist)
str(result) |
pollutantmean <- function(directory, pollutant, id = 1:332) {
## 'directory' is a character vector of length 1 indicating
## the location of the CSV files
## 'pollutant' is a character vector of length 1 indicating
## the name of the pollutant for which we will calculate the
## mean; either "sulfate" or "nitrate".
## 'id' is an integer vector indicating the monitor ID numbers
## to be used
## Return the mean of the pollutant across all monitors list
## in the 'id' vector (ignoring NA values)
if ((pollutant != "sulfate") && (pollutant != "nitrate" )) {
return ("ERROR")
}
todas = vector()
for (sensor in id) {
sensor_txt = paste(sprintf("%03i", sensor), "csv", sep = ".")
sensor = paste (directory, sensor_txt, sep = "/")
mediciones <- read.csv(sensor)
todas <- rbind (todas, mediciones[pollutant])
}
los_ok = todas[!is.na(todas)]
media_total = mean(los_ok)
return(media_total)
}
| /PA1.R | no_license | Surfinfan/ProgrammingAssignment-1 | R | false | false | 964 | r | pollutantmean <- function(directory, pollutant, id = 1:332) {
## 'directory' is a character vector of length 1 indicating
## the location of the CSV files
## 'pollutant' is a character vector of length 1 indicating
## the name of the pollutant for which we will calculate the
## mean; either "sulfate" or "nitrate".
## 'id' is an integer vector indicating the monitor ID numbers
## to be used
## Return the mean of the pollutant across all monitors list
## in the 'id' vector (ignoring NA values)
if ((pollutant != "sulfate") && (pollutant != "nitrate" )) {
return ("ERROR")
}
todas = vector()
for (sensor in id) {
sensor_txt = paste(sprintf("%03i", sensor), "csv", sep = ".")
sensor = paste (directory, sensor_txt, sep = "/")
mediciones <- read.csv(sensor)
todas <- rbind (todas, mediciones[pollutant])
}
los_ok = todas[!is.na(todas)]
media_total = mean(los_ok)
return(media_total)
}
|
numPerPatch111228 <- c(2462,2538)
| /NatureEE-data-archive/Run203071/JAFSdata/JAFSnumPerPatch111228.R | no_license | flaxmans/NatureEE2017 | R | false | false | 34 | r | numPerPatch111228 <- c(2462,2538)
|
library(RCurl)
library(XML)
library(stringr)
library(rvest)
library(xlsx)
crawl_article <- function(year){
volume = 0
if(year>2020 | year<2000){
stop("Entered I/P is not correct.")
} else {
volume = (year %% 2000) + 1
}
journal = "https://genomebiology.biomedcentral.com/"
journal_clear = "https://genomebiology.biomedcentral.com"
list_of_articles = function(page_url){
link_of_article = page_url %>% read_html() %>% html_nodes("#main-content > div > main > div:nth-child(3) > ol > li > article > div:nth-child(1) > h3 > a") %>% html_attr("href")
publish_date_str = page_url %>% read_html() %>% html_nodes("#main-content > div > main > div:nth-child(3) > ol > li > article > div > div > div > p:nth-child(2) > span") %>% html_text()
published_date = as.numeric(str_extract(publish_date_str, "[0-9]{4}+"))
return(data.frame(DATE=published_date,url=link_of_article))
}
page_list_url = sprintf("https://genomebiology.biomedcentral.com/articles?tab=keyword&searchType=journalSearch&sort=PubDate&volume=%d&page=1",volume)
max_str = page_list_url %>% read_html() %>% html_nodes("#main-content > div > main > div:nth-child(3) > h2 > strong") %>% html_text()
max_articles = as.numeric(str_extract(max_str, "[0-9]+"))
if(max_articles %% 50 == 0)
max_pages = max_articles / 50
else
max_pages = (max_articles / 50) + 1
page_url = sprintf("https://genomebiology.biomedcentral.com/articles?tab=keyword&searchType=journalSearch&sort=PubDate&volume=%d&page=",volume)
#generate article url list
page_url_list = ""
articles_data = data.frame(DATE=c(),url=c())
for(i in 1:max_pages){
cat("\r",paste("Page number ",i," Loading..."))
full_url = paste(page_url,i,sep="")
articlesUrl_and_DATE = list_of_articles(full_url)#function call: list_of_articles()
articlesUrl_and_DATE$url = paste(journal_clear, articlesUrl_and_DATE$url, sep="")#add site url, to fulfill the url of an article
articles_data = rbind(articles_data, articlesUrl_and_DATE)#rown bind, store all articles urls and DATE
page_url_list = c(page_url_list, full_url)
}
page_url_list = page_url_list[-1]
write(page_url_list, "page_url_list.txt")
print("[I/O]: FILE: page_url_list.txt created.")
write.csv(articles_data, "article_DATEandURL_list.csv")
print("[I/O]: FILE: article_DATEandURL_list.csv created.")
Analysis_of_article = function(DATE, url){
options(warn=-1)
doc = url %>% read_html()
DATE = DATE
title = doc %>% html_nodes("#main-content > main > article > div > h1") %>% html_text()
author_list = doc %>% html_nodes("#main-content > main > article > div > ul.c-author-list.js-list-authors.js-etal-collapsed > li > span > a") %>% html_text()
author = paste(unlist(author_list),collapse = ";")
authorAffiliation = doc %>% html_nodes("#author-information-content > ol.c-article-author-affiliation__list") %>% html_text()
correspondingAuthor = doc %>% html_nodes("#corresp-c1") %>% html_text()
correspondingAuthorEmail = paste(journal_clear,doc %>% html_nodes("#corresp-c1") %>% html_attr("href"),"")
publicationDate = doc %>% html_nodes("#main-content > main > article > div > ul.c-article-identifiers > li:nth-child(3) > a > time") %>% html_text()
abstract = doc %>% html_nodes("#Abs1-content") %>% html_text()
keywords_list = doc %>% html_nodes("#article-info-content > div > div:nth-child(2) > ul.c-article-subject-list > li > span") %>% html_text()
keywords = paste(unlist(keywords_list),collapse = ";")
fullText = paste("https:",doc %>% html_nodes("#main-content > div > aside > div.c-pdf-download.u-clear-both > a") %>% html_attr("href"),sep = "")
if(length(abstract)==0) abstract <- NA
if(length(correspondingAuthor)==0) correspondingAuthor <- NA
if(length(authorAffiliation)==0) authorAffiliation <- NA
extract_data_from_row = data.frame(DATE, title, author, authorAffiliation, correspondingAuthor,
correspondingAuthorEmail, publicationDate, abstract, keywords, fullText)
return(extract_data_from_row)
}
extracted_data = data.frame("DOP"=c(),"Title"=c(), "Author"=c(), "Author_Affiliation"=c(), "Corresponding_Author"=c(), "Corresponding_Author_email"=c(),
"Publication_Date"=c(), "Abstract"=c(), "Keywords"=c(), "Full Text"=c())
total_number = as.integer(length(articles_data[,1]))
for(i in 1:total_number){
cat("\r",paste("Crawling articles from article ",i,"..."))
extracted_data = rbind(extracted_data, Analysis_of_article(articles_data[i,1], articles_data[i,2]))#function call: Analysis_of_article
}
options(warn=-1)
dir.create("output")
write.csv(extracted_data,file = "output/Genome_Biology.csv", append = TRUE)
print("[I/O]: FILE: output/Genome_Biology.csv created.")
}
crawl_article(2018)
| /scraping.R | no_license | manishptl/web_crawling_using_R | R | false | false | 5,234 | r | library(RCurl)
library(XML)
library(stringr)
library(rvest)
library(xlsx)
crawl_article <- function(year){
volume = 0
if(year>2020 | year<2000){
stop("Entered I/P is not correct.")
} else {
volume = (year %% 2000) + 1
}
journal = "https://genomebiology.biomedcentral.com/"
journal_clear = "https://genomebiology.biomedcentral.com"
list_of_articles = function(page_url){
link_of_article = page_url %>% read_html() %>% html_nodes("#main-content > div > main > div:nth-child(3) > ol > li > article > div:nth-child(1) > h3 > a") %>% html_attr("href")
publish_date_str = page_url %>% read_html() %>% html_nodes("#main-content > div > main > div:nth-child(3) > ol > li > article > div > div > div > p:nth-child(2) > span") %>% html_text()
published_date = as.numeric(str_extract(publish_date_str, "[0-9]{4}+"))
return(data.frame(DATE=published_date,url=link_of_article))
}
page_list_url = sprintf("https://genomebiology.biomedcentral.com/articles?tab=keyword&searchType=journalSearch&sort=PubDate&volume=%d&page=1",volume)
max_str = page_list_url %>% read_html() %>% html_nodes("#main-content > div > main > div:nth-child(3) > h2 > strong") %>% html_text()
max_articles = as.numeric(str_extract(max_str, "[0-9]+"))
if(max_articles %% 50 == 0)
max_pages = max_articles / 50
else
max_pages = (max_articles / 50) + 1
page_url = sprintf("https://genomebiology.biomedcentral.com/articles?tab=keyword&searchType=journalSearch&sort=PubDate&volume=%d&page=",volume)
#generate article url list
page_url_list = ""
articles_data = data.frame(DATE=c(),url=c())
for(i in 1:max_pages){
cat("\r",paste("Page number ",i," Loading..."))
full_url = paste(page_url,i,sep="")
articlesUrl_and_DATE = list_of_articles(full_url)#function call: list_of_articles()
articlesUrl_and_DATE$url = paste(journal_clear, articlesUrl_and_DATE$url, sep="")#add site url, to fulfill the url of an article
articles_data = rbind(articles_data, articlesUrl_and_DATE)#rown bind, store all articles urls and DATE
page_url_list = c(page_url_list, full_url)
}
page_url_list = page_url_list[-1]
write(page_url_list, "page_url_list.txt")
print("[I/O]: FILE: page_url_list.txt created.")
write.csv(articles_data, "article_DATEandURL_list.csv")
print("[I/O]: FILE: article_DATEandURL_list.csv created.")
Analysis_of_article = function(DATE, url){
options(warn=-1)
doc = url %>% read_html()
DATE = DATE
title = doc %>% html_nodes("#main-content > main > article > div > h1") %>% html_text()
author_list = doc %>% html_nodes("#main-content > main > article > div > ul.c-author-list.js-list-authors.js-etal-collapsed > li > span > a") %>% html_text()
author = paste(unlist(author_list),collapse = ";")
authorAffiliation = doc %>% html_nodes("#author-information-content > ol.c-article-author-affiliation__list") %>% html_text()
correspondingAuthor = doc %>% html_nodes("#corresp-c1") %>% html_text()
correspondingAuthorEmail = paste(journal_clear,doc %>% html_nodes("#corresp-c1") %>% html_attr("href"),"")
publicationDate = doc %>% html_nodes("#main-content > main > article > div > ul.c-article-identifiers > li:nth-child(3) > a > time") %>% html_text()
abstract = doc %>% html_nodes("#Abs1-content") %>% html_text()
keywords_list = doc %>% html_nodes("#article-info-content > div > div:nth-child(2) > ul.c-article-subject-list > li > span") %>% html_text()
keywords = paste(unlist(keywords_list),collapse = ";")
fullText = paste("https:",doc %>% html_nodes("#main-content > div > aside > div.c-pdf-download.u-clear-both > a") %>% html_attr("href"),sep = "")
if(length(abstract)==0) abstract <- NA
if(length(correspondingAuthor)==0) correspondingAuthor <- NA
if(length(authorAffiliation)==0) authorAffiliation <- NA
extract_data_from_row = data.frame(DATE, title, author, authorAffiliation, correspondingAuthor,
correspondingAuthorEmail, publicationDate, abstract, keywords, fullText)
return(extract_data_from_row)
}
extracted_data = data.frame("DOP"=c(),"Title"=c(), "Author"=c(), "Author_Affiliation"=c(), "Corresponding_Author"=c(), "Corresponding_Author_email"=c(),
"Publication_Date"=c(), "Abstract"=c(), "Keywords"=c(), "Full Text"=c())
total_number = as.integer(length(articles_data[,1]))
for(i in 1:total_number){
cat("\r",paste("Crawling articles from article ",i,"..."))
extracted_data = rbind(extracted_data, Analysis_of_article(articles_data[i,1], articles_data[i,2]))#function call: Analysis_of_article
}
options(warn=-1)
dir.create("output")
write.csv(extracted_data,file = "output/Genome_Biology.csv", append = TRUE)
print("[I/O]: FILE: output/Genome_Biology.csv created.")
}
crawl_article(2018)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/synthdid.R
\name{did_estimate}
\alias{did_estimate}
\title{synthdid_estimate for diff-in-diff estimates.
Takes all the same parameters, but default, uses constant weights lambda and omega}
\usage{
did_estimate(
Y,
N0,
T0,
X = array(dim = c(dim(Y), 0)),
zeta.lambda = 0,
zeta.omega = sd(apply(Y, 1, diff)),
lambda.intercept = FALSE,
omega.intercept = FALSE,
weights = list(lambda = rep(1/T0, T0), omega = rep(1/N0, N0), vals = NULL),
min.decrease = 0.001,
max.iter = 10000
)
}
\arguments{
\item{Y}{the observation matrix.}
\item{N0}{the number of control units. Rows 1-N0 of Y correspond to the control units.}
\item{T0}{the number of pre-treatment time steps. Columns 1-T0 of Y correspond to pre-treatment time steps.}
\item{X}{an optional 3-D array of time-varying covariates. Shape should be N X T X C for C covariates.}
\item{zeta.lambda}{Its square is weight of the ridge penalty relative to MSE. Defaults to 0.}
\item{zeta.omega}{Analogous for omega. Defaults to the standard deviation of first differences of Y.}
\item{lambda.intercept}{Binary. Use an intercept when estimating lambda.}
\item{omega.intercept}{Binary. Use an intercept when estimating omega.}
\item{weights}{a list with fields lambda and omega. If non-null weights$lambda is passed,
we use them instead of estimating lambda weights. Same for weights$omega.}
\item{min.decrease}{Tunes a stopping criterion for our weight estimator. Stop after an iteration results in a decrease
in penalized MSE smaller than min.decrease^2.}
\item{max.iter}{A fallback stopping criterion for our weight estimator. Stop after this number of iterations.}
}
\value{
An average treatment effect estimate, 'weights' and 'setup' attached as attributes.
Weights contains the estimated weights lambda and omega and corresponding intercepts.
If covariates X are passedas well as regression coefficients beta if X is passed
Setup is a list describing the problem passed in: Y, N0, T0, X.
}
\description{
synthdid_estimate for diff-in-diff estimates.
Takes all the same parameters, but default, uses constant weights lambda and omega
}
| /man/did_estimate.Rd | permissive | akankshavardani/synthdid | R | false | true | 2,215 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/synthdid.R
\name{did_estimate}
\alias{did_estimate}
\title{synthdid_estimate for diff-in-diff estimates.
Takes all the same parameters, but default, uses constant weights lambda and omega}
\usage{
did_estimate(
Y,
N0,
T0,
X = array(dim = c(dim(Y), 0)),
zeta.lambda = 0,
zeta.omega = sd(apply(Y, 1, diff)),
lambda.intercept = FALSE,
omega.intercept = FALSE,
weights = list(lambda = rep(1/T0, T0), omega = rep(1/N0, N0), vals = NULL),
min.decrease = 0.001,
max.iter = 10000
)
}
\arguments{
\item{Y}{the observation matrix.}
\item{N0}{the number of control units. Rows 1-N0 of Y correspond to the control units.}
\item{T0}{the number of pre-treatment time steps. Columns 1-T0 of Y correspond to pre-treatment time steps.}
\item{X}{an optional 3-D array of time-varying covariates. Shape should be N X T X C for C covariates.}
\item{zeta.lambda}{Its square is weight of the ridge penalty relative to MSE. Defaults to 0.}
\item{zeta.omega}{Analogous for omega. Defaults to the standard deviation of first differences of Y.}
\item{lambda.intercept}{Binary. Use an intercept when estimating lambda.}
\item{omega.intercept}{Binary. Use an intercept when estimating omega.}
\item{weights}{a list with fields lambda and omega. If non-null weights$lambda is passed,
we use them instead of estimating lambda weights. Same for weights$omega.}
\item{min.decrease}{Tunes a stopping criterion for our weight estimator. Stop after an iteration results in a decrease
in penalized MSE smaller than min.decrease^2.}
\item{max.iter}{A fallback stopping criterion for our weight estimator. Stop after this number of iterations.}
}
\value{
An average treatment effect estimate, 'weights' and 'setup' attached as attributes.
Weights contains the estimated weights lambda and omega and corresponding intercepts.
If covariates X are passedas well as regression coefficients beta if X is passed
Setup is a list describing the problem passed in: Y, N0, T0, X.
}
\description{
synthdid_estimate for diff-in-diff estimates.
Takes all the same parameters, but default, uses constant weights lambda and omega
}
|
#!/usr/bin/env Rscript
# Command line argument processing
args <- commandArgs(trailingOnly=TRUE)
if (length(args) < 3) {
stop("Usage: edgeR_heatmap_MDS.r <sample_1.bam> <sample_2.bam> <sample_3.bam> (more bam files optional)", call.=FALSE)
}
# Load / install required packages
if (!require("limma")){
source("http://bioconductor.org/biocLite.R")
biocLite("limma", suppressUpdates=TRUE)
library("limma")
}
if (!require("edgeR")){
source("http://bioconductor.org/biocLite.R")
biocLite("edgeR", suppressUpdates=TRUE)
library("edgeR")
}
if (!require("data.table")){
install.packages("data.table", dependencies=TRUE, repos='http://cloud.r-project.org/')
library("data.table")
}
if (!require("gplots")) {
install.packages("gplots", dependencies=TRUE, repos='http://cloud.r-project.org/')
library("gplots")
}
# Load count column from all files into a list of data frames
# Use data.tables fread as much much faster than read.table
# Row names are GeneIDs
temp <- lapply(lapply(args, fread, skip="Geneid", header=TRUE), function(x){return(as.data.frame(x)[,c(1, ncol(x))])})
# Merge into a single data frame
merge.all <- function(x, y) {
merge(x, y, all=TRUE, by="Geneid")
}
data <- data.frame(Reduce(merge.all, temp))
# Clean sample name headers
colnames(data) <- gsub("Aligned.sortedByCoord.out.bam", "", colnames(data))
# Set GeneID as row name
rownames(data) <- data[,1]
data[,1] <- NULL
# Convert data frame to edgeR DGE object
dataDGE <- DGEList( counts=data.matrix(data) )
# Normalise counts
dataNorm <- calcNormFactors(dataDGE)
# Make MDS plot
pdf('edgeR_MDS_plot.pdf')
MDSdata <- plotMDS(dataNorm)
dev.off()
# Print distance matrix to file
write.csv(MDSdata$distance.matrix, 'edgeR_MDS_distance_matrix.csv', quote=FALSE,append=TRUE)
# Print plot x,y co-ordinates to file
MDSxy = MDSdata$cmdscale.out
colnames(MDSxy) = c(paste(MDSdata$axislabel, '1'), paste(MDSdata$axislabel, '2'))
write.csv(MDSxy, 'edgeR_MDS_Aplot_coordinates_mqc.csv', quote=FALSE, append=TRUE)
# Get the log counts per million values
logcpm <- cpm(dataNorm, prior.count=2, log=TRUE)
# Calculate the euclidean distances between samples
dists = dist(t(logcpm))
# Plot a heatmap of correlations
pdf('log2CPM_sample_distances_heatmap.pdf')
hmap <- heatmap.2(as.matrix(dists),
main="Sample Correlations", key.title="Distance", trace="none",
dendrogram="row", margin=c(9, 9)
)
dev.off()
# Plot the heatmap dendrogram
pdf('log2CPM_sample_distances_dendrogram.pdf')
plot(hmap$rowDendrogram, main="Sample Dendrogram")
dev.off()
# Write clustered distance values to file
write.csv(hmap$carpet, 'log2CPM_sample_distances_mqc.csv', quote=FALSE, append=TRUE)
file.create("corr.done")
# Printing sessioninfo to standard out
print("Sample correlation info:")
sessionInfo()
| /bin/edgeR_heatmap_MDS.r | permissive | kerimoff/rnaseq | R | false | false | 2,798 | r | #!/usr/bin/env Rscript
# Command line argument processing
args <- commandArgs(trailingOnly=TRUE)
if (length(args) < 3) {
stop("Usage: edgeR_heatmap_MDS.r <sample_1.bam> <sample_2.bam> <sample_3.bam> (more bam files optional)", call.=FALSE)
}
# Load / install required packages
if (!require("limma")){
source("http://bioconductor.org/biocLite.R")
biocLite("limma", suppressUpdates=TRUE)
library("limma")
}
if (!require("edgeR")){
source("http://bioconductor.org/biocLite.R")
biocLite("edgeR", suppressUpdates=TRUE)
library("edgeR")
}
if (!require("data.table")){
install.packages("data.table", dependencies=TRUE, repos='http://cloud.r-project.org/')
library("data.table")
}
if (!require("gplots")) {
install.packages("gplots", dependencies=TRUE, repos='http://cloud.r-project.org/')
library("gplots")
}
# Load count column from all files into a list of data frames
# Use data.tables fread as much much faster than read.table
# Row names are GeneIDs
temp <- lapply(lapply(args, fread, skip="Geneid", header=TRUE), function(x){return(as.data.frame(x)[,c(1, ncol(x))])})
# Merge into a single data frame
merge.all <- function(x, y) {
merge(x, y, all=TRUE, by="Geneid")
}
data <- data.frame(Reduce(merge.all, temp))
# Clean sample name headers
colnames(data) <- gsub("Aligned.sortedByCoord.out.bam", "", colnames(data))
# Set GeneID as row name
rownames(data) <- data[,1]
data[,1] <- NULL
# Convert data frame to edgeR DGE object
dataDGE <- DGEList( counts=data.matrix(data) )
# Normalise counts
dataNorm <- calcNormFactors(dataDGE)
# Make MDS plot
pdf('edgeR_MDS_plot.pdf')
MDSdata <- plotMDS(dataNorm)
dev.off()
# Print distance matrix to file
write.csv(MDSdata$distance.matrix, 'edgeR_MDS_distance_matrix.csv', quote=FALSE,append=TRUE)
# Print plot x,y co-ordinates to file
MDSxy = MDSdata$cmdscale.out
colnames(MDSxy) = c(paste(MDSdata$axislabel, '1'), paste(MDSdata$axislabel, '2'))
write.csv(MDSxy, 'edgeR_MDS_Aplot_coordinates_mqc.csv', quote=FALSE, append=TRUE)
# Get the log counts per million values
logcpm <- cpm(dataNorm, prior.count=2, log=TRUE)
# Calculate the euclidean distances between samples
dists = dist(t(logcpm))
# Plot a heatmap of correlations
pdf('log2CPM_sample_distances_heatmap.pdf')
hmap <- heatmap.2(as.matrix(dists),
main="Sample Correlations", key.title="Distance", trace="none",
dendrogram="row", margin=c(9, 9)
)
dev.off()
# Plot the heatmap dendrogram
pdf('log2CPM_sample_distances_dendrogram.pdf')
plot(hmap$rowDendrogram, main="Sample Dendrogram")
dev.off()
# Write clustered distance values to file
write.csv(hmap$carpet, 'log2CPM_sample_distances_mqc.csv', quote=FALSE, append=TRUE)
file.create("corr.done")
# Printing sessioninfo to standard out
print("Sample correlation info:")
sessionInfo()
|
require(ggplot2)
plot.p.value <- function(mpvalue, vlabel, filename)
{
grf <- ggplot() +
geom_line(data=mpvalue[mpvalue$config==1,], aes(x = participation, y = p.value, color = vlabel[1])) +
geom_point(data=mpvalue[mpvalue$config==1,], aes(x = participation, y = p.value, color = vlabel[1]))
if (length(mpvalue$config[mpvalue$config==2]) > 0)
{
grf <- grf + geom_line(data=mpvalue[mpvalue$config==2,], aes(x = participation, y = p.value, color = vlabel[2])) +
geom_point(data=mpvalue[mpvalue$config==2,], aes(x = participation, y = p.value, color = vlabel[2]))
}
if (length(mpvalue$config[mpvalue$config==3]) > 0)
{
grf <- grf + geom_line(data=mpvalue[mpvalue$config==3,], aes(x = participation, y = p.value, color = vlabel[3])) +
geom_point(data=mpvalue[mpvalue$config==3,], aes(x = participation, y = p.value, color = vlabel[3]))
}
if (length(mpvalue$config[mpvalue$config==4]) > 0) {
grf <- grf + geom_line(data=mpvalue[mpvalue$config==4,], aes(x = participation, y = p.value, color = vlabel[4]))
}
grf <- grf +
scale_color_manual(values=c("orange", "darkblue", "darkgreen", "darkred")) +
labs(color="Configuration") +
theme_bw() +
theme(panel.grid.minor = element_blank()) + theme(legend.position = "bottom") +
scale_x_continuous(breaks = seq(0, 1, 0.1), labels = scales::percent_format()) +
scale_y_continuous(breaks = seq(0, 1, 0.1))
ggsave(filename, width = 8, height = 5)
}
plot.boxplot.clo <- function(mpvalue, filename)
{
grf <- ggplot(mpvalue, aes(participation, closeness)) + geom_boxplot(aes(group = cut_width(participation, 0.1)), color="darkblue") +
theme_bw() +
theme(panel.grid.minor = element_blank()) + theme(legend.position = "bottom") +
scale_x_continuous(breaks = seq(0, 1, 0.1), labels = scales::percent_format())
ggsave(filename, width = 8, height = 5)
}
plot.boxplot.degree <- function(mpvalue, filename, filenameh)
{
grf <- ggplot(mpvalue, aes(participation, degree)) + geom_boxplot(aes(group = cut_width(participation, 0.1)), color="darkblue") +
theme_bw() +
theme(panel.grid.minor = element_blank()) + theme(legend.position = "none") +
scale_x_continuous(breaks = seq(0, 1, 0.1), labels = scales::percent_format())
ggsave(filename, width = 8, height = 5)
t <- mpvalue[mpvalue$participation==0 | mpvalue$participation==1,]
t$participation = paste(t$participation*100, "%")
ggplot(t, aes(x=degree, fill = participation)) +
geom_histogram(binwidth = 1) +
scale_fill_manual(values=c("darkblue", "darkgreen", "darkred")) +
theme_bw() +
theme(panel.grid.minor = element_blank()) + theme(legend.position = "none") +
theme(strip.background = element_rect(fill="orange")) +
facet_wrap(~participation, ncol = 1)
ggsave(filenameh, width = 8, height = 5)
} | /adiliorosa/scripts/outros/DataVizFunctions.R | no_license | AdilioR/tccs | R | false | false | 2,878 | r | require(ggplot2)
plot.p.value <- function(mpvalue, vlabel, filename)
{
grf <- ggplot() +
geom_line(data=mpvalue[mpvalue$config==1,], aes(x = participation, y = p.value, color = vlabel[1])) +
geom_point(data=mpvalue[mpvalue$config==1,], aes(x = participation, y = p.value, color = vlabel[1]))
if (length(mpvalue$config[mpvalue$config==2]) > 0)
{
grf <- grf + geom_line(data=mpvalue[mpvalue$config==2,], aes(x = participation, y = p.value, color = vlabel[2])) +
geom_point(data=mpvalue[mpvalue$config==2,], aes(x = participation, y = p.value, color = vlabel[2]))
}
if (length(mpvalue$config[mpvalue$config==3]) > 0)
{
grf <- grf + geom_line(data=mpvalue[mpvalue$config==3,], aes(x = participation, y = p.value, color = vlabel[3])) +
geom_point(data=mpvalue[mpvalue$config==3,], aes(x = participation, y = p.value, color = vlabel[3]))
}
if (length(mpvalue$config[mpvalue$config==4]) > 0) {
grf <- grf + geom_line(data=mpvalue[mpvalue$config==4,], aes(x = participation, y = p.value, color = vlabel[4]))
}
grf <- grf +
scale_color_manual(values=c("orange", "darkblue", "darkgreen", "darkred")) +
labs(color="Configuration") +
theme_bw() +
theme(panel.grid.minor = element_blank()) + theme(legend.position = "bottom") +
scale_x_continuous(breaks = seq(0, 1, 0.1), labels = scales::percent_format()) +
scale_y_continuous(breaks = seq(0, 1, 0.1))
ggsave(filename, width = 8, height = 5)
}
plot.boxplot.clo <- function(mpvalue, filename)
{
grf <- ggplot(mpvalue, aes(participation, closeness)) + geom_boxplot(aes(group = cut_width(participation, 0.1)), color="darkblue") +
theme_bw() +
theme(panel.grid.minor = element_blank()) + theme(legend.position = "bottom") +
scale_x_continuous(breaks = seq(0, 1, 0.1), labels = scales::percent_format())
ggsave(filename, width = 8, height = 5)
}
plot.boxplot.degree <- function(mpvalue, filename, filenameh)
{
grf <- ggplot(mpvalue, aes(participation, degree)) + geom_boxplot(aes(group = cut_width(participation, 0.1)), color="darkblue") +
theme_bw() +
theme(panel.grid.minor = element_blank()) + theme(legend.position = "none") +
scale_x_continuous(breaks = seq(0, 1, 0.1), labels = scales::percent_format())
ggsave(filename, width = 8, height = 5)
t <- mpvalue[mpvalue$participation==0 | mpvalue$participation==1,]
t$participation = paste(t$participation*100, "%")
ggplot(t, aes(x=degree, fill = participation)) +
geom_histogram(binwidth = 1) +
scale_fill_manual(values=c("darkblue", "darkgreen", "darkred")) +
theme_bw() +
theme(panel.grid.minor = element_blank()) + theme(legend.position = "none") +
theme(strip.background = element_rect(fill="orange")) +
facet_wrap(~participation, ncol = 1)
ggsave(filenameh, width = 8, height = 5)
} |
#**************************************
# 1. PV of Annuities #####
#**************************************
# 1.1 function calculating temporary annuity values from age x to retirment age 65 (fixed end)
get_tla <- function(px, i, sx = rep(1, length(px))){
# suppose the age corresponding to px runs from a1 to aN, and f = aN + 1 (eg. age 30:64, f = 65)
# The function computes a..{x, f - x} and s_a..{x, f - x}, x runing from a1 to aN.
# The length of px is f - a1
# Note that the last element is redundant, just used as a place holder.
# inputs:
# px: an vector of composite survivial probs from age x to x + n - 1. Length = n
# i: discount rate, scalar
# sx: salary scale. default is a n vector of 1, meaning no salary scale.
# output:
# tla: an n vector storing the value of temporary life annuities from age x to age x + n - 1.
tla <- numeric(length(px))
n <- length(tla)
for(j in 1:n){
v <- 1/(1 + i)^(0:(n - j)) # dicount vector
if(j < n) pxr <- cumprod(c(1, px[j:(n - 1)])) else pxr = 1 # survival probability to retirment at age x. Note that participant always survives at the beginning of age x
SS <- sx[j:n]/sx[j] # salary scale
tla[j] = sum(SS * v * pxr) # computing annuity value at j
}
return(tla)
}
get_tla(rep(0.98, 65), 0.08) # test the function
# 1.2 function calculating temporary annuity values from a fixed entry age y to x (fixed start)
get_tla2 = function(px, i, sx = rep(1, length(px))){
# Suppose the age corresponding to px runs from a1 to aN, y = a1 (eg. age 30:65, y = 30)
# This function conputes a..{y, x - y} and s_a..{y, x - y}, x ruuning from a1 to aN.
# Note that when x = a1 = y, we define a..{y, 0} = 0. so the first element is always 0.
# For age x > y, the number of years receiviing annuity is x - y, the resulting annuity value will be placed at age x.
# eg1: x = 31, y = 30, annuity ($1) received only once at age 30, but the resulting annuity value will be placed at age 31.
# eg2: x = 65, y = 30, annuity received from age 30 to 64(total 65 years), the resulting annuity value will be placed at age 65
# Note that the last 2 survival rates and last salary scale are redundant in the calculation, they are just used as place holders.
#(calculating the value of annuity running from 30 to 64 only involves survival rate from 30 to 63,
# because the last annuity payment is paid at the begining of 64. )
# inputs:
# px: an vector of composite survivial probs from age x to x + n - 1. Length = n
# i: discount rate, scalar
# sx: salary scale. default is an n vector of 1, meaning no salary scale.
# output:
# tla: an n vector storing the value of temporary life annuities from age x to age x + n - 1.
tla = numeric(length(px))
n = length(tla)
# tla[1] will be kept as 0, next calculate tla[2:n]:
for(j in 1:(n - 1)){
v <- 1/(1 + i)^(0:(j - 1)) # dicount vector
if(j == 1) pxr <- 1 else pxr <- cumprod(c(1, px[1:(j - 1)])) # survival probability to retirment at age x. Note that participant always survives at the beginning of age x
SS <- sx[1:j]/sx[1] # salary scale
tla[j + 1] = sum(SS * v * pxr) # computing annuity value at j;
}
return(tla)
}
# 1.2a A simpler implementation of 1.2
get_tla2a <- function(px, i, sx = rep(1, length(px))){
n <- length(px)
tla <- numeric(n)
v <- 1/(1 + i)
tla[-1] <- cumsum(cumprod(c(1,px[1:(n-2)])* v * sx[1:(n - 1)]/sx[1])/v)
return(tla)
}
get_tla2(rep(0.98, 65), 0.08, rep(1.1, 65)) # test the function
get_tla2a(rep(0.98, 65), 0.08, rep(1.1, 65))# test the function
# 1.3 PVFB of term costs
get_PVFB <- function(px, v, TC){ # present values of subsets of TC (fixed end)
# This function compute the total present value of TC[j:n] at the beginning of time j, with j running from 1 to n.
# The function can be used to calculate PVFB of term costs of ancillary benefits or retirement benefits with multiple
# retirement ages.
# Inputs
# px: numeric vector of length n. Probability of survival at time 1 through n
# v : numeric. discount factor 1/(1 + i)
# TC: numeric vector of length n. A series of term costs. Term costs are valued at the begninning of period.
# Returns
# PVFBs of fixed end contracting windows of TC.
n <- length(px)
PVFB <- sapply(seq_len(n), function(j) ifelse(j == n, TC[j], sum(cumprod(c(1, (px[j:(n - 1)] * v))) * TC[j:n])))
return(PVFB)
}
# 1.4 NC of UC and PUC
get_NC.UC <- function(px, v, TC){
# This function is a variation of get_PVFB. It is used to calculate NC under UC and PUC methods.
# Below we explain the major difference between get_NC.UC and get_PVFB:
# 1. Why TC[(j + 1):n]? Remember NC is the discounted value of benefit accrual. During age x, the individual can
# accrue benefit for age x + 1 to r'', so the corresponding elements in TC are TC[(j + 1):n]. Note that
# TC[j+1] is gx.r(j+1)*qxr(j+1)*ax(j+1) in PUC.
# 2. Why start discounting from the 1st element? Since at j the individual starts accruing benefit from j + 1,
# we need to discount the value in j + 1.
# Note The last elements (at age r'') of the result is NA by construction.
# px must be survival probability from min(age) to r''.
# TC must be defined as
# gx.r(x) * qxr(x) * ax(x), x running from y (entry age) to r'' (eg. 20 to 65 in Winklevoss book)
# Bx(x)/(x - y) * gx.r(x) * qxr(x) * ax(x), x running from entry age (y) to r'' (0 when x = y)
n <- length(px) # n is r''
Fun_NC <- function(j) ifelse(j == n, NA, sum(cumprod(px[j:(n - 1)]) * v^(1:(n-j)) * TC[(j + 1):n]))
NC <- sapply(seq_len(n), Fun_NC)
return(NC)
}
# 1.5 AL of PUC
get_AL.PUC <- function(px, v, TC){
# This function is a variation of get_PVFB. It is used to calculate AL under PUC methods.
# Note that the only difference between get_AL.PUC and get_PVFB is that TC[j] is multiplied by (j - 1)
# Note that y(entry age) corresponds to index 1 and age x corresponds to index j, so at age x the individual
# has been accruing benefits for x - y years, which is equal to j - 1 years. (eg. Assuming y = 20, then when x = 21 and j = 2 the
# individual have accrued benefits for 1 year (x - y = 21 - 1 and j - 1 = 2 - 1).
# TC must be defined the same way as in get_NC.UC.
# the first element (age y) should be zero, the last element should be the same as the last element in TC.
n <- length(px) # n is r'' - y + 1
AL <- sapply(seq_len(n),
function(j) ifelse(j == n, TC[j]*(j-1), sum(cumprod(c(1, (px[j:(n - 1)] * v))) * TC[j:n] * (j - 1)))
)
return(AL)
}
#**************************************
# 2. Amortization Functions #####
#**************************************
pmt <- function(p, i, n, end = FALSE){
# amortization function with constant payment at each period
# p = principle, i = interest rate, n = periods.
# end: , if TRUE, payment at the end of period.
if(end) p <- p*(1 + i)
a_n <- (1 - (1 + i)^(-n))/(1 - 1/(1 + i))
pmt <- p / a_n
return(pmt)
}
# pmt(100, 0.08, 10)
# pmt2(100, 0.08, 10, TRUE)
# pmt2(-100, 0.08, 10)
gaip <- function(p, i, n, g, end = FALSE){
# p=principal, i=interest rate, n=periods, g=growth rate in payments
# calculating gaip directly
# end: , if TRUE, payment at the end of period.
if(end) p <- p*(1 + i)
k <- (1 + g)/(1 + i)
a_sn <- (1 - k^n )/(1 - k)
pmt <- p/a_sn
return(pmt)
}
# gaip2(100, 0.08, 10, 0.04)
# gaip3(100, 0.08, 10, 0.02, end = TRUE)
# Constant dollar amortization method
amort_cd <- function(p, i, m, end = FALSE) rep(pmt(p, i, m, end), m)
# Constant percent amortization method
amort_cp <- function(p, i, m, g, end = FALSE) gaip(p, i, m, g, end)*(g + 1)^(1:m - 1)
# Strait line method #
amort_sl <- function(p, i, m, end = FALSE){
# Straitline amortization method
# See Winklevoss(1993, p101)
if(end){
sl <- i*(p - p*(0:(m - 1))/m) + p/m
} else {
d <- 1/(1+i)
sl <- d*(p - p*(1:m)/m) + p/m}
return(sl)
}
# Test the functions
amort_cd(100, 0.08, 10, F)
amort_cp(100, 0.08, 10, 0.05, F)
amort_sl(100, 0.08, 10, F)
# Function for choosing amortization methods
amort_LG <- function(p, i, m, g, end = FALSE, method = "cd"){
# amortize the gain/loss using specified amortization method
switch(method,
cd = amort_cd(p, i ,m, end),
cp = amort_cp(p, i, m, g, end),
sl = amort_sl(p, i, m, end)
)
}
#********************************
# 3.Utility functions ####
#********************************
cton <- function (cvar) as.numeric(gsub("[ ,$%]", "", cvar)) # character to numeric, eliminating "," "$" "%". chars will become NA
ht <- function (df, nrecs=6) {print(head(df, nrecs)); print(tail(df, nrecs))} # head tail
memory<-function(maxnobjs=5){
# function for getting the sizes of objects in memory
objs<-ls(envir=globalenv())
nobjs<-min(length(objs),maxnobjs)
tmp<-as.data.frame(sapply(objs, function(x) object.size(get(x)))/1048600)
tmp<-data.frame(name=row.names(tmp), sizeMB=tmp[,1])
tmp<-tmp[order(-tmp$sizeMB),]
tmp$sizeMB<-formatC(tmp$sizeMB,format="f",digits=2,big.mark=",",preserve.width="common")
print(paste("Memory available: ",memory.size(NA),sep=""))
print(paste("Memory in use before: ",memory.size(),sep=""))
print("Memory for selected objects: ")
print(head(tmp,nobjs))
print(gc())
print(paste("Memory in use after: ",memory.size(),sep=""))
}
na2zero <- function(x){x[is.na(x)] <- 0 ;return(x)}
f2n <- function(x) as.numeric(levels(x)[x])
## spline smoothing
splong<-function(df,fillvar,fitrange=NULL, method = "natural"){
# df should have only 3 columns: fillvar, nonfillvar [in either order], and value
# or just 2 columns, with no nonfillvar
# last column ALWAYS must be the value var
valvar<-names(df)[length(names(df))]
nonfillvar<-setdiff(names(df),c(fillvar,valvar))
f<-function(x) {
if(is.null(fitrange)) fitrange<-min(x[,fillvar]):max(x[,fillvar])
spl<-spline(x[,fillvar], x[,valvar], xout=fitrange, method = method)
dfout<-data.frame(x=spl$x, y=spl$y)
names(dfout)<-c(fillvar,valvar)
return(dfout)
}
if(length(nonfillvar)>0) dfl2<-ddply(df,c(nonfillvar),f) else dfl2<-f(df)
return(dfl2)
}
# pmt <- function(p, i, n){
# # amortization function, with payment at the end of period.
# # p = principle, i = interest rate, n = periods.
# pmt <- p * (1 + i)^n * i/((1 + i)^n - 1)
# return(pmt)
# }
# gaip2 <- function(p, i, n, g){
# # p=principal, i=interest rate, n=periods, g=growth rate in payments
# # calculating gaip directly
# # end: , if TRUE, payment at the end of period.
# #if(end) p <- p*(1 + i)
# k <- (1 + i)/(1 + g)
# gaf <- (1 + i) * (1 - k)/(k * (k^(-n) - 1))
# return(gaf*p)
# }
| /Functions.R | no_license | donboyd5/Model_Main | R | false | false | 10,975 | r |
#**************************************
# 1. PV of Annuities #####
#**************************************
# 1.1 function calculating temporary annuity values from age x to retirment age 65 (fixed end)
get_tla <- function(px, i, sx = rep(1, length(px))){
# suppose the age corresponding to px runs from a1 to aN, and f = aN + 1 (eg. age 30:64, f = 65)
# The function computes a..{x, f - x} and s_a..{x, f - x}, x runing from a1 to aN.
# The length of px is f - a1
# Note that the last element is redundant, just used as a place holder.
# inputs:
# px: an vector of composite survivial probs from age x to x + n - 1. Length = n
# i: discount rate, scalar
# sx: salary scale. default is a n vector of 1, meaning no salary scale.
# output:
# tla: an n vector storing the value of temporary life annuities from age x to age x + n - 1.
tla <- numeric(length(px))
n <- length(tla)
for(j in 1:n){
v <- 1/(1 + i)^(0:(n - j)) # dicount vector
if(j < n) pxr <- cumprod(c(1, px[j:(n - 1)])) else pxr = 1 # survival probability to retirment at age x. Note that participant always survives at the beginning of age x
SS <- sx[j:n]/sx[j] # salary scale
tla[j] = sum(SS * v * pxr) # computing annuity value at j
}
return(tla)
}
get_tla(rep(0.98, 65), 0.08) # test the function
# 1.2 function calculating temporary annuity values from a fixed entry age y to x (fixed start)
get_tla2 = function(px, i, sx = rep(1, length(px))){
# Suppose the age corresponding to px runs from a1 to aN, y = a1 (eg. age 30:65, y = 30)
# This function conputes a..{y, x - y} and s_a..{y, x - y}, x ruuning from a1 to aN.
# Note that when x = a1 = y, we define a..{y, 0} = 0. so the first element is always 0.
# For age x > y, the number of years receiviing annuity is x - y, the resulting annuity value will be placed at age x.
# eg1: x = 31, y = 30, annuity ($1) received only once at age 30, but the resulting annuity value will be placed at age 31.
# eg2: x = 65, y = 30, annuity received from age 30 to 64(total 65 years), the resulting annuity value will be placed at age 65
# Note that the last 2 survival rates and last salary scale are redundant in the calculation, they are just used as place holders.
#(calculating the value of annuity running from 30 to 64 only involves survival rate from 30 to 63,
# because the last annuity payment is paid at the begining of 64. )
# inputs:
# px: an vector of composite survivial probs from age x to x + n - 1. Length = n
# i: discount rate, scalar
# sx: salary scale. default is an n vector of 1, meaning no salary scale.
# output:
# tla: an n vector storing the value of temporary life annuities from age x to age x + n - 1.
tla = numeric(length(px))
n = length(tla)
# tla[1] will be kept as 0, next calculate tla[2:n]:
for(j in 1:(n - 1)){
v <- 1/(1 + i)^(0:(j - 1)) # dicount vector
if(j == 1) pxr <- 1 else pxr <- cumprod(c(1, px[1:(j - 1)])) # survival probability to retirment at age x. Note that participant always survives at the beginning of age x
SS <- sx[1:j]/sx[1] # salary scale
tla[j + 1] = sum(SS * v * pxr) # computing annuity value at j;
}
return(tla)
}
# 1.2a A simpler implementation of 1.2
get_tla2a <- function(px, i, sx = rep(1, length(px))){
n <- length(px)
tla <- numeric(n)
v <- 1/(1 + i)
tla[-1] <- cumsum(cumprod(c(1,px[1:(n-2)])* v * sx[1:(n - 1)]/sx[1])/v)
return(tla)
}
get_tla2(rep(0.98, 65), 0.08, rep(1.1, 65)) # test the function
get_tla2a(rep(0.98, 65), 0.08, rep(1.1, 65))# test the function
# 1.3 PVFB of term costs
get_PVFB <- function(px, v, TC){ # present values of subsets of TC (fixed end)
# This function compute the total present value of TC[j:n] at the beginning of time j, with j running from 1 to n.
# The function can be used to calculate PVFB of term costs of ancillary benefits or retirement benefits with multiple
# retirement ages.
# Inputs
# px: numeric vector of length n. Probability of survival at time 1 through n
# v : numeric. discount factor 1/(1 + i)
# TC: numeric vector of length n. A series of term costs. Term costs are valued at the begninning of period.
# Returns
# PVFBs of fixed end contracting windows of TC.
n <- length(px)
PVFB <- sapply(seq_len(n), function(j) ifelse(j == n, TC[j], sum(cumprod(c(1, (px[j:(n - 1)] * v))) * TC[j:n])))
return(PVFB)
}
# 1.4 NC of UC and PUC
get_NC.UC <- function(px, v, TC){
# This function is a variation of get_PVFB. It is used to calculate NC under UC and PUC methods.
# Below we explain the major difference between get_NC.UC and get_PVFB:
# 1. Why TC[(j + 1):n]? Remember NC is the discounted value of benefit accrual. During age x, the individual can
# accrue benefit for age x + 1 to r'', so the corresponding elements in TC are TC[(j + 1):n]. Note that
# TC[j+1] is gx.r(j+1)*qxr(j+1)*ax(j+1) in PUC.
# 2. Why start discounting from the 1st element? Since at j the individual starts accruing benefit from j + 1,
# we need to discount the value in j + 1.
# Note The last elements (at age r'') of the result is NA by construction.
# px must be survival probability from min(age) to r''.
# TC must be defined as
# gx.r(x) * qxr(x) * ax(x), x running from y (entry age) to r'' (eg. 20 to 65 in Winklevoss book)
# Bx(x)/(x - y) * gx.r(x) * qxr(x) * ax(x), x running from entry age (y) to r'' (0 when x = y)
n <- length(px) # n is r''
Fun_NC <- function(j) ifelse(j == n, NA, sum(cumprod(px[j:(n - 1)]) * v^(1:(n-j)) * TC[(j + 1):n]))
NC <- sapply(seq_len(n), Fun_NC)
return(NC)
}
# 1.5 AL of PUC
get_AL.PUC <- function(px, v, TC){
# This function is a variation of get_PVFB. It is used to calculate AL under PUC methods.
# Note that the only difference between get_AL.PUC and get_PVFB is that TC[j] is multiplied by (j - 1)
# Note that y(entry age) corresponds to index 1 and age x corresponds to index j, so at age x the individual
# has been accruing benefits for x - y years, which is equal to j - 1 years. (eg. Assuming y = 20, then when x = 21 and j = 2 the
# individual have accrued benefits for 1 year (x - y = 21 - 1 and j - 1 = 2 - 1).
# TC must be defined the same way as in get_NC.UC.
# the first element (age y) should be zero, the last element should be the same as the last element in TC.
n <- length(px) # n is r'' - y + 1
AL <- sapply(seq_len(n),
function(j) ifelse(j == n, TC[j]*(j-1), sum(cumprod(c(1, (px[j:(n - 1)] * v))) * TC[j:n] * (j - 1)))
)
return(AL)
}
#**************************************
# 2. Amortization Functions #####
#**************************************
pmt <- function(p, i, n, end = FALSE){
# amortization function with constant payment at each period
# p = principle, i = interest rate, n = periods.
# end: , if TRUE, payment at the end of period.
if(end) p <- p*(1 + i)
a_n <- (1 - (1 + i)^(-n))/(1 - 1/(1 + i))
pmt <- p / a_n
return(pmt)
}
# pmt(100, 0.08, 10)
# pmt2(100, 0.08, 10, TRUE)
# pmt2(-100, 0.08, 10)
gaip <- function(p, i, n, g, end = FALSE){
# p=principal, i=interest rate, n=periods, g=growth rate in payments
# calculating gaip directly
# end: , if TRUE, payment at the end of period.
if(end) p <- p*(1 + i)
k <- (1 + g)/(1 + i)
a_sn <- (1 - k^n )/(1 - k)
pmt <- p/a_sn
return(pmt)
}
# gaip2(100, 0.08, 10, 0.04)
# gaip3(100, 0.08, 10, 0.02, end = TRUE)
# Constant dollar amortization method
amort_cd <- function(p, i, m, end = FALSE) rep(pmt(p, i, m, end), m)
# Constant percent amortization method
amort_cp <- function(p, i, m, g, end = FALSE) gaip(p, i, m, g, end)*(g + 1)^(1:m - 1)
# Strait line method #
amort_sl <- function(p, i, m, end = FALSE){
# Straitline amortization method
# See Winklevoss(1993, p101)
if(end){
sl <- i*(p - p*(0:(m - 1))/m) + p/m
} else {
d <- 1/(1+i)
sl <- d*(p - p*(1:m)/m) + p/m}
return(sl)
}
# Test the functions
amort_cd(100, 0.08, 10, F)
amort_cp(100, 0.08, 10, 0.05, F)
amort_sl(100, 0.08, 10, F)
# Function for choosing amortization methods
amort_LG <- function(p, i, m, g, end = FALSE, method = "cd"){
# amortize the gain/loss using specified amortization method
switch(method,
cd = amort_cd(p, i ,m, end),
cp = amort_cp(p, i, m, g, end),
sl = amort_sl(p, i, m, end)
)
}
#********************************
# 3.Utility functions ####
#********************************
cton <- function (cvar) as.numeric(gsub("[ ,$%]", "", cvar)) # character to numeric, eliminating "," "$" "%". chars will become NA
ht <- function (df, nrecs=6) {print(head(df, nrecs)); print(tail(df, nrecs))} # head tail
memory<-function(maxnobjs=5){
# function for getting the sizes of objects in memory
objs<-ls(envir=globalenv())
nobjs<-min(length(objs),maxnobjs)
tmp<-as.data.frame(sapply(objs, function(x) object.size(get(x)))/1048600)
tmp<-data.frame(name=row.names(tmp), sizeMB=tmp[,1])
tmp<-tmp[order(-tmp$sizeMB),]
tmp$sizeMB<-formatC(tmp$sizeMB,format="f",digits=2,big.mark=",",preserve.width="common")
print(paste("Memory available: ",memory.size(NA),sep=""))
print(paste("Memory in use before: ",memory.size(),sep=""))
print("Memory for selected objects: ")
print(head(tmp,nobjs))
print(gc())
print(paste("Memory in use after: ",memory.size(),sep=""))
}
na2zero <- function(x){x[is.na(x)] <- 0 ;return(x)}
f2n <- function(x) as.numeric(levels(x)[x])
## spline smoothing
splong<-function(df,fillvar,fitrange=NULL, method = "natural"){
# df should have only 3 columns: fillvar, nonfillvar [in either order], and value
# or just 2 columns, with no nonfillvar
# last column ALWAYS must be the value var
valvar<-names(df)[length(names(df))]
nonfillvar<-setdiff(names(df),c(fillvar,valvar))
f<-function(x) {
if(is.null(fitrange)) fitrange<-min(x[,fillvar]):max(x[,fillvar])
spl<-spline(x[,fillvar], x[,valvar], xout=fitrange, method = method)
dfout<-data.frame(x=spl$x, y=spl$y)
names(dfout)<-c(fillvar,valvar)
return(dfout)
}
if(length(nonfillvar)>0) dfl2<-ddply(df,c(nonfillvar),f) else dfl2<-f(df)
return(dfl2)
}
# pmt <- function(p, i, n){
# # amortization function, with payment at the end of period.
# # p = principle, i = interest rate, n = periods.
# pmt <- p * (1 + i)^n * i/((1 + i)^n - 1)
# return(pmt)
# }
# gaip2 <- function(p, i, n, g){
# # p=principal, i=interest rate, n=periods, g=growth rate in payments
# # calculating gaip directly
# # end: , if TRUE, payment at the end of period.
# #if(end) p <- p*(1 + i)
# k <- (1 + i)/(1 + g)
# gaf <- (1 + i) * (1 - k)/(k * (k^(-n) - 1))
# return(gaf*p)
# }
|
##' @importFrom dplyr full_join
##' @importFrom tibble data_frame
##' @importFrom dplyr select_
##' @method full_join treedata
##' @export
full_join.treedata <- function(x, y, by = NULL,
copy = FALSE, suffix = c(".x", ".y"), ...) {
by <- match.arg(by, c("node", "label"))
y <- as_data_frame(y)
if (by == "label") {
ntip <- Ntip(x)
N <- Nnode2(x)
label <- rep(NA, N)
label[1:ntip] <- x@phylo[["tip.label"]]
if (!is.null(x@phylo$node.label)) {
label[(ntip+1):N] <- x@phylo$node.label
}
lab <- data_frame(node = 1:N, label = label)
y <- full_join(lab, y, by = "label") %>% select_(~ -label)
}
if (nrow(x@extraInfo) == 0) {
x@extraInfo <- y
} else {
x@extraInfo %<>% full_join(y, by = "node", copy = copy, suffix = suffix)
}
return(x)
}
| /R/full-join.R | no_license | tbradley1013/treeio | R | false | false | 890 | r | ##' @importFrom dplyr full_join
##' @importFrom tibble data_frame
##' @importFrom dplyr select_
##' @method full_join treedata
##' @export
full_join.treedata <- function(x, y, by = NULL,
copy = FALSE, suffix = c(".x", ".y"), ...) {
by <- match.arg(by, c("node", "label"))
y <- as_data_frame(y)
if (by == "label") {
ntip <- Ntip(x)
N <- Nnode2(x)
label <- rep(NA, N)
label[1:ntip] <- x@phylo[["tip.label"]]
if (!is.null(x@phylo$node.label)) {
label[(ntip+1):N] <- x@phylo$node.label
}
lab <- data_frame(node = 1:N, label = label)
y <- full_join(lab, y, by = "label") %>% select_(~ -label)
}
if (nrow(x@extraInfo) == 0) {
x@extraInfo <- y
} else {
x@extraInfo %<>% full_join(y, by = "node", copy = copy, suffix = suffix)
}
return(x)
}
|
library(tidyverse)
library(here)
library(lubridate)
library(tsibble)
# Plot all trees ------------------------------------------------------------
all_trees <- "static/talk/data/scbi.stem3.csv" %>%
here() %>%
read_csv()
all_trees
ggplot(all_trees, aes(x = gx, y = gy, col = sp)) +
geom_point(size = 0.5) +
coord_fixed() +
labs(x = "x-coordinate (meters)", y = "y-coordinate (meters)", col = "species",
title = "Census 2018: 72,555 cataloged trees") +
annotate("point", x = 147, y = 620, size = 4)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig0.png", width = 4*2, height = 5*2)
all_trees %>%
filter(tag == 082422)
# 5-parameter model ------------------------------------------------------------
generalized_logistic_function <- function(params, doy) {
L <- params[1]
K <- params[2]
doy.ip <- params[3]
r <- params[4]
theta <- params[5]
dbh <- L + ((K - L) / (1 + 1/theta * exp(-(r * (doy - doy.ip) / theta)) ^ theta))
return(dbh)
}
K <- 13
L <- 15
doy.ip <- 200
r <- 0.075
theta <- 1
sigma <- 0.05
params <- c(K, L, doy.ip, r, theta)
set.seed(79)
observed_values <- tibble(
doy = seq(from = 1, to = 365, by = 5),
dbh = generalized_logistic_function(params, doy)
) %>%
mutate(dbh = dbh + rnorm(n(), sd = sigma))
# Not a great fit!
base_plot <- ggplot() +
geom_point(data = observed_values, mapping = aes(x = doy, y = dbh)) +
labs(x = "Day of year", y = "Diameter at breast height", title = "Idealized example of dendroband measurements")
base_plot
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig1.png",width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig2.png", width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75) +
geom_hline(yintercept = L, linetype = "dashed", size = 0.75)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig3.png",width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75) +
geom_hline(yintercept = L, linetype = "dashed", size = 0.75) +
geom_vline(xintercept = doy.ip, linetype = "dashed", size = 0.75)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig4.png",width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75) +
geom_hline(yintercept = L, linetype = "dashed", size = 0.75) +
geom_vline(xintercept = doy.ip, linetype = "dashed", size = 0.75) +
geom_abline(slope = r, intercept = 14 - r*doy.ip, size = 0.75)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig5.png",width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75, col = "grey") +
geom_hline(yintercept = L, linetype = "dashed", size = 0.75, col = "grey") +
geom_vline(xintercept = doy.ip, linetype = "dashed", size = 0.75, col = "grey") +
geom_abline(slope = r, intercept = 14 - r*doy.ip, size = 0.75, col = "grey") +
stat_function(fun = generalized_logistic_function, args = list(params = params), col = "red", n = 500, size = 1)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig6.png",width = 8, height = 4.5)
# Time series ------------------------------------------------------------
# Copied from 2020/9/25 Friday SCBI talk
litu_stem <- "static/talk/data/all_stems.csv" %>%
here() %>%
read_csv() %>%
# Create date variable
unite("date", c(year, month, day), sep = "-") %>%
mutate(date = ymd(date)) %>%
filter(tag %in% c(082422)) %>%
dplyr::select(tag, date, measure) %>%
# Convert to tsibble = time series tibble data type
# Not sure what to make of regular vs irregular
as_tsibble(index = date, regular = TRUE) %>%
# Create growth variable by taking differences in measurements
mutate(
measure_before = lag(measure),
growth = measure - measure_before
)
ggplot(litu_stem, aes(x = date, y = measure)) +
geom_line() +
scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
labs(x = "date", y = "measurement", title = "Tulip Poplar: Tag 082422")
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig7.png",width = 8, height = 4.5)
litu_stem_growth_plot <-
ggplot(litu_stem, aes(x = date, y = growth)) +
geom_hline(yintercept = 0, linetype = "dashed", col = "grey") +
scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
labs(x = "date", y = "growth", title = "Tulip Poplar: Tag 082422") +
geom_line()
litu_stem_growth_plot
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig8.png",width = 8, height = 4.5)
litu_stem_growth_plot +
geom_smooth(se = FALSE, span = 0.1) +
geom_smooth(se = FALSE, method = "lm", col = "red")
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig9.png",width = 8, height = 4.5)
litu_stem_growth_plot +
geom_vline(xintercept = as.Date("2017-07-01"), linetype = "dashed", col = "red", size = 1)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig10.png",width = 8, height = 4.5)
litu_stem_growth_plot +
geom_vline(xintercept = as.Date("2020-07-01"), linetype = "dashed", col = "red", size = 1) +
scale_x_date(date_breaks = "1 year", date_labels = "%Y", limits = as.Date(c(NA, "2020-08-01")))
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig11.png",width = 8, height = 4.5)
| /static/talk/2020-09-30_ES&P.R | no_license | rudeboybert/rudeboybert | R | false | false | 5,319 | r | library(tidyverse)
library(here)
library(lubridate)
library(tsibble)
# Plot all trees ------------------------------------------------------------
all_trees <- "static/talk/data/scbi.stem3.csv" %>%
here() %>%
read_csv()
all_trees
ggplot(all_trees, aes(x = gx, y = gy, col = sp)) +
geom_point(size = 0.5) +
coord_fixed() +
labs(x = "x-coordinate (meters)", y = "y-coordinate (meters)", col = "species",
title = "Census 2018: 72,555 cataloged trees") +
annotate("point", x = 147, y = 620, size = 4)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig0.png", width = 4*2, height = 5*2)
all_trees %>%
filter(tag == 082422)
# 5-parameter model ------------------------------------------------------------
generalized_logistic_function <- function(params, doy) {
L <- params[1]
K <- params[2]
doy.ip <- params[3]
r <- params[4]
theta <- params[5]
dbh <- L + ((K - L) / (1 + 1/theta * exp(-(r * (doy - doy.ip) / theta)) ^ theta))
return(dbh)
}
K <- 13
L <- 15
doy.ip <- 200
r <- 0.075
theta <- 1
sigma <- 0.05
params <- c(K, L, doy.ip, r, theta)
set.seed(79)
observed_values <- tibble(
doy = seq(from = 1, to = 365, by = 5),
dbh = generalized_logistic_function(params, doy)
) %>%
mutate(dbh = dbh + rnorm(n(), sd = sigma))
# Not a great fit!
base_plot <- ggplot() +
geom_point(data = observed_values, mapping = aes(x = doy, y = dbh)) +
labs(x = "Day of year", y = "Diameter at breast height", title = "Idealized example of dendroband measurements")
base_plot
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig1.png",width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig2.png", width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75) +
geom_hline(yintercept = L, linetype = "dashed", size = 0.75)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig3.png",width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75) +
geom_hline(yintercept = L, linetype = "dashed", size = 0.75) +
geom_vline(xintercept = doy.ip, linetype = "dashed", size = 0.75)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig4.png",width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75) +
geom_hline(yintercept = L, linetype = "dashed", size = 0.75) +
geom_vline(xintercept = doy.ip, linetype = "dashed", size = 0.75) +
geom_abline(slope = r, intercept = 14 - r*doy.ip, size = 0.75)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig5.png",width = 8, height = 4.5)
base_plot +
geom_hline(yintercept = K, linetype = "dashed", size = 0.75, col = "grey") +
geom_hline(yintercept = L, linetype = "dashed", size = 0.75, col = "grey") +
geom_vline(xintercept = doy.ip, linetype = "dashed", size = 0.75, col = "grey") +
geom_abline(slope = r, intercept = 14 - r*doy.ip, size = 0.75, col = "grey") +
stat_function(fun = generalized_logistic_function, args = list(params = params), col = "red", n = 500, size = 1)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig6.png",width = 8, height = 4.5)
# Time series ------------------------------------------------------------
# Copied from 2020/9/25 Friday SCBI talk
litu_stem <- "static/talk/data/all_stems.csv" %>%
here() %>%
read_csv() %>%
# Create date variable
unite("date", c(year, month, day), sep = "-") %>%
mutate(date = ymd(date)) %>%
filter(tag %in% c(082422)) %>%
dplyr::select(tag, date, measure) %>%
# Convert to tsibble = time series tibble data type
# Not sure what to make of regular vs irregular
as_tsibble(index = date, regular = TRUE) %>%
# Create growth variable by taking differences in measurements
mutate(
measure_before = lag(measure),
growth = measure - measure_before
)
ggplot(litu_stem, aes(x = date, y = measure)) +
geom_line() +
scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
labs(x = "date", y = "measurement", title = "Tulip Poplar: Tag 082422")
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig7.png",width = 8, height = 4.5)
litu_stem_growth_plot <-
ggplot(litu_stem, aes(x = date, y = growth)) +
geom_hline(yintercept = 0, linetype = "dashed", col = "grey") +
scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
labs(x = "date", y = "growth", title = "Tulip Poplar: Tag 082422") +
geom_line()
litu_stem_growth_plot
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig8.png",width = 8, height = 4.5)
litu_stem_growth_plot +
geom_smooth(se = FALSE, span = 0.1) +
geom_smooth(se = FALSE, method = "lm", col = "red")
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig9.png",width = 8, height = 4.5)
litu_stem_growth_plot +
geom_vline(xintercept = as.Date("2017-07-01"), linetype = "dashed", col = "red", size = 1)
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig10.png",width = 8, height = 4.5)
litu_stem_growth_plot +
geom_vline(xintercept = as.Date("2020-07-01"), linetype = "dashed", col = "red", size = 1) +
scale_x_date(date_breaks = "1 year", date_labels = "%Y", limits = as.Date(c(NA, "2020-08-01")))
ggsave(filename = "static/talk/figure/2020-09-30_ES&P_Fig11.png",width = 8, height = 4.5)
|
library(ape)
library(igraph)
setwd(paste(getwd(), "./listResults/toEvaluate-music-gzip", sep="/"))
listValues = read.table("data.csv", header = FALSE)$V1
listFilenames = read.table("names.csv", header = FALSE)$V1
numVal = length(listFilenames)
data = matrix(data = listValues, nrow=numVal, ncol=numVal, dimnames=list(listFilenames,listFilenames))
phylo_tree = as.phylo(hclust(as.dist(data)))
graph_edges = phylo_tree$edge
graph_net = graph.edgelist(graph_edges)
l2 = as_adj_list(graph_net, mode="out")
library(RJSONIO)
write(toJSON(l2), "test.json")
| /listResults/music-gzip/generate.r | no_license | W95Psp/NID-results | R | false | false | 551 | r |
library(ape)
library(igraph)
setwd(paste(getwd(), "./listResults/toEvaluate-music-gzip", sep="/"))
listValues = read.table("data.csv", header = FALSE)$V1
listFilenames = read.table("names.csv", header = FALSE)$V1
numVal = length(listFilenames)
data = matrix(data = listValues, nrow=numVal, ncol=numVal, dimnames=list(listFilenames,listFilenames))
phylo_tree = as.phylo(hclust(as.dist(data)))
graph_edges = phylo_tree$edge
graph_net = graph.edgelist(graph_edges)
l2 = as_adj_list(graph_net, mode="out")
library(RJSONIO)
write(toJSON(l2), "test.json")
|
# This funtion creates 5 sets of N-Grams. Each containing the aggregate frequency of all N-grams (N = 1 to 5)
# Input this this funtion is the N (order of the gram) that needs to be generated
# This routine used the Corpus that has already been saved via Obtain_Data.R routine
getProfanityWords <- function(corpus) {
profanityFileName <- "profanity.txt"
if (!file.exists(profanityFileName)) {
profanity.url <- "https://raw.githubusercontent.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/master/en"
download.file(profanity.url, destfile = profanityFileName, method = "curl")
}
if (sum(ls() == "profanity") < 1) {
profanity <- read.csv(profanityFileName, header = FALSE, stringsAsFactors = FALSE)
profanity <- profanity$V1
profanity <- profanity[1:length(profanity)-1]
}
profanity
}
Create_Ngrams <- function(N)
{
# Check the user input. Currently only 1-5 grams are supported
if (N > 5 && N < 1) stop ("Fatal Error. N should be between 1 and 5")
# Load Packages
library(tm)
library(RWeka)
library(reshape2)
library(slam)
library(doParallel)
library(tau)
library(data.table)
library(stringr)
library(quanteda)
# Register for Parellel Processing
registerDoParallel(4)
jobcluster <- makeCluster(detectCores())
invisible(clusterEvalQ(jobcluster, library(tm)))
invisible(clusterEvalQ(jobcluster, library(RWeka)))
invisible(clusterEvalQ(jobcluster, library(reshape2)))
invisible(clusterEvalQ(jobcluster, library(slam)))
options(mc.cores = 4)
# Clear unused memory
gc()
if (N != 1)
{
load("./Swiftkey/with_twitter/1-Grams.rds")
if(!exists("df_all")) {stop("Please first load the 1-Grams")}
df1_all <- df_all
rm(df_all)
df1_all <- as.data.table(df1_all)
setkey(df1_all, word)
# Load Data - Corpus which has already been created by "Obtain_Data.R" routine
load("./Swiftkey/Corp_all.RData")
# Create N-Gram tokenizer control funtion
NgramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = N, max = N))
# Create the Document Term Matrix
dtm <- DocumentTermMatrix(Corp, control = list(tokenize = NgramTokenizer))
# Clear Unused Memory
rm(Corp_sample)
gc()
# Status
print("Stage 1 Complete")
# Get the term frequencies Matrix
freq_all <- rollup(dtm, 1, na.rm=TRUE, FUN = sum)
# Clear Unused Memory
rm(dtm)
gc()
# Status
print("Stage 2 Complete")
# Aggregate the Frequencies
df_all <- melt(apply(freq_all , 2, sum))
# Clear unused Memory
rm(freq_all)
gc()
# Print number if rows processed
print(nrow(df_all))
# Status
print("Stage 3 Complete")
# Format Data to Split N Grams into N Words , 1 each per column
df_all$grams <- rownames(df_all)
df_all <- as.data.table(df_all)
} else {
# Create the custom Data Formatting Funtions
removeNonAsciiChars <- function(x) iconv(x, "latin1", "ASCII", sub="")
removeHashtags <- function(x) gsub("\\B#\\S+\\b","", x)
removeUrls <- function(x) gsub("http[s]?://.*\\S+","",x)
removeSites <- function(x) gsub("www\\..*\\.[com|edu|net|biz]","",x)
# Read Data from Source - We will only use the blog and news data
# Twitter Data uses manu non-english words which arent appropriate for prediction
data_blogs_all <- readLines("C:/Users/nithsubr/Documents/Swiftkey/en_US.blogs.txt")
data_news_all <- readLines("C:/Users/nithsubr/Documents/Swiftkey/en_US.news.txt")
data_twitter_all <- readLines("C:/Users/nithsubr/Documents/Swiftkey/en_US.twitter.txt")
data <- sample(c(data_blogs_all, data_news_all, data_twitter_all))
rm(data_blogs_all)
rm(data_news_all)
rm(data_twitter_all)
gc()
# Status
print("Stage 1 Complete")
data <- gsub("*[[:digit:]]*", "", data)
data <- gsub("*[[:punct:]]*", "", data)
data <- removeNonAsciiChars(data)
data <- removeHashtags(data)
data <- removeUrls(data)
data <- removeSites(data)
data <- str_trim(data, side = c("both", "left", "right"))
# Status
print("Stage 2 Complete")
dtm <- dfm(data, toLower = TRUE, removeNumbers = TRUE, removePunct = TRUE, removeSeparators = TRUE, removeTwitter = TRUE)
# Clear unused memory
rm(data)
gc()
df_all <- data.table(grams = features(dtm), value = colSums(dtm))
df_all <- df_all[order(df_all$grams), ]
rm(dtm)
# Status
print("Stage 3 Complete")
}
if (N == 1)
{
df_all <- df_all[order(df_all$grams), ]
df_all$id <- 1:nrow(df_all)
names(df_all) <- c("word", "value", "id")
}
if (N == 2)
{
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[1])
setkey(df_all, word)
word_1 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_1 = word_1$id)
rm(word_1)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[2])
setkey(df_all, word)
pred <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, pred = pred$id)
rm(pred)
df_all <- df_all[, c("value", "word_1", "pred"), with = FALSE]
df_all <- df_all[order(df_all$word_1,-df_all$value), ]
}
if (N == 3)
{
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[1])
setkey(df_all, word)
word_1 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_1 = word_1$id)
rm(word_1)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[2])
setkey(df_all, word)
word_2 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_2 = word_2$id)
rm(word_2)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[3])
setkey(df_all, word)
pred <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, pred = pred$id)
rm(pred)
df_all <- df_all[, c("value", "word_1", "word_2", "pred"), with = FALSE]
df_all <- df_all[order(df_all$word_1, df_all$word_2, -df_all$value), ]
}
if (N == 4)
{
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[1])
setkey(df_all, word)
word_1 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_1 = word_1$id)
rm(word_1)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[2])
setkey(df_all, word)
word_2 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_2 = word_2$id)
rm(word_2)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[3])
setkey(df_all, word)
word_3 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_3 = word_3$id)
rm(word_3)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[4])
setkey(df_all, word)
pred <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, pred = pred$id)
rm(pred)
df_all <- df_all[, c("value", "word_1", "word_2", "word_3", "pred"), with = FALSE]
df_all <- df_all[order(df_all$word_1, df_all$word_2, df_all$word_3, -df_all$value), ]
}
if (N == 5)
{
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[1])
setkey(df_all, word)
word_1 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_1 = word_1$id)
rm(word_1)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[2])
setkey(df_all, word)
word_2 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_2 = word_2$id)
rm(word_2)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[3])
setkey(df_all, word)
word_3 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_3 = word_3$id)
rm(word_3)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[4])
setkey(df_all, word)
word_4 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_4 = word_4$id)
rm(word_4)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[5])
setkey(df_all, word)
pred <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, pred = pred$id)
rm(pred)
df_all <- df_all[, c("value", "word_1", "word_2", "word_3", "word_4", "pred"), with = FALSE]
df_all <- df_all[order(df_all$word_1, df_all$word_2, df_all$word_3, df_all$word_4, -df_all$value), ]
}
# Print number if rows saved
# print(nrow(df_all))
# Store the Data on disk
filename <- paste("./Swiftkey/with_twitter/", N, "-Grams.rds", sep = "")
save(df_all, file = filename, precheck = F)
# Status
print("Stage 4 Complete")
# Clear unused memory
rm(df_all)
gc()
} | /Routines/03.Create_Ngrams.R | no_license | nithsubr/Swiftkey_NWP | R | false | false | 8,900 | r |
# This funtion creates 5 sets of N-Grams. Each containing the aggregate frequency of all N-grams (N = 1 to 5)
# Input this this funtion is the N (order of the gram) that needs to be generated
# This routine used the Corpus that has already been saved via Obtain_Data.R routine
getProfanityWords <- function(corpus) {
profanityFileName <- "profanity.txt"
if (!file.exists(profanityFileName)) {
profanity.url <- "https://raw.githubusercontent.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/master/en"
download.file(profanity.url, destfile = profanityFileName, method = "curl")
}
if (sum(ls() == "profanity") < 1) {
profanity <- read.csv(profanityFileName, header = FALSE, stringsAsFactors = FALSE)
profanity <- profanity$V1
profanity <- profanity[1:length(profanity)-1]
}
profanity
}
Create_Ngrams <- function(N)
{
# Check the user input. Currently only 1-5 grams are supported
if (N > 5 && N < 1) stop ("Fatal Error. N should be between 1 and 5")
# Load Packages
library(tm)
library(RWeka)
library(reshape2)
library(slam)
library(doParallel)
library(tau)
library(data.table)
library(stringr)
library(quanteda)
# Register for Parellel Processing
registerDoParallel(4)
jobcluster <- makeCluster(detectCores())
invisible(clusterEvalQ(jobcluster, library(tm)))
invisible(clusterEvalQ(jobcluster, library(RWeka)))
invisible(clusterEvalQ(jobcluster, library(reshape2)))
invisible(clusterEvalQ(jobcluster, library(slam)))
options(mc.cores = 4)
# Clear unused memory
gc()
if (N != 1)
{
load("./Swiftkey/with_twitter/1-Grams.rds")
if(!exists("df_all")) {stop("Please first load the 1-Grams")}
df1_all <- df_all
rm(df_all)
df1_all <- as.data.table(df1_all)
setkey(df1_all, word)
# Load Data - Corpus which has already been created by "Obtain_Data.R" routine
load("./Swiftkey/Corp_all.RData")
# Create N-Gram tokenizer control funtion
NgramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = N, max = N))
# Create the Document Term Matrix
dtm <- DocumentTermMatrix(Corp, control = list(tokenize = NgramTokenizer))
# Clear Unused Memory
rm(Corp_sample)
gc()
# Status
print("Stage 1 Complete")
# Get the term frequencies Matrix
freq_all <- rollup(dtm, 1, na.rm=TRUE, FUN = sum)
# Clear Unused Memory
rm(dtm)
gc()
# Status
print("Stage 2 Complete")
# Aggregate the Frequencies
df_all <- melt(apply(freq_all , 2, sum))
# Clear unused Memory
rm(freq_all)
gc()
# Print number if rows processed
print(nrow(df_all))
# Status
print("Stage 3 Complete")
# Format Data to Split N Grams into N Words , 1 each per column
df_all$grams <- rownames(df_all)
df_all <- as.data.table(df_all)
} else {
# Create the custom Data Formatting Funtions
removeNonAsciiChars <- function(x) iconv(x, "latin1", "ASCII", sub="")
removeHashtags <- function(x) gsub("\\B#\\S+\\b","", x)
removeUrls <- function(x) gsub("http[s]?://.*\\S+","",x)
removeSites <- function(x) gsub("www\\..*\\.[com|edu|net|biz]","",x)
# Read Data from Source - We will only use the blog and news data
# Twitter Data uses manu non-english words which arent appropriate for prediction
data_blogs_all <- readLines("C:/Users/nithsubr/Documents/Swiftkey/en_US.blogs.txt")
data_news_all <- readLines("C:/Users/nithsubr/Documents/Swiftkey/en_US.news.txt")
data_twitter_all <- readLines("C:/Users/nithsubr/Documents/Swiftkey/en_US.twitter.txt")
data <- sample(c(data_blogs_all, data_news_all, data_twitter_all))
rm(data_blogs_all)
rm(data_news_all)
rm(data_twitter_all)
gc()
# Status
print("Stage 1 Complete")
data <- gsub("*[[:digit:]]*", "", data)
data <- gsub("*[[:punct:]]*", "", data)
data <- removeNonAsciiChars(data)
data <- removeHashtags(data)
data <- removeUrls(data)
data <- removeSites(data)
data <- str_trim(data, side = c("both", "left", "right"))
# Status
print("Stage 2 Complete")
dtm <- dfm(data, toLower = TRUE, removeNumbers = TRUE, removePunct = TRUE, removeSeparators = TRUE, removeTwitter = TRUE)
# Clear unused memory
rm(data)
gc()
df_all <- data.table(grams = features(dtm), value = colSums(dtm))
df_all <- df_all[order(df_all$grams), ]
rm(dtm)
# Status
print("Stage 3 Complete")
}
if (N == 1)
{
df_all <- df_all[order(df_all$grams), ]
df_all$id <- 1:nrow(df_all)
names(df_all) <- c("word", "value", "id")
}
if (N == 2)
{
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[1])
setkey(df_all, word)
word_1 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_1 = word_1$id)
rm(word_1)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[2])
setkey(df_all, word)
pred <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, pred = pred$id)
rm(pred)
df_all <- df_all[, c("value", "word_1", "pred"), with = FALSE]
df_all <- df_all[order(df_all$word_1,-df_all$value), ]
}
if (N == 3)
{
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[1])
setkey(df_all, word)
word_1 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_1 = word_1$id)
rm(word_1)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[2])
setkey(df_all, word)
word_2 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_2 = word_2$id)
rm(word_2)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[3])
setkey(df_all, word)
pred <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, pred = pred$id)
rm(pred)
df_all <- df_all[, c("value", "word_1", "word_2", "pred"), with = FALSE]
df_all <- df_all[order(df_all$word_1, df_all$word_2, -df_all$value), ]
}
if (N == 4)
{
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[1])
setkey(df_all, word)
word_1 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_1 = word_1$id)
rm(word_1)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[2])
setkey(df_all, word)
word_2 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_2 = word_2$id)
rm(word_2)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[3])
setkey(df_all, word)
word_3 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_3 = word_3$id)
rm(word_3)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[4])
setkey(df_all, word)
pred <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, pred = pred$id)
rm(pred)
df_all <- df_all[, c("value", "word_1", "word_2", "word_3", "pred"), with = FALSE]
df_all <- df_all[order(df_all$word_1, df_all$word_2, df_all$word_3, -df_all$value), ]
}
if (N == 5)
{
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[1])
setkey(df_all, word)
word_1 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_1 = word_1$id)
rm(word_1)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[2])
setkey(df_all, word)
word_2 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_2 = word_2$id)
rm(word_2)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[3])
setkey(df_all, word)
word_3 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_3 = word_3$id)
rm(word_3)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[4])
setkey(df_all, word)
word_4 <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, word_4 = word_4$id)
rm(word_4)
df_all$word <- sapply(df_all$grams, function(x) unlist(strsplit(x, " "))[5])
setkey(df_all, word)
pred <- df1_all[df_all, id, by = word]
df_all <- cbind(df_all, pred = pred$id)
rm(pred)
df_all <- df_all[, c("value", "word_1", "word_2", "word_3", "word_4", "pred"), with = FALSE]
df_all <- df_all[order(df_all$word_1, df_all$word_2, df_all$word_3, df_all$word_4, -df_all$value), ]
}
# Print number if rows saved
# print(nrow(df_all))
# Store the Data on disk
filename <- paste("./Swiftkey/with_twitter/", N, "-Grams.rds", sep = "")
save(df_all, file = filename, precheck = F)
# Status
print("Stage 4 Complete")
# Clear unused memory
rm(df_all)
gc()
} |
library(forecast)
setwd("C:/Users/cdavalos/Documents/Pronostico TM/R/Pronosticos/Arima")
#Lee el archivo
Input_Pax_Real <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/PAX_Real.csv"
Input_Rev_USD_Real <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/REV_USD_Real.csv"
Input_Rev_COP_Real <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/REV_COP_Real.csv"
Input_Pax_Outliers <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/PAX_Outliers.csv"
Input_Rev_USD_Outliers <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/REV_USD_Outliers.csv"
Input_Rev_COP_Outliers <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/REV_COP_Outliers.csv"
Input_MINMAX <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Input/Min Max Fechas.txt"
Pax_Real <- read.table(Input_Pax_Real, sep=" ", header=TRUE, fileEncoding="latin1")
Rev_USD_Real <- read.table(Input_Rev_USD_Real, sep=" ", header=TRUE, fileEncoding="latin1")
Rev_COP_Real <- read.table(Input_Rev_COP_Real, sep=" ", header=TRUE, fileEncoding="latin1")
Pax_Outliers <- read.table(Input_Pax_Outliers, sep=" ", header=TRUE, fileEncoding="latin1")
Rev_USD_Outliers<- read.table(Input_Rev_USD_Outliers, sep=" ", header=TRUE, fileEncoding="latin1")
Rev_COP_Outliers<- read.table(Input_Rev_COP_Outliers, sep=" ", header=TRUE, fileEncoding="latin1")
MINMAX <- read.table(Input_MINMAX, sep=" ", header=TRUE, fileEncoding="latin1")
legsPaxReal <- ncol(Pax_Real)
cantDatosPaxReal <- nrow(Pax_Real)
legsUSDReal <- ncol(Rev_USD_Real)
cantDatosUSDReal <- nrow(Rev_USD_Real)
legsCOPReal <- ncol(Rev_COP_Real)
cantDatosCOPReal <- nrow(Rev_COP_Real)
legsPaxOutliers <- ncol(Pax_Outliers)
cantDatosPaxOutliers <- nrow(Pax_Outliers)
legsUSDOutliers <- ncol(Rev_USD_Outliers)
cantDatosUSDOutliers <- nrow(Rev_USD_Outliers)
legsCOPOutliers <- ncol(Rev_COP_Outliers)
cantDatosOutliers <- nrow(Rev_COP_Outliers)
forecast_periods <- 3
confidence_level <- 95
iterations <- 4
matriz_Indicadores_Pax_Real <- data.frame()
matriz_Indicadores_Rev_USD_Real <- data.frame()
matriz_Indicadores_Rev_COP_Real <- data.frame()
matriz_Indicadores_Pax_Outlier <- data.frame()
matriz_Indicadores_Rev_USD_Outlier <- data.frame()
matriz_Indicadores_Rev_COP_Outlier <- data.frame()
hw_forecast_Error_Pax_Real <- data.frame()
hw_forecast_Error_USD_Real <- data.frame()
hw_forecast_Error_COP_Real <- data.frame()
hw_forecast_Error_Pax_Outlier <- data.frame()
hw_forecast_Error_Rev_USD_Outlier <- data.frame()
hw_forecast_Error_Rev_COP_Outlier <- data.frame()
ntrPaxReal <- c(8,31,62,64)
getrmse <- function(x,h,j,...)
{
mape <- double()
me <- double()
rmse <- double()
mae <- double()
mase <- double()
for(i in 1:j)
{
train.end <- time(x)[length(x)-h-j+i]
test.start <- time(x)[length(x)-h-j+i+1]
train <- window(x,end=train.end)
test <- window(x,start=test.start)
fit <- holt(train, exponential=TRUE,damped=TRUE)
fc <- forecast(fit,h = h)
prueba <- as.data.frame(fit[2])
YYinicial <- start(test)[1]
MMinicial <- start(test)[2]
a <- ts(prueba,start=c(YYinicial,MMinicial), frequency = 12)
YYFinal<-start(a)[1]
MMFinal<-start(a)[2]
if (MMFinal + j-2> 12){
fit_ts <- ts( a, frequency = 12, start = c(YYFinal, MMFinal), end= c(YYFinal+1, MMFinal + j -2-12))
test_ts <- ts( test, frequency = 12, start = c(YYFinal, MMFinal), end= c(YYFinal+1, MMFinal + j -2-12))
} else {
fit_ts <- ts( a, frequency = 12, start = c(YYFinal, MMFinal), end= c(YYFinal, MMFinal+j-2))
test_ts <- ts( test, frequency = 12, start = c(YYFinal, MMFinal), end= c(YYFinal, MMFinal+j-2))
}
mape <- c(mape, accuracy(a,test)[1,5])
me <- c(me, accuracy(a,test)[1,1])
rmse <- c(rmse, accuracy(a,test)[1,2])
mae <- c(mae, accuracy(a,test)[1,3])
}
return(c(mean(me),mean(rmse), mean(mae), mean(mape)))
}
for(g in 1:legsPaxReal){
if(!(g %in% ntrPaxReal)){
posRuta <- match(colnames(Pax_Real)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
seriepaxesp_REAL <- Pax_Real[g][which(rownames(Pax_Real[g])>=inicio & rownames(Pax_Real[g]) <= fin),]
ts_Pax_Real <- ts(seriepaxesp_REAL, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Pax_Real <- getrmse(ts_Pax_Real, forecast_periods, iterations)
matriz_Indicadores_Pax_Real <- rbind(matriz_Indicadores_Pax_Real,Indicadores_Pax_Real)
}
}
for(g in 1:legsPaxOutliers){
posRuta <- match(colnames(Pax_Outliers)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
seriepaxesp_OUTLIER <- Pax_Outliers[g][which(rownames(Pax_Outliers[g])>=inicio & rownames(Pax_Outliers[g]) <= fin),]
ts_Pax_Outlier <- ts(seriepaxesp_OUTLIER, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Pax_Outlier <- getrmse(ts_Pax_Outlier, forecast_periods, iterations)
matriz_Indicadores_Pax_Outlier <- rbind(matriz_Indicadores_Pax_Outlier,Indicadores_Pax_Outlier)
}
for(g in 1:legsUSDReal){
posRuta <- match(colnames(Rev_USD_Real)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
data_rev_usdesp_REAL <- Rev_USD_Real[g][which(rownames(Rev_USD_Real[g])>=inicio & rownames(Rev_USD_Real[g]) <= fin),]
ts_Rev_USD_Real <- ts(data_rev_usdesp_REAL, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Rev_USD_Real <- getrmse(ts_Rev_USD_Real, forecast_periods, iterations)
matriz_Indicadores_Rev_USD_Real <- rbind(matriz_Indicadores_Rev_USD_Real,Indicadores_Rev_USD_Real)
}
for(g in 1:legsUSDOutliers){
posRuta <- match(colnames(REV_USD_Outliers)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
data_rev_usdesp_OUTLIER <- Rev_USD_Outliers[g][which(rownames(Rev_USD_Outliers[g])>=inicio & rownames(Rev_USD_Outliers[g]) <= fin),]
ts_Rev_USD_Outlier <- ts(data_rev_usdesp_OUTLIER, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Rev_USD_Outlier <- getrmse(ts_Rev_USD_Outlier, forecast_periods, iterations)
matriz_Indicadores_Rev_USD_Outlier <- rbind(matriz_Indicadores_Rev_USD_Outlier,Indicadores_Rev_USD_Outlier)
}
for(g in 1:legsCOPReal){
posRuta <- match(colnames(REV_COP_Real)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
data_rev_copesp_REAL <- Rev_COP_Real[g][which(rownames(Rev_COP_Real[g])>=inicio & rownames(Rev_COP_Real[g]) <= fin),]
ts_Rev_COP_Real <- ts(data_rev_copesp_REAL, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Rev_COP_Real <- getrmse(ts_Rev_COP_Real, forecast_periods, iterations)
matriz_Indicadores_Rev_COP_Real <- rbind(matriz_Indicadores_Rev_COP_Real,Indicadores_Rev_COP_Real)
}
for(g in 1:legsCOPOutliers){
posRuta <- match(colnames(REV_COP_Outliers)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
data_rev_copesp_OUTLIER <- Rev_COP_Outliers[g][which(rownames(Rev_COP_Outliers[g])>=inicio & rownames(Rev_COP_Outliers[g]) <= fin),]
ts_Rev_COP_Outlier <- ts(data_rev_copesp_OUTLIER, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Rev_COP_Outlier <- getrmse(ts_Rev_COP_Outlier, forecast_periods, iterations)
matriz_Indicadores_Rev_COP_Outlier <- rbind(matriz_Indicadores_Rev_COP_Outlier,Indicadores_Rev_COP_Outlier)
}
hw_forecast_Error_Pax_Real <- t(matriz_Indicadores_Pax_Real)
hw_forecast_Error_USD_Real <- t(matriz_Indicadores_Rev_USD_Real)
hw_forecast_Error_COP_Real <- t(matriz_Indicadores_Rev_COP_Real)
hw_forecast_Error_Pax_Outlier <- t(matriz_Indicadores_Pax_Outlier)
hw_forecast_Error_Rev_USD_Outlier <- t(matriz_Indicadores_Rev_USD_Outlier)
hw_forecast_Error_Rev_COP_Outlier <- t(matriz_Indicadores_Rev_COP_Outlier)
colnames(hw_forecast_Error_Pax_Real) <- colnames(Pax_Real)
colnames(hw_forecast_Error_USD_Real) <- colnames(Pax_Real)
colnames(hw_forecast_Error_COP_Real) <- colnames(Pax_Real)
colnames(hw_forecast_Error_Pax_Outlier) <- colnames(Pax_Real)
colnames(hw_forecast_Error_Rev_USD_Outlier) <- colnames(Pax_Real)
colnames(hw_forecast_Error_Rev_COP_Outlier) <- colnames(Pax_Real)
Vector_Indicadores <- c("ME","RMSE","MAE","MAPE")
rownames(hw_forecast_Error_Pax_Real) <- Vector_Indicadores
rownames(hw_forecast_Error_USD_Real) <- Vector_Indicadores
rownames(hw_forecast_Error_COP_Real) <- Vector_Indicadores
rownames(hw_forecast_Error_Pax_Outlier) <- Vector_Indicadores
rownames(hw_forecast_Error_Rev_USD_Outlier) <- Vector_Indicadores
rownames(hw_forecast_Error_Rev_COP_Outlier) <- Vector_Indicadores
setwd("C:/Users/cdavalos/Documents/Pronostico TM/R/Indicadores/Damped Trend")
write.table(file="Indicadores_PAX_Real.csv",hw_forecast_Error_Pax_Real)
write.table(file="Indicadores_REV_USD_Real.csv",hw_forecast_Error_USD_Real)
write.table(file="Indicadores_REV_COP_Real.csv",hw_forecast_Error_COP_Real)
write.table(file="Indicadores_PAX_Outliers.csv",hw_forecast_Error_Pax_Outlier)
write.table(file="Indicadores_REV_USD_Outliers.csv",hw_forecast_Error_Rev_USD_Outlier)
write.table(file="Indicadores_REV_COP_Outliers.csv",hw_forecast_Error_Rev_COP_Outlier)
| /Measurements/Exponential Damped Trend (Data Splitting).r | no_license | cdavalos970/AirlineForecasting | R | false | false | 10,201 | r | library(forecast)
setwd("C:/Users/cdavalos/Documents/Pronostico TM/R/Pronosticos/Arima")
#Lee el archivo
Input_Pax_Real <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/PAX_Real.csv"
Input_Rev_USD_Real <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/REV_USD_Real.csv"
Input_Rev_COP_Real <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/REV_COP_Real.csv"
Input_Pax_Outliers <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/PAX_Outliers.csv"
Input_Rev_USD_Outliers <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/REV_USD_Outliers.csv"
Input_Rev_COP_Outliers <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Output Outlier/REV_COP_Outliers.csv"
Input_MINMAX <- "C:/Users/cdavalos/Documents/Pronostico TM/R/Input/Min Max Fechas.txt"
Pax_Real <- read.table(Input_Pax_Real, sep=" ", header=TRUE, fileEncoding="latin1")
Rev_USD_Real <- read.table(Input_Rev_USD_Real, sep=" ", header=TRUE, fileEncoding="latin1")
Rev_COP_Real <- read.table(Input_Rev_COP_Real, sep=" ", header=TRUE, fileEncoding="latin1")
Pax_Outliers <- read.table(Input_Pax_Outliers, sep=" ", header=TRUE, fileEncoding="latin1")
Rev_USD_Outliers<- read.table(Input_Rev_USD_Outliers, sep=" ", header=TRUE, fileEncoding="latin1")
Rev_COP_Outliers<- read.table(Input_Rev_COP_Outliers, sep=" ", header=TRUE, fileEncoding="latin1")
MINMAX <- read.table(Input_MINMAX, sep=" ", header=TRUE, fileEncoding="latin1")
legsPaxReal <- ncol(Pax_Real)
cantDatosPaxReal <- nrow(Pax_Real)
legsUSDReal <- ncol(Rev_USD_Real)
cantDatosUSDReal <- nrow(Rev_USD_Real)
legsCOPReal <- ncol(Rev_COP_Real)
cantDatosCOPReal <- nrow(Rev_COP_Real)
legsPaxOutliers <- ncol(Pax_Outliers)
cantDatosPaxOutliers <- nrow(Pax_Outliers)
legsUSDOutliers <- ncol(Rev_USD_Outliers)
cantDatosUSDOutliers <- nrow(Rev_USD_Outliers)
legsCOPOutliers <- ncol(Rev_COP_Outliers)
cantDatosOutliers <- nrow(Rev_COP_Outliers)
forecast_periods <- 3
confidence_level <- 95
iterations <- 4
matriz_Indicadores_Pax_Real <- data.frame()
matriz_Indicadores_Rev_USD_Real <- data.frame()
matriz_Indicadores_Rev_COP_Real <- data.frame()
matriz_Indicadores_Pax_Outlier <- data.frame()
matriz_Indicadores_Rev_USD_Outlier <- data.frame()
matriz_Indicadores_Rev_COP_Outlier <- data.frame()
hw_forecast_Error_Pax_Real <- data.frame()
hw_forecast_Error_USD_Real <- data.frame()
hw_forecast_Error_COP_Real <- data.frame()
hw_forecast_Error_Pax_Outlier <- data.frame()
hw_forecast_Error_Rev_USD_Outlier <- data.frame()
hw_forecast_Error_Rev_COP_Outlier <- data.frame()
ntrPaxReal <- c(8,31,62,64)
getrmse <- function(x,h,j,...)
{
mape <- double()
me <- double()
rmse <- double()
mae <- double()
mase <- double()
for(i in 1:j)
{
train.end <- time(x)[length(x)-h-j+i]
test.start <- time(x)[length(x)-h-j+i+1]
train <- window(x,end=train.end)
test <- window(x,start=test.start)
fit <- holt(train, exponential=TRUE,damped=TRUE)
fc <- forecast(fit,h = h)
prueba <- as.data.frame(fit[2])
YYinicial <- start(test)[1]
MMinicial <- start(test)[2]
a <- ts(prueba,start=c(YYinicial,MMinicial), frequency = 12)
YYFinal<-start(a)[1]
MMFinal<-start(a)[2]
if (MMFinal + j-2> 12){
fit_ts <- ts( a, frequency = 12, start = c(YYFinal, MMFinal), end= c(YYFinal+1, MMFinal + j -2-12))
test_ts <- ts( test, frequency = 12, start = c(YYFinal, MMFinal), end= c(YYFinal+1, MMFinal + j -2-12))
} else {
fit_ts <- ts( a, frequency = 12, start = c(YYFinal, MMFinal), end= c(YYFinal, MMFinal+j-2))
test_ts <- ts( test, frequency = 12, start = c(YYFinal, MMFinal), end= c(YYFinal, MMFinal+j-2))
}
mape <- c(mape, accuracy(a,test)[1,5])
me <- c(me, accuracy(a,test)[1,1])
rmse <- c(rmse, accuracy(a,test)[1,2])
mae <- c(mae, accuracy(a,test)[1,3])
}
return(c(mean(me),mean(rmse), mean(mae), mean(mape)))
}
for(g in 1:legsPaxReal){
if(!(g %in% ntrPaxReal)){
posRuta <- match(colnames(Pax_Real)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
seriepaxesp_REAL <- Pax_Real[g][which(rownames(Pax_Real[g])>=inicio & rownames(Pax_Real[g]) <= fin),]
ts_Pax_Real <- ts(seriepaxesp_REAL, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Pax_Real <- getrmse(ts_Pax_Real, forecast_periods, iterations)
matriz_Indicadores_Pax_Real <- rbind(matriz_Indicadores_Pax_Real,Indicadores_Pax_Real)
}
}
for(g in 1:legsPaxOutliers){
posRuta <- match(colnames(Pax_Outliers)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
seriepaxesp_OUTLIER <- Pax_Outliers[g][which(rownames(Pax_Outliers[g])>=inicio & rownames(Pax_Outliers[g]) <= fin),]
ts_Pax_Outlier <- ts(seriepaxesp_OUTLIER, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Pax_Outlier <- getrmse(ts_Pax_Outlier, forecast_periods, iterations)
matriz_Indicadores_Pax_Outlier <- rbind(matriz_Indicadores_Pax_Outlier,Indicadores_Pax_Outlier)
}
for(g in 1:legsUSDReal){
posRuta <- match(colnames(Rev_USD_Real)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
data_rev_usdesp_REAL <- Rev_USD_Real[g][which(rownames(Rev_USD_Real[g])>=inicio & rownames(Rev_USD_Real[g]) <= fin),]
ts_Rev_USD_Real <- ts(data_rev_usdesp_REAL, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Rev_USD_Real <- getrmse(ts_Rev_USD_Real, forecast_periods, iterations)
matriz_Indicadores_Rev_USD_Real <- rbind(matriz_Indicadores_Rev_USD_Real,Indicadores_Rev_USD_Real)
}
for(g in 1:legsUSDOutliers){
posRuta <- match(colnames(REV_USD_Outliers)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
data_rev_usdesp_OUTLIER <- Rev_USD_Outliers[g][which(rownames(Rev_USD_Outliers[g])>=inicio & rownames(Rev_USD_Outliers[g]) <= fin),]
ts_Rev_USD_Outlier <- ts(data_rev_usdesp_OUTLIER, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Rev_USD_Outlier <- getrmse(ts_Rev_USD_Outlier, forecast_periods, iterations)
matriz_Indicadores_Rev_USD_Outlier <- rbind(matriz_Indicadores_Rev_USD_Outlier,Indicadores_Rev_USD_Outlier)
}
for(g in 1:legsCOPReal){
posRuta <- match(colnames(REV_COP_Real)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
data_rev_copesp_REAL <- Rev_COP_Real[g][which(rownames(Rev_COP_Real[g])>=inicio & rownames(Rev_COP_Real[g]) <= fin),]
ts_Rev_COP_Real <- ts(data_rev_copesp_REAL, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Rev_COP_Real <- getrmse(ts_Rev_COP_Real, forecast_periods, iterations)
matriz_Indicadores_Rev_COP_Real <- rbind(matriz_Indicadores_Rev_COP_Real,Indicadores_Rev_COP_Real)
}
for(g in 1:legsCOPOutliers){
posRuta <- match(colnames(REV_COP_Outliers)[g],rownames(MINMAX))
añoInicio <- MINMAX[posRuta,1]
mesInicio <- MINMAX[posRuta,3]
añoFin <- MINMAX[posRuta,2]
mesFin <- MINMAX[posRuta,4]
inicio <- as.Date(paste(añoInicio,mesInicio,"1",sep ="/"))
fin <- as.Date(paste(añoFin,mesFin,"1",sep ="/"))
data_rev_copesp_OUTLIER <- Rev_COP_Outliers[g][which(rownames(Rev_COP_Outliers[g])>=inicio & rownames(Rev_COP_Outliers[g]) <= fin),]
ts_Rev_COP_Outlier <- ts(data_rev_copesp_OUTLIER, frequency = 12, start = c(añoInicio,mesInicio), end= c(añoFin,mesFin))
Indicadores_Rev_COP_Outlier <- getrmse(ts_Rev_COP_Outlier, forecast_periods, iterations)
matriz_Indicadores_Rev_COP_Outlier <- rbind(matriz_Indicadores_Rev_COP_Outlier,Indicadores_Rev_COP_Outlier)
}
hw_forecast_Error_Pax_Real <- t(matriz_Indicadores_Pax_Real)
hw_forecast_Error_USD_Real <- t(matriz_Indicadores_Rev_USD_Real)
hw_forecast_Error_COP_Real <- t(matriz_Indicadores_Rev_COP_Real)
hw_forecast_Error_Pax_Outlier <- t(matriz_Indicadores_Pax_Outlier)
hw_forecast_Error_Rev_USD_Outlier <- t(matriz_Indicadores_Rev_USD_Outlier)
hw_forecast_Error_Rev_COP_Outlier <- t(matriz_Indicadores_Rev_COP_Outlier)
colnames(hw_forecast_Error_Pax_Real) <- colnames(Pax_Real)
colnames(hw_forecast_Error_USD_Real) <- colnames(Pax_Real)
colnames(hw_forecast_Error_COP_Real) <- colnames(Pax_Real)
colnames(hw_forecast_Error_Pax_Outlier) <- colnames(Pax_Real)
colnames(hw_forecast_Error_Rev_USD_Outlier) <- colnames(Pax_Real)
colnames(hw_forecast_Error_Rev_COP_Outlier) <- colnames(Pax_Real)
Vector_Indicadores <- c("ME","RMSE","MAE","MAPE")
rownames(hw_forecast_Error_Pax_Real) <- Vector_Indicadores
rownames(hw_forecast_Error_USD_Real) <- Vector_Indicadores
rownames(hw_forecast_Error_COP_Real) <- Vector_Indicadores
rownames(hw_forecast_Error_Pax_Outlier) <- Vector_Indicadores
rownames(hw_forecast_Error_Rev_USD_Outlier) <- Vector_Indicadores
rownames(hw_forecast_Error_Rev_COP_Outlier) <- Vector_Indicadores
setwd("C:/Users/cdavalos/Documents/Pronostico TM/R/Indicadores/Damped Trend")
write.table(file="Indicadores_PAX_Real.csv",hw_forecast_Error_Pax_Real)
write.table(file="Indicadores_REV_USD_Real.csv",hw_forecast_Error_USD_Real)
write.table(file="Indicadores_REV_COP_Real.csv",hw_forecast_Error_COP_Real)
write.table(file="Indicadores_PAX_Outliers.csv",hw_forecast_Error_Pax_Outlier)
write.table(file="Indicadores_REV_USD_Outliers.csv",hw_forecast_Error_Rev_USD_Outlier)
write.table(file="Indicadores_REV_COP_Outliers.csv",hw_forecast_Error_Rev_COP_Outlier)
|
####################################################################################################
# An egg of any color hatches into a chick
####################################################################################################
EasterEgg = function (from=NULL, to=NULL, shell="aliceblue") {
# Canvas
plot(1:5, 1:5, ylim=c(-1,1.5), xlim=c(-0.9,0.9), type="n", axes=F, ylab="", xlab="", main="Happy Easter!", cex.main=2)
if (!is.null(from)) {mtext(paste("From", from), col="darkgray", font=4)}
if (!is.null(to)) {mtext(paste("To", to), side=1, col="darkgray", font=4)}
# Define egg
t = seq(-pi, pi, by=0.01)
x = cos(t/4)*sin(t)/2
y = -cos(t)
# Paint Easter egg
polygon(x, y, col=shell)
# Propogate crack
n=20
x_crack = seq(cos(-pi/2/4)*sin(-pi/2)/2, cos(pi/2/4)*sin(pi/2)/2, length.out=n)
y_crack = rnorm(n, sd=0.05)
y_crack[1] <- y[n] <- 0
Sys.sleep(1)
for (i in 1:(n-1)) {
segments(x_crack[i], y_crack[i], x_crack[i+1], y_crack[i+1], lwd=2)
Sys.sleep(abs(rnorm(1, sd=0.25)))
}
# Hatch!
polygon(x=c(x_crack[1:20], x_crack[20:1]), y=c(y_crack[1:20], y_crack[20:1]+0.3), col="white", border="white")
polygon(x=c(x_crack[3:18], x_crack[18:3]), y=c(y_crack[3:18], y_crack[18:3]+0.3), col="yellow", border="yellow")
symbols(x=-0.1, y=0.2, circles=0.1, bg="white", add=TRUE, inches=FALSE)
symbols(x=0.1, y=0.2, circles=0.1, bg="white", add=TRUE, inches=FALSE)
points(c(-0.09, 0.09), c(0.2, 0.2), cex=3, pch=16)
polygon(x=c(-0.05, 0.05, 0.05), y=c(0.05,0.1,-0.1), col="orangered")
t2 = c(seq(pi/2, pi, by=0.01), seq(-pi, -pi/2, by=0.01))
x2 = cos(t2/4)*sin(t2)/2
y2 = -cos(t2)
x_upper = c(x_crack, x2)
y_upper = c(y_crack, y2)+0.3
polygon(x_upper, y_upper, col=shell)
}
| /R/EasterEgg.R | permissive | rgriff23/caRds | R | false | false | 1,765 | r |
####################################################################################################
# An egg of any color hatches into a chick
####################################################################################################
EasterEgg = function (from=NULL, to=NULL, shell="aliceblue") {
# Canvas
plot(1:5, 1:5, ylim=c(-1,1.5), xlim=c(-0.9,0.9), type="n", axes=F, ylab="", xlab="", main="Happy Easter!", cex.main=2)
if (!is.null(from)) {mtext(paste("From", from), col="darkgray", font=4)}
if (!is.null(to)) {mtext(paste("To", to), side=1, col="darkgray", font=4)}
# Define egg
t = seq(-pi, pi, by=0.01)
x = cos(t/4)*sin(t)/2
y = -cos(t)
# Paint Easter egg
polygon(x, y, col=shell)
# Propogate crack
n=20
x_crack = seq(cos(-pi/2/4)*sin(-pi/2)/2, cos(pi/2/4)*sin(pi/2)/2, length.out=n)
y_crack = rnorm(n, sd=0.05)
y_crack[1] <- y[n] <- 0
Sys.sleep(1)
for (i in 1:(n-1)) {
segments(x_crack[i], y_crack[i], x_crack[i+1], y_crack[i+1], lwd=2)
Sys.sleep(abs(rnorm(1, sd=0.25)))
}
# Hatch!
polygon(x=c(x_crack[1:20], x_crack[20:1]), y=c(y_crack[1:20], y_crack[20:1]+0.3), col="white", border="white")
polygon(x=c(x_crack[3:18], x_crack[18:3]), y=c(y_crack[3:18], y_crack[18:3]+0.3), col="yellow", border="yellow")
symbols(x=-0.1, y=0.2, circles=0.1, bg="white", add=TRUE, inches=FALSE)
symbols(x=0.1, y=0.2, circles=0.1, bg="white", add=TRUE, inches=FALSE)
points(c(-0.09, 0.09), c(0.2, 0.2), cex=3, pch=16)
polygon(x=c(-0.05, 0.05, 0.05), y=c(0.05,0.1,-0.1), col="orangered")
t2 = c(seq(pi/2, pi, by=0.01), seq(-pi, -pi/2, by=0.01))
x2 = cos(t2/4)*sin(t2)/2
y2 = -cos(t2)
x_upper = c(x_crack, x2)
y_upper = c(y_crack, y2)+0.3
polygon(x_upper, y_upper, col=shell)
}
|
#
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Philippines Gender Data"),
mainPanel(
align = "center",
width = 12,
selectInput("variable","Choose data to plot:",
list (
"Employers"="SL.EMP.MPYR",
"Employment in agriculture"="SL.AGR.EMPL",
"Employment in industry"="SL.IND.EMPL",
"Employment in services"="SL.SRV.EMPL",
"Employment to population ratio, ages 15+"="SL.EMP.TOTL.SP",
"Employment to population ratio, ages 15- 24"="SL.EMP.1524.SP"
)
),
submitButton("Submit"),
tags$a(),
plotOutput("distPlot")
)
))
| /Developing Data Products/Week 4/genderPlot/ui.R | no_license | camillebt/datasciencecoursera | R | false | false | 1,195 | r | #
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Philippines Gender Data"),
mainPanel(
align = "center",
width = 12,
selectInput("variable","Choose data to plot:",
list (
"Employers"="SL.EMP.MPYR",
"Employment in agriculture"="SL.AGR.EMPL",
"Employment in industry"="SL.IND.EMPL",
"Employment in services"="SL.SRV.EMPL",
"Employment to population ratio, ages 15+"="SL.EMP.TOTL.SP",
"Employment to population ratio, ages 15- 24"="SL.EMP.1524.SP"
)
),
submitButton("Submit"),
tags$a(),
plotOutput("distPlot")
)
))
|
# Felipe Montes
# Program to match Willow row plant census data to GPS track coordinates
# V :2013-05-02
#set working Directory
#setwd("C:/Users/frm10/Desktop/Willow Census R")
setwd("G:/Willow Census R")
#read plant data from the excell CVS file
Plant.data<-read.csv('Data_Plants2.csv',header=T,as.is=T,colClasses=c('numeric','character'))
#convert time and date to appropriate format for manipulation
Plant.data$Date_time<-as.POSIXct(strptime(Plant.data$Time.Stamp,format='%m/%d/%Y %H:%M:%S'))
# Select only necesary columns
Plant<-Plant.data[,c('Date_time','No.plants..Rows.')]
#read data from the GPS file
GPS.data<-read.csv('Current Track_ 03 MAY 2013 09_15.csv',skip=42,header=T,as.is=T)
#convert time and date to appropriate format for manipulation
GPS.data$Date<-substr(GPS.data$time,1,10)
#the date in the GPS data appears to be 4 hours later that what it appears in local time, probably due to Universal time setting
#therefore needs to be changed by 4 hours
Hours<-as.numeric(substr(GPS.data$time,12,13))-4
Min.sec<-substr(GPS.data$time,14,19)
#the format for time has to be '00' hours, therefore hours needs to be corrected
Hours.c<-substr(as.character(Hours+1000),3,4)
Time.c<-paste(Hours.c,Min.sec,sep='')
#Corrected Date and time put together
GPS.data$Date_time<-as.POSIXct(strptime(paste(GPS.data$Date,Time.c),format='%Y-%m-%d %H:%M:%S'),tz='')
#Select only necesary columns
GPS<-GPS.data[,c('Date_time','lat','lon')]
Census<-merge(GPS,Plant,by='Date_time',all=T)
Census.o<-Census[,order(c('Date_time','lat','lon','No.plants..Rows.'))]
# create a variable to update the No.Plants.rows variable
Census.o$Plants[1]<-'a'
# Set the fist value of the No.plants..Rows. to a recognizable value 'a'
#Census.o$No.plants..Rows.[1]<-'a'
#in this census, the first value of No.plants..Rows. is '1' a legitimate value therefore it is not changed
Census.o$No.plants..Rows.[1]<-Census.o$Plants[1]<-1
for (i in 2:dim(Census.o)[1]) {
if (is.na(Census.o$No.plants..Rows.[i])) Census.o$Plants[i]<-Census.o$Plants[i-1]
else Census.o$Plants[i]<-Census.o$No.plants..Rows.[i]
}
#extract only points in the GPS.data data frame to match the gps points in the map
Final.data<-Census.o[match(GPS.data$Date_time,Census.o$Date_time ),]
#Export the data to added to the GPS file
write.csv(Final.data,file='Final.data_part2.csv') | /Willow_census_part2.R | no_license | FelipeMonts/WillowHarvest | R | false | false | 2,364 | r | # Felipe Montes
# Program to match Willow row plant census data to GPS track coordinates
# V :2013-05-02
#set working Directory
#setwd("C:/Users/frm10/Desktop/Willow Census R")
setwd("G:/Willow Census R")
#read plant data from the excell CVS file
Plant.data<-read.csv('Data_Plants2.csv',header=T,as.is=T,colClasses=c('numeric','character'))
#convert time and date to appropriate format for manipulation
Plant.data$Date_time<-as.POSIXct(strptime(Plant.data$Time.Stamp,format='%m/%d/%Y %H:%M:%S'))
# Select only necesary columns
Plant<-Plant.data[,c('Date_time','No.plants..Rows.')]
#read data from the GPS file
GPS.data<-read.csv('Current Track_ 03 MAY 2013 09_15.csv',skip=42,header=T,as.is=T)
#convert time and date to appropriate format for manipulation
GPS.data$Date<-substr(GPS.data$time,1,10)
#the date in the GPS data appears to be 4 hours later that what it appears in local time, probably due to Universal time setting
#therefore needs to be changed by 4 hours
Hours<-as.numeric(substr(GPS.data$time,12,13))-4
Min.sec<-substr(GPS.data$time,14,19)
#the format for time has to be '00' hours, therefore hours needs to be corrected
Hours.c<-substr(as.character(Hours+1000),3,4)
Time.c<-paste(Hours.c,Min.sec,sep='')
#Corrected Date and time put together
GPS.data$Date_time<-as.POSIXct(strptime(paste(GPS.data$Date,Time.c),format='%Y-%m-%d %H:%M:%S'),tz='')
#Select only necesary columns
GPS<-GPS.data[,c('Date_time','lat','lon')]
Census<-merge(GPS,Plant,by='Date_time',all=T)
Census.o<-Census[,order(c('Date_time','lat','lon','No.plants..Rows.'))]
# create a variable to update the No.Plants.rows variable
Census.o$Plants[1]<-'a'
# Set the fist value of the No.plants..Rows. to a recognizable value 'a'
#Census.o$No.plants..Rows.[1]<-'a'
#in this census, the first value of No.plants..Rows. is '1' a legitimate value therefore it is not changed
Census.o$No.plants..Rows.[1]<-Census.o$Plants[1]<-1
for (i in 2:dim(Census.o)[1]) {
if (is.na(Census.o$No.plants..Rows.[i])) Census.o$Plants[i]<-Census.o$Plants[i-1]
else Census.o$Plants[i]<-Census.o$No.plants..Rows.[i]
}
#extract only points in the GPS.data data frame to match the gps points in the map
Final.data<-Census.o[match(GPS.data$Date_time,Census.o$Date_time ),]
#Export the data to added to the GPS file
write.csv(Final.data,file='Final.data_part2.csv') |
library('rvest')
library('tidyr')
initialurl<-'https://www.the-numbers.com/movie/budgets/all'
MovieStats <- read_html(initialurl)
MovieStats <- html_nodes(MovieStats, css = 'table')
MovieStats <- html_table(MovieStats)[[1]]
MovieStats1<- data.frame(MovieStats)
for (page in c(1:60)){
urlList<-paste0("https://www.the-numbers.com/movie/budgets/all/",page,"01")
MovieStats <- read_html(urlList)
MovieStats <- html_nodes(MovieStats, css = 'table')
MovieStats <- html_table(MovieStats)[[1]]
MovieStats<- data.frame(MovieStats)
MovieStats1<-rbind(MovieStats1,MovieStats)
}
names(MovieStats1) <- c("number","releaseDate", "movieName", "productionBudget","domesticGross","worldwideGross")
MovieStats1$movieName<-tolower(MovieStats1$movieName)
df<-na.omit(MovieStats1)
df$movieName<-gsub('[[:punct:]]+',' ',df$movieName)
df$domestic <- 1
df <- as.data.frame(df[, c('movieName','domestic')], stringAsFactors = F)
write.csv(df,"3_domestic.csv")
| /3_Domestic.R | no_license | ssudhasuresha/Movie-Analytics-Prediction-of-Movie-Success | R | false | false | 960 | r | library('rvest')
library('tidyr')
initialurl<-'https://www.the-numbers.com/movie/budgets/all'
MovieStats <- read_html(initialurl)
MovieStats <- html_nodes(MovieStats, css = 'table')
MovieStats <- html_table(MovieStats)[[1]]
MovieStats1<- data.frame(MovieStats)
for (page in c(1:60)){
urlList<-paste0("https://www.the-numbers.com/movie/budgets/all/",page,"01")
MovieStats <- read_html(urlList)
MovieStats <- html_nodes(MovieStats, css = 'table')
MovieStats <- html_table(MovieStats)[[1]]
MovieStats<- data.frame(MovieStats)
MovieStats1<-rbind(MovieStats1,MovieStats)
}
names(MovieStats1) <- c("number","releaseDate", "movieName", "productionBudget","domesticGross","worldwideGross")
MovieStats1$movieName<-tolower(MovieStats1$movieName)
df<-na.omit(MovieStats1)
df$movieName<-gsub('[[:punct:]]+',' ',df$movieName)
df$domestic <- 1
df <- as.data.frame(df[, c('movieName','domestic')], stringAsFactors = F)
write.csv(df,"3_domestic.csv")
|
#
# pickoption.R
#
# $Revision: 1.6 $ $Date: 2016/04/25 02:34:40 $
#
pickoption <- function(what="option", key, keymap, ...,
exact=FALSE, list.on.err=TRUE, die=TRUE, multi=FALSE,
allow.all=TRUE)
{
keyname <- short.deparse(substitute(key))
if(!is.character(key))
stop(paste(keyname, "must be a character string",
if(multi) "or strings" else NULL))
if(length(key) == 0)
stop(paste("Argument", sQuote(keyname), "has length zero"))
key <- unique(key)
if(!multi && length(key) > 1)
stop(paste("Must specify only one", what, sQuote(keyname)))
allow.all <- allow.all && multi
id <-
if(allow.all && identical(key, "all")) {
seq_along(keymap)
} else if(exact) {
match(key, names(keymap), nomatch=NA)
} else {
pmatch(key, names(keymap), nomatch=NA)
}
if(any(nbg <- is.na(id))) {
# no match
whinge <- paste("unrecognised", what,
paste(dQuote(key[nbg]), collapse=", "),
"in argument", sQuote(keyname))
if(list.on.err) {
cat(paste(whinge, "\n", "Options are:"),
paste(dQuote(names(keymap)), collapse=","), "\n")
}
if(die)
stop(whinge, call.=FALSE)
else
return(NULL)
}
key <- keymap[id]
names(key) <- NULL
return(key)
}
| /R/pickoption.R | no_license | kasselhingee/spatstat | R | false | false | 1,341 | r | #
# pickoption.R
#
# $Revision: 1.6 $ $Date: 2016/04/25 02:34:40 $
#
pickoption <- function(what="option", key, keymap, ...,
exact=FALSE, list.on.err=TRUE, die=TRUE, multi=FALSE,
allow.all=TRUE)
{
keyname <- short.deparse(substitute(key))
if(!is.character(key))
stop(paste(keyname, "must be a character string",
if(multi) "or strings" else NULL))
if(length(key) == 0)
stop(paste("Argument", sQuote(keyname), "has length zero"))
key <- unique(key)
if(!multi && length(key) > 1)
stop(paste("Must specify only one", what, sQuote(keyname)))
allow.all <- allow.all && multi
id <-
if(allow.all && identical(key, "all")) {
seq_along(keymap)
} else if(exact) {
match(key, names(keymap), nomatch=NA)
} else {
pmatch(key, names(keymap), nomatch=NA)
}
if(any(nbg <- is.na(id))) {
# no match
whinge <- paste("unrecognised", what,
paste(dQuote(key[nbg]), collapse=", "),
"in argument", sQuote(keyname))
if(list.on.err) {
cat(paste(whinge, "\n", "Options are:"),
paste(dQuote(names(keymap)), collapse=","), "\n")
}
if(die)
stop(whinge, call.=FALSE)
else
return(NULL)
}
key <- keymap[id]
names(key) <- NULL
return(key)
}
|
#' @title Lipid library build
#' @description Build lipid library based on sdf file and smile file
#' @author Zhiwei Zhou
#' \email{zhouzw@@sioc.ac.cn}
#' @param sdf.file The file name of sdf file
#' @param smile.file The file name of smile file
#' @param category The category of lipids. "GP": Glycerophospholipids; "SP": Sphingolipids; "GL": Glycerolipids; The default is "GP"
#' @param is.output The output csv file. The default is TRUE.
#' @param output.address The output address of csv file. The default is NULL.
#'
#' @example LipLibBuild(sdf.file="PC.sdf", smile.file="PC.smile")
LipLibBuild <- function(sdf.file,
smile.file,
category="GP",
is.output=TRUE,
output.address=NULL){
# raw.data <- readr::read_lines("GPAbbrev.sdf")
# raw.smiles <- readr::read_lines("GPAbbrev.sdf.smiles")
raw.data <- readr::read_lines(sdf.file)
raw.smiles <- readr::read_lines(smile.file)
idx.abbr <- which(raw.data=="> <Abbrev>")+1
idx.category <- which(raw.data=="> <LM Category>")+1
idx.main.class <- which(raw.data=="> <LM Main Class>")+1
idx.sub.class <- which(raw.data=="> <LM Sub Class>")+1
idx.sn1.chain.length <- which(raw.data=="> <Sn1 Chain Length>")+1
idx.sn1.double.bonds <- which(raw.data=="> <Sn1 Double Bonds>")+1
idx.sn2.chain.length <- which(raw.data=="> <Sn2 Chain Length>")+1
idx.sn2.double.bonds <- which(raw.data=="> <Sn2 Double Bonds>")+1
idx.sys.name <- which(raw.data=="> <Systematic Name>")+1
abbr.name <- as.character(raw.data[idx.abbr])
category <- as.character(raw.data[idx.category])
main.class <- as.character(raw.data[idx.main.class])
sub.class <- as.character(raw.data[idx.sub.class])
sn1.chain.length <- as.numeric(raw.data[idx.sn1.chain.length])
sn1.double.bonds <- as.numeric(raw.data[idx.sn1.double.bonds])
sn2.chain.length <- as.numeric(raw.data[idx.sn2.chain.length])
sn2.double.bonds <- as.numeric(raw.data[idx.sn2.double.bonds])
sys.name <- as.character(raw.data[idx.sys.name])
if (category=="GP" | category=="SP") {
result <- data.frame(abbr.name=abbr.name,
smiles=raw.smiles,
category=category,
main.class=main.class,
sub.class=sub.class,
sn1.chain.length=sn1.chain.length,
sn1.double.bonds=sn1.double.bonds,
sn2.chain.length=sn2.chain.length,
sn2.double.bonds=sn2.double.bonds,
sys.name=sys.name,
stringsAsFactors = F)
}
if (category=="GL") {
idx.sn3.chain.length <- which(raw.data=="> <Sn3 Chain Length>")+1
idx.sn3.double.bonds <- which(raw.data=="> <Sn3 Double Bonds>")+1
sn3.chain.length <- as.numeric(raw.data[idx.sn3.chain.length])
sn3.double.bonds <- as.numeric(raw.data[idx.sn3.double.bonds])
result <- data.frame(abbr.name=abbr.name,
smiles=raw.smiles,
category=category,
main.class=main.class,
sub.class=sub.class,
sn1.chain.length=sn1.chain.length,
sn1.double.bonds=sn1.double.bonds,
sn2.chain.length=sn2.chain.length,
sn2.double.bonds=sn2.double.bonds,
sn3.chain.length=sn3.chain.length,
sn3.double.bonds=sn3.double.bonds,
sys.name=sys.name,
stringsAsFactors = F)
}
return(result)
if (is.output==TRUE) {
if (is.null(output.address)) {
temp <- paste(getwd(), "library", sep = "/")
} else {
temp <- paste(output.address, "library", sep = "/")
}
dir.create(path = temp)
temp <- paste(temp, "lipid_lib.csv", sep = "/")
write.csv(result, file = temp, row.names = F)
}
}
| /R/LipLibBuild.R | no_license | JustinZZW/LipLibBuild | R | false | false | 3,994 | r | #' @title Lipid library build
#' @description Build lipid library based on sdf file and smile file
#' @author Zhiwei Zhou
#' \email{zhouzw@@sioc.ac.cn}
#' @param sdf.file The file name of sdf file
#' @param smile.file The file name of smile file
#' @param category The category of lipids. "GP": Glycerophospholipids; "SP": Sphingolipids; "GL": Glycerolipids; The default is "GP"
#' @param is.output The output csv file. The default is TRUE.
#' @param output.address The output address of csv file. The default is NULL.
#'
#' @example LipLibBuild(sdf.file="PC.sdf", smile.file="PC.smile")
LipLibBuild <- function(sdf.file,
smile.file,
category="GP",
is.output=TRUE,
output.address=NULL){
# raw.data <- readr::read_lines("GPAbbrev.sdf")
# raw.smiles <- readr::read_lines("GPAbbrev.sdf.smiles")
raw.data <- readr::read_lines(sdf.file)
raw.smiles <- readr::read_lines(smile.file)
idx.abbr <- which(raw.data=="> <Abbrev>")+1
idx.category <- which(raw.data=="> <LM Category>")+1
idx.main.class <- which(raw.data=="> <LM Main Class>")+1
idx.sub.class <- which(raw.data=="> <LM Sub Class>")+1
idx.sn1.chain.length <- which(raw.data=="> <Sn1 Chain Length>")+1
idx.sn1.double.bonds <- which(raw.data=="> <Sn1 Double Bonds>")+1
idx.sn2.chain.length <- which(raw.data=="> <Sn2 Chain Length>")+1
idx.sn2.double.bonds <- which(raw.data=="> <Sn2 Double Bonds>")+1
idx.sys.name <- which(raw.data=="> <Systematic Name>")+1
abbr.name <- as.character(raw.data[idx.abbr])
category <- as.character(raw.data[idx.category])
main.class <- as.character(raw.data[idx.main.class])
sub.class <- as.character(raw.data[idx.sub.class])
sn1.chain.length <- as.numeric(raw.data[idx.sn1.chain.length])
sn1.double.bonds <- as.numeric(raw.data[idx.sn1.double.bonds])
sn2.chain.length <- as.numeric(raw.data[idx.sn2.chain.length])
sn2.double.bonds <- as.numeric(raw.data[idx.sn2.double.bonds])
sys.name <- as.character(raw.data[idx.sys.name])
if (category=="GP" | category=="SP") {
result <- data.frame(abbr.name=abbr.name,
smiles=raw.smiles,
category=category,
main.class=main.class,
sub.class=sub.class,
sn1.chain.length=sn1.chain.length,
sn1.double.bonds=sn1.double.bonds,
sn2.chain.length=sn2.chain.length,
sn2.double.bonds=sn2.double.bonds,
sys.name=sys.name,
stringsAsFactors = F)
}
if (category=="GL") {
idx.sn3.chain.length <- which(raw.data=="> <Sn3 Chain Length>")+1
idx.sn3.double.bonds <- which(raw.data=="> <Sn3 Double Bonds>")+1
sn3.chain.length <- as.numeric(raw.data[idx.sn3.chain.length])
sn3.double.bonds <- as.numeric(raw.data[idx.sn3.double.bonds])
result <- data.frame(abbr.name=abbr.name,
smiles=raw.smiles,
category=category,
main.class=main.class,
sub.class=sub.class,
sn1.chain.length=sn1.chain.length,
sn1.double.bonds=sn1.double.bonds,
sn2.chain.length=sn2.chain.length,
sn2.double.bonds=sn2.double.bonds,
sn3.chain.length=sn3.chain.length,
sn3.double.bonds=sn3.double.bonds,
sys.name=sys.name,
stringsAsFactors = F)
}
return(result)
if (is.output==TRUE) {
if (is.null(output.address)) {
temp <- paste(getwd(), "library", sep = "/")
} else {
temp <- paste(output.address, "library", sep = "/")
}
dir.create(path = temp)
temp <- paste(temp, "lipid_lib.csv", sep = "/")
write.csv(result, file = temp, row.names = F)
}
}
|
## File Name: sirt_csink.R
## File Version: 0.06
sirt_csink <- function(file)
{
CDM::csink( file=file )
}
| /R/sirt_csink.R | no_license | alexanderrobitzsch/sirt | R | false | false | 111 | r | ## File Name: sirt_csink.R
## File Version: 0.06
sirt_csink <- function(file)
{
CDM::csink( file=file )
}
|
library(quantmod)
amzn = getSymbols("AMZN",auto.assign=FALSE)
sampleTimes = index(amzn)
sampleTimes
df <- data.frame(sapply(sampleTimes, format, "%Y"), sapply(sampleTimes, format, "%a"))
names(df) <- c("year", "dayofweek")
print(table(df$year))
print(table(df)) | /week4/q4_5.R | no_license | hardikns/getting-cleaning-data | R | false | false | 262 | r | library(quantmod)
amzn = getSymbols("AMZN",auto.assign=FALSE)
sampleTimes = index(amzn)
sampleTimes
df <- data.frame(sapply(sampleTimes, format, "%Y"), sapply(sampleTimes, format, "%a"))
names(df) <- c("year", "dayofweek")
print(table(df$year))
print(table(df)) |
#' Calculate a weighted harmonic mean
#' @param x An invertable R object.
#' @param ... further arguments passed to \code{\link{sum}}
#' @seealso \code{\link{rmfi_weighted_geomean}}, \code{\link{weighted.mean}}, \code{\link{rmfi_harmean}} \code{\link{rmfi_geomean}} and \code{\link{mean}}
#' @keywords internal
rmfi_weighted_harmean <- function(x, w, ...) {
return(sum(w)/(sum(w/x, ...)))
}
| /R/rmfi-weighted-harmean.R | no_license | CasillasMX/RMODFLOW | R | false | false | 393 | r | #' Calculate a weighted harmonic mean
#' @param x An invertable R object.
#' @param ... further arguments passed to \code{\link{sum}}
#' @seealso \code{\link{rmfi_weighted_geomean}}, \code{\link{weighted.mean}}, \code{\link{rmfi_harmean}} \code{\link{rmfi_geomean}} and \code{\link{mean}}
#' @keywords internal
rmfi_weighted_harmean <- function(x, w, ...) {
return(sum(w)/(sum(w/x, ...)))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mcmc_plotting.R
\name{plot.post_sim_list}
\alias{plot.post_sim_list}
\title{Plot posterior trajectory}
\usage{
\method{plot}{post_sim_list}(x, plot.type = "medianHDI", col = c("red",
"darkgrey"), lty = c(1, 2), auto.layout = TRUE, panel.first = NULL,
...)
}
\arguments{
\item{x}{a post_sim or post_sim_list object}
\item{plot.type}{character, which type of plot. Options are "ensemble" and "medianHDI".}
\item{col}{color, for plot.type = "medianHDI" the first element is used for the median, the second for the HDI}
\item{lty}{line type, for plot.type = "medianHDI" the first element is used for the median, the second for the HDI}
\item{auto.layout}{logical, should the layout for plot.type = "medianHDI" be determined automatically?}
\item{panel.first}{an expression to be evaluated after the plot axes are set up but before any plotting takes place. This can be useful for adding data points.}
\item{...}{further arguments to methods}
}
\description{
Plots the inference results from a debinfer_result object
}
| /man/plot.post_sim_list.Rd | no_license | waternk/debinfer | R | false | true | 1,102 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mcmc_plotting.R
\name{plot.post_sim_list}
\alias{plot.post_sim_list}
\title{Plot posterior trajectory}
\usage{
\method{plot}{post_sim_list}(x, plot.type = "medianHDI", col = c("red",
"darkgrey"), lty = c(1, 2), auto.layout = TRUE, panel.first = NULL,
...)
}
\arguments{
\item{x}{a post_sim or post_sim_list object}
\item{plot.type}{character, which type of plot. Options are "ensemble" and "medianHDI".}
\item{col}{color, for plot.type = "medianHDI" the first element is used for the median, the second for the HDI}
\item{lty}{line type, for plot.type = "medianHDI" the first element is used for the median, the second for the HDI}
\item{auto.layout}{logical, should the layout for plot.type = "medianHDI" be determined automatically?}
\item{panel.first}{an expression to be evaluated after the plot axes are set up but before any plotting takes place. This can be useful for adding data points.}
\item{...}{further arguments to methods}
}
\description{
Plots the inference results from a debinfer_result object
}
|
unlink(list.dirs("."), recursive = TRUE)
test_that("assuming the function runs", {
expect_invisible(sq.aln(folder = "1.CuratedSequences", FilePatterns = "renamed", mask = TRUE))
})
test_that("NULL folder", {
expect_error(sq.aln(folder = NULL))
})
test_that("Mask is non-logic", {
expect_error(sq.aln(mask = "H"))
})
unlink(list.dirs("."), recursive = TRUE)
| /tests/testthat/test_sq.aln.R | permissive | ropensci/phruta | R | false | false | 370 | r | unlink(list.dirs("."), recursive = TRUE)
test_that("assuming the function runs", {
expect_invisible(sq.aln(folder = "1.CuratedSequences", FilePatterns = "renamed", mask = TRUE))
})
test_that("NULL folder", {
expect_error(sq.aln(folder = NULL))
})
test_that("Mask is non-logic", {
expect_error(sq.aln(mask = "H"))
})
unlink(list.dirs("."), recursive = TRUE)
|
library(ape)
testtree <- read.tree("3419_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="3419_0_unrooted.txt") | /codeml_files/newick_trees_processed/3419_0/rinput.R | no_license | DaniBoo/cyanobacteria_project | R | false | false | 135 | r | library(ape)
testtree <- read.tree("3419_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="3419_0_unrooted.txt") |
metabricENetCoxModelCancerCensusM <- setRefClass(Class = "metabricENetCoxModelCancerCensusM",
contains="PredictiveModel",
fields=c("model","childclass"),
methods = list(
initialize = function(...){
return(.self)
},
rawModel = function(){
return(.self$model)
},
customTrain = function(exprData,copyData,clinicalFeaturesData,clinicalSurvData, ...){
load("~/COMPBIO/trunk/users/pandey/controlledExptGeneLists.Rdata")
featureData <-createAggregateFeatureDataSet(list(expr=exprData,copy = copyData))
featureData<-featureData[cancer_census_names,]
featureData_filtered <- filterNasFromMatrix(dataMatrix=featureData, filterBy = "rows")
featureData <- unique(featureData_filtered)
FEA <-t(featureData)
# Model training
.self$childclass <- myEnetCoxIterModel$new()
.self$model <- .self$childclass$customTrain(FEA,
clinicalSurvData,
alpha = alphas,
lambda = lambdas,
nfolds =10,
iterNum = 20)
},
customPredict = function(exprData, copyData, clinicalFeaturesData, ...){
beta <- rownames(.self$childclass$getCoefficients())
featureData <-createAggregateFeatureDataSet(list(expr=exprData,copy = copyData))
FEA<-featureData[beta,]
FEA <- t(FEA)
predictedResponse <- predict(.self$childclass$model,FEA)
return(predictedResponse)
}
)
)
| /survival_analysis/IterCV_Gaurav/ML/metabricENetCoxModelCancerCensusM.R | no_license | insockjang/DrugResponse | R | false | false | 4,007 | r | metabricENetCoxModelCancerCensusM <- setRefClass(Class = "metabricENetCoxModelCancerCensusM",
contains="PredictiveModel",
fields=c("model","childclass"),
methods = list(
initialize = function(...){
return(.self)
},
rawModel = function(){
return(.self$model)
},
customTrain = function(exprData,copyData,clinicalFeaturesData,clinicalSurvData, ...){
load("~/COMPBIO/trunk/users/pandey/controlledExptGeneLists.Rdata")
featureData <-createAggregateFeatureDataSet(list(expr=exprData,copy = copyData))
featureData<-featureData[cancer_census_names,]
featureData_filtered <- filterNasFromMatrix(dataMatrix=featureData, filterBy = "rows")
featureData <- unique(featureData_filtered)
FEA <-t(featureData)
# Model training
.self$childclass <- myEnetCoxIterModel$new()
.self$model <- .self$childclass$customTrain(FEA,
clinicalSurvData,
alpha = alphas,
lambda = lambdas,
nfolds =10,
iterNum = 20)
},
customPredict = function(exprData, copyData, clinicalFeaturesData, ...){
beta <- rownames(.self$childclass$getCoefficients())
featureData <-createAggregateFeatureDataSet(list(expr=exprData,copy = copyData))
FEA<-featureData[beta,]
FEA <- t(FEA)
predictedResponse <- predict(.self$childclass$model,FEA)
return(predictedResponse)
}
)
)
|
\name{ternvis-package}
\alias{ternvis-package}
\alias{ternvis}
\docType{package}
\title{
Visualisation, verification and calibration of ternary forecast data
}
\description{
A suite of functions for visualising ternary probabilistic forecasts.
}
\details{
\tabular{ll}{
Package: \tab ternvis\cr
Type: \tab Package\cr
Version: \tab 1.0\cr
Date: \tab 2012-03-29\cr
License: \tab GPL-2
}
Colours can be assigned to ternary probabilistic forecasts using \code{\link{tcolour}}.
These colours can be used to produce forecast maps as in the example function \code{\link{tmap}}.
A set of ternary forecasts \code{p} can be compared with subsequent ternary observations \code{o} using the function \code{\link{tverify}}. \code{\link{plot.tverify}} then displays this information in a Ternary Reliability Diagram. Calibration is performed using \code{\link{tgetcal}} and \code{\link{tcalibrate}}.
}
\author{
Tim Jupp
Maintainer: Tim Jupp <t.e.jupp@exeter.ac.uk>
}
\references{
Jupp TE, Lowe R, Stephenson DB, Coelho CAS (2012) On the visualization, verification and recalibration of ternary probabilistic forecasts, Philosophical Transactions of the Royal Society, volume 370, pages 1100-1120.
\url{http://rsta.royalsocietypublishing.org/content/370/1962/1100.full}
\url{http://arxiv.org/abs/1103.1303}
}
\keyword{ package }
\seealso{
Some concepts adapted from those in package \emph{vcd}.
}
\examples{
data(foot)
# see the distribution of forecasts
tplot(foot$p,main="Bookmaker forecasts of \n football matches",
dimnames=c("Home Win","Draw","Away Win"))
# see how well forecasts compare with results
# create object of class tverify
foot.verify <- tverify(p=foot$p,o=foot$o)
# plot ternary reliability diagram
dev.new()
plot(foot.verify, thresh=3)
# get a (linear) calibration of these data
# create an object of class tverify
foot.calib <- tgetcal(foot.verify)
# plot ternary reliability diagram of calibrated
dev.new()
plot(foot.calib, thresh=3)
data(rain)
tmap(rain,iyr=17,palette=TRUE,circles=FALSE,fac=10) }
| /man/ternvis-package.Rd | no_license | cran/ternvis | R | false | false | 2,124 | rd | \name{ternvis-package}
\alias{ternvis-package}
\alias{ternvis}
\docType{package}
\title{
Visualisation, verification and calibration of ternary forecast data
}
\description{
A suite of functions for visualising ternary probabilistic forecasts.
}
\details{
\tabular{ll}{
Package: \tab ternvis\cr
Type: \tab Package\cr
Version: \tab 1.0\cr
Date: \tab 2012-03-29\cr
License: \tab GPL-2
}
Colours can be assigned to ternary probabilistic forecasts using \code{\link{tcolour}}.
These colours can be used to produce forecast maps as in the example function \code{\link{tmap}}.
A set of ternary forecasts \code{p} can be compared with subsequent ternary observations \code{o} using the function \code{\link{tverify}}. \code{\link{plot.tverify}} then displays this information in a Ternary Reliability Diagram. Calibration is performed using \code{\link{tgetcal}} and \code{\link{tcalibrate}}.
}
\author{
Tim Jupp
Maintainer: Tim Jupp <t.e.jupp@exeter.ac.uk>
}
\references{
Jupp TE, Lowe R, Stephenson DB, Coelho CAS (2012) On the visualization, verification and recalibration of ternary probabilistic forecasts, Philosophical Transactions of the Royal Society, volume 370, pages 1100-1120.
\url{http://rsta.royalsocietypublishing.org/content/370/1962/1100.full}
\url{http://arxiv.org/abs/1103.1303}
}
\keyword{ package }
\seealso{
Some concepts adapted from those in package \emph{vcd}.
}
\examples{
data(foot)
# see the distribution of forecasts
tplot(foot$p,main="Bookmaker forecasts of \n football matches",
dimnames=c("Home Win","Draw","Away Win"))
# see how well forecasts compare with results
# create object of class tverify
foot.verify <- tverify(p=foot$p,o=foot$o)
# plot ternary reliability diagram
dev.new()
plot(foot.verify, thresh=3)
# get a (linear) calibration of these data
# create an object of class tverify
foot.calib <- tgetcal(foot.verify)
# plot ternary reliability diagram of calibrated
dev.new()
plot(foot.calib, thresh=3)
data(rain)
tmap(rain,iyr=17,palette=TRUE,circles=FALSE,fac=10) }
|
if (!exists("trimws", "package:base")) {
# trimws was new in R 3.2.0. Backport it for internal data.table use in R 3.1.0
trimws <- function(x) {
mysub <- function(re, x) sub(re, "", x, perl = TRUE)
mysub("[ \t\r\n]+$", mysub("^[ \t\r\n]+", x))
}
}
dim.data.table <- function(x)
{
.Call(Cdim, x)
}
.global <- new.env() # thanks to: http://stackoverflow.com/a/12605694/403310
setPackageName("data.table",.global)
.global$print = ""
.SD = .N = .I = .GRP = .BY = .EACHI = NULL
# These are exported to prevent NOTEs from R CMD check, and checkUsage via compiler.
# But also exporting them makes it clear (to users and other packages) that data.table uses these as symbols.
# And NULL makes it clear (to the R's mask check on loading) that they're variables not functions.
# utils::globalVariables(c(".SD",".N")) was tried as well, but exporting seems better.
# So even though .BY doesn't appear in this file, it should still be NULL here and exported because it's
# defined in SDenv and can be used by users.
is.data.table <- function(x) inherits(x, "data.table")
is.ff <- function(x) inherits(x, "ff") # define this in data.table so that we don't have to require(ff), but if user is using ff we'd like it to work
#NCOL <- function(x) {
# # copied from base, but additionally covers data.table via is.list()
# # because NCOL in base explicitly tests using is.data.frame()
# if (is.list(x) && !is.ff(x)) return(length(x))
# if (is.array(x) && length(dim(x)) > 1L) ncol(x) else as.integer(1L)
#}
#NROW <- function(x) {
# if (is.data.frame(x) || is.data.table(x)) return(nrow(x))
# if (is.list(x) && !is.ff(x)) stop("List is not a data.frame or data.table. Convert first before using NROW") # list may have different length elements, which data.table and data.frame's resolve.
# if (is.array(x)) nrow(x) else length(x)
#}
null.data.table <-function() {
ans = list()
setattr(ans,"class",c("data.table","data.frame"))
setattr(ans,"row.names",.set_row_names(0L))
alloc.col(ans)
}
data.table <-function(..., keep.rownames=FALSE, check.names=FALSE, key=NULL, stringsAsFactors=FALSE)
{
# NOTE: It may be faster in some circumstances to create a data.table by creating a list l first, and then setattr(l,"class",c("data.table","data.frame")) at the expense of checking.
# TO DO: rewrite data.table(), one of the oldest functions here. Many people use data.table() to convert data.frame rather than
# as.data.table which is faster; speed could be better. Revisit how many copies are taken in for example data.table(DT1,DT2) which
# cbind directs to. And the nested loops for recycling lend themselves to being C level.
x <- list(...) # doesn't copy named inputs as from R >= 3.1.0 (a very welcome change)
.Call(CcopyNamedInList,x) # to maintain pre-Rv3.1.0 behaviour, for now. See test 548.2. TODO: revist
# TODO Something strange with NAMED on components of `...` to investigate. Or, just port data.table() to C.
if (length(x) < 1L)
return( null.data.table() )
# fix for #5377 - data.table(null list, data.frame and data.table) should return null data.table. Simple fix: check all scenarios here at the top.
if (identical(x, list(NULL)) || identical(x, list(list())) ||
identical(x, list(data.frame(NULL))) || identical(x, list(data.table(NULL)))) return( null.data.table() )
nd = name_dots(...)
myNCOL = function(x) if (is.null(x)) 0L else NCOL(x) # tmp fix (since NCOL(NULL)==1) until PR#3471 goes ahread in v1.12.4
if (any(nocols<-sapply(x, myNCOL)==0L)) { tt=!nocols; x=x[tt]; nd=lapply(nd,'[',tt); } # data.table(data.table(), data.table(a=integer())), #3445
vnames = nd$vnames
novname = nd$novname # novname used later to know which were explicitly supplied in the call
n <- length(x)
if (length(vnames) != n) stop("logical error in vnames") # nocov
# cast to a list to facilitate naming of columns with dimension --
# unlist() at the end automatically handles the need to "push" names
# to accommodate the "new" columns
vnames <- as.list.default(vnames)
nrows = integer(n) # vector of lengths of each column. may not be equal if silent repetition is required.
numcols = integer(n) # the ncols of each of the inputs (e.g. if inputs contain matrix or data.table)
for (i in seq_len(n)) {
xi = x[[i]]
if (is.null(xi)) stop("Internal error: NULL item ", i," should have been removed from list above") # nocov
if ("POSIXlt" %chin% class(xi)) {
warning("POSIXlt column type detected and converted to POSIXct. We do not recommend use of POSIXlt at all because it uses 40 bytes to store one date. Use as.POSIXct to avoid this warning.")
x[[i]] = as.POSIXct(xi)
} else if (is.matrix(xi) || is.data.frame(xi)) { # including data.table (a data.frame, too)
xi = as.data.table(xi, keep.rownames=keep.rownames) # TO DO: allow a matrix to be a column of a data.table. This could allow a key'd lookup to a matrix, not just by a single rowname vector, but by a combination of several columns. A matrix column could be stored either by row or by column contiguous in memory.
x[[i]] = xi
numcols[i] = length(xi)
} else if (is.table(xi)) {
x[[i]] = xi = as.data.table.table(xi, keep.rownames=keep.rownames)
numcols[i] = length(xi)
} else if (is.function(xi)) {
x[[i]] = xi = list(xi)
}
nrows[i] <- NROW(xi) # for a vector (including list() columns) returns the length
if (numcols[i]>0L) {
namesi <- names(xi) # works for both data.frame's, matrices and data.tables's
if (length(namesi)==0L) namesi = rep.int("",ncol(xi))
namesi[is.na(namesi)] = ""
tt = namesi==""
if (any(tt)) namesi[tt] = paste0("V", which(tt))
if (novname[i]) vnames[[i]] = namesi
else vnames[[i]] = paste(vnames[[i]], namesi, sep=".")
}
}
nr <- max(nrows)
ckey = NULL
recycledkey = FALSE
for (i in seq_len(n)) {
xi = x[[i]]
if (is.data.table(xi) && haskey(xi)) {
if (nrows[i]<nr) recycledkey = TRUE
else ckey = c(ckey, key(xi))
}
}
for (i in which(nrows < nr)) {
# TO DO ... recycle in C, but not high priority as large data already regular from database or file
xi <- x[[i]]
if (identical(xi,list())) {
x[[i]] = vector("list", nr)
next
}
if (nrows[i]==0L) stop("Item ",i," has no length. Provide at least one item (such as NA, NA_integer_ etc) to be repeated to match the ",nr," row", if (nr > 1L) "s", " in the longest column. Or, all columns can be 0 length, for insert()ing rows into.")
# Implementing FR #4813 - recycle with warning when nr %% nrows[i] != 0L
if (nr%%nrows[i] != 0L) warning("Item ", i, " is of size ", nrows[i], " but maximum size is ", nr, " (recycled leaving remainder of ", nr%%nrows[i], " items)")
if (is.data.frame(xi)) { # including data.table
..i = rep(seq_len(nrow(xi)), length.out = nr)
x[[i]] = xi[..i,,drop=FALSE]
next
}
if (is.atomic(xi) || is.list(xi)) {
# TO DO: surely use set() here, or avoid the coercion
x[[i]] = rep(xi, length.out = nr)
next
}
stop("problem recycling column ",i,", try a simpler type")
}
if (any(numcols>0L)) {
value = vector("list",sum(pmax(numcols,1L)))
k = 1L
for(i in seq_len(n)) {
if (is.list(x[[i]]) && !is.ff(x[[i]])) {
for(j in seq_len(length(x[[i]]))) {
value[[k]] = x[[i]][[j]]
k=k+1L
}
} else {
value[[k]] = x[[i]]
k=k+1L
}
}
} else {
value = x
}
vnames <- unlist(vnames)
if (check.names) # default FALSE
vnames <- make.names(vnames, unique = TRUE)
setattr(value,"names",vnames)
setattr(value,"row.names",.set_row_names(nr))
setattr(value,"class",c("data.table","data.frame"))
if (!is.null(key)) {
if (!is.character(key)) stop("key argument of data.table() must be character")
if (length(key)==1L) {
key = strsplit(key,split=",")[[1L]]
# eg key="A,B"; a syntax only useful in key argument to data.table(), really.
}
setkeyv(value,key)
} else {
# retain key of cbind(DT1, DT2, DT3) where DT2 is keyed but not DT1. cbind calls data.table().
# If DT inputs with keys have been recycled then can't retain key
if (length(ckey)
&& !recycledkey
&& !any(duplicated(ckey))
&& all(ckey %chin% names(value))
&& !any(duplicated(names(value)[names(value) %chin% ckey])))
setattr(value, "sorted", ckey)
}
if (isTRUE(stringsAsFactors)) {
for (j in which(vapply(value, is.character, TRUE))) set(value, NULL, j, as_factor(.subset2(value, j)))
# as_factor is internal function in fread.R currently
}
alloc.col(value) # returns a NAMED==0 object, unlike data.frame()
}
replace_dot_alias <- function(e) {
# we don't just simply alias .=list because i) list is a primitive (faster to iterate) and ii) we test for use
# of "list" in several places so it saves having to remember to write "." || "list" in those places
if (is.call(e) && !is.function(e[[1L]])) {
# . alias also used within bquote, #1912
if (e[[1L]] == 'bquote') return(e)
if (e[[1L]] == ".") e[[1L]] = quote(list)
for (i in seq_along(e)[-1L]) if (!is.null(e[[i]])) e[[i]] = replace_dot_alias(e[[i]])
}
e
}
.massagei <- function(x) {
# J alias for list as well in i, just if the first symbol
# if x = substitute(base::order) then as.character(x[[1L]]) == c("::", "base", "order")
if (is.call(x) && as.character(x[[1L]])[[1L]] %chin% c("J","."))
x[[1L]] = quote(list)
x
}
.checkTypos = function(err, ref) {
if (grepl('object.*not found', err$message)) {
used = gsub(".*object '([^']+)'.*", "\\1", err$message)
found = agrep(used, ref, value=TRUE, ignore.case=TRUE, fixed=TRUE)
if (length(found)) {
stop("Object '", used, "' not found. Perhaps you intended ",
paste(head(found, 5L), collapse=", "),
if (length(found)<=5L) "" else paste(" or",length(found)-5L, "more"))
} else {
stop("Object '", used, "' not found amongst ",
paste(head(ref, 5L), collapse=', '),
if (length(ref)<=5L) "" else paste(" and", length(ref)-5L, "more"))
}
} else {
stop(err$message, call.=FALSE)
}
}
"[.data.table" <- function (x, i, j, by, keyby, with=TRUE, nomatch=getOption("datatable.nomatch"), mult="all", roll=FALSE, rollends=if (roll=="nearest") c(TRUE,TRUE) else if (roll>=0) c(FALSE,TRUE) else c(TRUE,FALSE), which=FALSE, .SDcols, verbose=getOption("datatable.verbose"), allow.cartesian=getOption("datatable.allow.cartesian"), drop=NULL, on=NULL)
{
# ..selfcount <<- ..selfcount+1 # in dev, we check no self calls, each of which doubles overhead, or could
# test explicitly if the caller is [.data.table (even stronger test. TO DO.)
# the drop=NULL is to sink drop argument when dispatching to [.data.frame; using '...' stops test 147
if (!cedta()) {
# Fix for #5070 (to do)
Nargs = nargs() - (!missing(drop))
ans = if (Nargs<3L) { `[.data.frame`(x,i) } # drop ignored anyway by DF[i]
else if (missing(drop)) `[.data.frame`(x,i,j)
else `[.data.frame`(x,i,j,drop)
# added is.data.table(ans) check to fix bug #5069
if (!missing(i) & is.data.table(ans)) setkey(ans,NULL) # See test 304
return(ans)
}
.global$print=""
missingby = missing(by) && missing(keyby) # for tests 359 & 590 where passing by=NULL results in data.table not vector
if (!missing(keyby)) {
if (!missing(by)) stop("Provide either by= or keyby= but not both")
if (missing(j)) { warning("Ignoring keyby= because j= is not supplied"); keyby=NULL; }
by=bysub=substitute(keyby)
keyby=TRUE
# Assign to 'by' so that by is no longer missing and we can proceed as if there were one by
} else {
if (!missing(by) && missing(j)) { warning("Ignoring by= because j= is not supplied"); by=NULL; }
by=bysub= if (missing(by)) NULL else substitute(by)
keyby=FALSE
}
bynull = !missingby && is.null(by) #3530
byjoin = !is.null(by) && is.symbol(bysub) && bysub==".EACHI"
if (missing(i) && missing(j)) {
tt_isub = substitute(i)
tt_jsub = substitute(j)
if (!is.null(names(sys.call())) && # not relying on nargs() as it considers DT[,] to have 3 arguments, #3163
tryCatch(!is.symbol(tt_isub), error=function(e)TRUE) && # a symbol that inherits missingness from caller isn't missing for our purpose; test 1974
tryCatch(!is.symbol(tt_jsub), error=function(e)TRUE)) {
warning("i and j are both missing so ignoring the other arguments. This warning will be upgraded to error in future.")
}
return(x)
}
if (!mult %chin% c("first","last","all")) stop("mult argument can only be 'first','last' or 'all'")
missingroll = missing(roll)
if (length(roll)!=1L || is.na(roll)) stop("roll must be a single TRUE, FALSE, positive/negative integer/double including +Inf and -Inf or 'nearest'")
if (is.character(roll)) {
if (roll!="nearest") stop("roll is '",roll,"' (type character). Only valid character value is 'nearest'.")
} else {
roll = if (isTRUE(roll)) +Inf else as.double(roll)
}
force(rollends)
if (!is.logical(rollends)) stop("rollends must be a logical vector")
if (length(rollends)>2L) stop("rollends must be length 1 or 2")
if (length(rollends)==1L) rollends=rep.int(rollends,2L)
# TO DO (document/faq/example). Removed for now ... if ((roll || rolltolast) && missing(mult)) mult="last" # for when there is exact match to mult. This does not control cases where the roll is mult, that is always the last one.
missingnomatch = missing(nomatch)
if (is.null(nomatch)) nomatch = 0L # allow nomatch=NULL API already now, part of: https://github.com/Rdatatable/data.table/issues/857
if (!is.na(nomatch) && nomatch!=0L) stop("nomatch= must be either NA or NULL (or 0 for backwards compatibility which is the same as NULL)")
nomatch = as.integer(nomatch)
if (!is.logical(which) || length(which)>1L) stop("which= must be a logical vector length 1. Either FALSE, TRUE or NA.")
if ((isTRUE(which)||is.na(which)) && !missing(j)) stop("which==",which," (meaning return row numbers) but j is also supplied. Either you need row numbers or the result of j, but only one type of result can be returned.")
if (!is.na(nomatch) && is.na(which)) stop("which=NA with nomatch=0 would always return an empty vector. Please change or remove either which or nomatch.")
if (!with && missing(j)) stop("j must be provided when with=FALSE")
if (missing(i) && !missing(on)) warning("ignoring on= because it is only relevant to i but i is not provided")
irows = NULL # Meaning all rows. We avoid creating 1:nrow(x) for efficiency.
notjoin = FALSE
rightcols = leftcols = integer()
optimizedSubset = FALSE ## flag: tells whether a normal query was optimized into a join.
..syms = NULL
av = NULL
jsub = NULL
if (!missing(j)) {
jsub = replace_dot_alias(substitute(j))
root = if (is.call(jsub)) as.character(jsub[[1L]])[1L] else ""
if (root == ":" ||
(root %chin% c("-","!") && is.call(jsub[[2L]]) && jsub[[2L]][[1L]]=="(" && is.call(jsub[[2L]][[2L]]) && jsub[[2L]][[2L]][[1L]]==":") ||
( (!length(av<-all.vars(jsub)) || all(substring(av,1L,2L)=="..")) &&
root %chin% c("","c","paste","paste0","-","!") &&
missingby )) { # test 763. TODO: likely that !missingby iff with==TRUE (so, with can be removed)
# When no variable names (i.e. symbols) occur in j, scope doesn't matter because there are no symbols to find.
# If variable names do occur, but they are all prefixed with .., then that means look up in calling scope.
# Automatically set with=FALSE in this case so that DT[,1], DT[,2:3], DT[,"someCol"] and DT[,c("colB","colD")]
# work as expected. As before, a vector will never be returned, but a single column data.table
# for type consistency with >1 cases. To return a single vector use DT[["someCol"]] or DT[[3]].
# The root==":" is to allow DT[,colC:colH] even though that contains two variable names.
# root == "-" or "!" is for tests 1504.11 and 1504.13 (a : with a ! or - modifier root)
# We don't want to evaluate j at all in making this decision because i) evaluating could itself
# increment some variable and not intended to be evaluated a 2nd time later on and ii) we don't
# want decisions like this to depend on the data or vector lengths since that can introduce
# inconistency reminiscent of drop=TRUE in [.data.frame that we seek to avoid.
with=FALSE
if (length(av)) {
for (..name in av) {
name = substring(..name, 3L)
if (name=="") stop("The symbol .. is invalid. The .. prefix must be followed by at least one character.")
if (!exists(name, where=parent.frame())) {
stop("Variable '",name,"' is not found in calling scope. Looking in calling scope because you used the .. prefix.",
if (exists(..name, where=parent.frame()))
paste0(" Variable '..",name,"' does exist in calling scope though, so please just removed the .. prefix from that variable name in calling scope.")
# We have recommended 'manual' .. prefix in the past, so try to be helpful
else
""
)
} else if (exists(..name, where=parent.frame())) {
warning("Both '",name,"' and '..", name, "' exist in calling scope. Please remove the '..", name,"' variable in calling scope for clarity.")
}
}
..syms = av
}
} else if (is.name(jsub)) {
if (substring(jsub, 1L, 2L) == "..") stop("Internal error: DT[, ..var] should be dealt with by the branch above now.") # nocov
if (!with && !exists(as.character(jsub), where=parent.frame()))
stop("Variable '",jsub,"' is not found in calling scope. Looking in calling scope because you set with=FALSE. Also, please use .. symbol prefix and remove with=FALSE.")
}
if (root=="{") {
if (length(jsub) == 2L) {
jsub = jsub[[2L]] # to allow {} wrapping of := e.g. [,{`:=`(...)},] [#376]
root = if (is.call(jsub)) as.character(jsub[[1L]])[1L] else ""
} else if (length(jsub) > 2L && is.call(jsub[[2L]]) && jsub[[2L]][[1L]] == ":=") {
#2142 -- j can be {} and have length 1
stop("You have wrapped := with {} which is ok but then := must be the only thing inside {}. You have something else inside {} as well. Consider placing the {} on the RHS of := instead; e.g. DT[,someCol:={tmpVar1<-...;tmpVar2<-...;tmpVar1*tmpVar2}")
}
}
if (root=="eval" && !any(all.vars(jsub[[2L]]) %chin% names(x))) {
# TODO: this && !any depends on data. Can we remove it?
# Grab the dynamic expression from calling scope now to give the optimizer a chance to optimize it
# Only when top level is eval call. Not nested like x:=eval(...) or `:=`(x=eval(...), y=eval(...))
jsub = eval(jsub[[2L]], parent.frame(), parent.frame()) # this evals the symbol to return the dynamic expression
if (is.expression(jsub)) jsub = jsub[[1L]] # if expression, convert it to call
# Note that the dynamic expression could now be := (new in v1.9.7)
root = if (is.call(jsub)) {
jsub = replace_dot_alias(jsub)
as.character(jsub[[1L]])[1L]
} else ""
}
if (root == ":=") {
allow.cartesian=TRUE # (see #800)
if (!missing(i) && keyby)
stop(":= with keyby is only possible when i is not supplied since you can't setkey on a subset of rows. Either change keyby to by or remove i")
if (!missingnomatch) {
warning("nomatch isn't relevant together with :=, ignoring nomatch")
nomatch=0L
}
}
}
# setdiff removes duplicate entries, which'll create issues with duplicated names. Use %chin% instead.
dupdiff <- function(x, y) x[!x %chin% y]
if (!missing(i)) {
xo = NULL
isub = substitute(i)
if (identical(isub, NA)) {
# only possibility *isub* can be NA (logical) is the symbol NA itself; i.e. DT[NA]
# replace NA in this case with NA_integer_ as that's almost surely what user intended to
# return a single row with NA in all columns. (DT[0] returns an empty table, with correct types.)
# Any expression (including length 1 vectors) that evaluates to a single NA logical will
# however be left as NA logical since that's important for consistency to return empty in that
# case; e.g. DT[Col==3] where DT is 1 row and Col contains NA.
# Replacing the NA symbol makes DT[NA] and DT[c(1,NA)] consistent and provides
# an easy way to achieve a single row of NA as users expect rather than requiring them
# to know and change to DT[NA_integer_].
isub=NA_integer_
}
isnull_inames = FALSE
nqgrp = integer(0L) # for non-equi join
nqmaxgrp = 1L # for non-equi join
# Fixes 4994: a case where quoted expression with a "!", ex: expr = quote(!dt1); dt[eval(expr)] requires
# the "eval" to be checked before `as.name("!")`. Therefore interchanged.
restore.N = remove.N = FALSE
if (exists(".N", envir=parent.frame(), inherits=FALSE)) {
old.N = get(".N", envir=parent.frame(), inherits=FALSE)
locked.N = bindingIsLocked(".N", parent.frame())
if (locked.N) eval(call("unlockBinding", ".N", parent.frame())) # eval call to pass R CMD check NOTE until we find cleaner way
assign(".N", nrow(x), envir=parent.frame(), inherits=FALSE)
restore.N = TRUE
# the comment below is invalid hereafter (due to fix for #1145)
# binding locked when .SD[.N] but that's ok as that's the .N we want anyway
# TO DO: change isub at C level s/.N/nrow(x); changing a symbol to a constant should be ok
} else {
assign(".N", nrow(x), envir=parent.frame(), inherits=FALSE)
remove.N = TRUE
}
if (is.call(isub) && isub[[1L]]=="eval") { # TO DO: or ..()
isub = eval(.massagei(isub[[2L]]), parent.frame(), parent.frame())
if (is.expression(isub)) isub=isub[[1L]]
}
if (is.call(isub) && isub[[1L]] == as.name("!")) {
notjoin = TRUE
if (!missingnomatch) stop("not-join '!' prefix is present on i but nomatch is provided. Please remove nomatch.");
nomatch = 0L
isub = isub[[2L]]
# #932 related so that !(v1 == 1) becomes v1 == 1 instead of (v1 == 1) after removing "!"
if (is.call(isub) && isub[[1L]] == "(" && !is.name(isub[[2L]]))
isub = isub[[2L]]
}
if (is.call(isub) && isub[[1L]] == as.name("order") && getOption("datatable.optimize") >= 1) { # optimize here so that we can switch it off if needed
if (verbose) cat("order optimisation is on, i changed from 'order(...)' to 'forder(DT, ...)'.\n")
isub = as.list(isub)
isub = as.call(c(list(quote(forder), quote(x)), isub[-1L]))
}
if (is.null(isub)) return( null.data.table() )
if (is.call(isub) && isub[[1L]] == quote(forder)) {
order_env = new.env(parent=parent.frame()) # until 'forder' is exported
assign("forder", forder, order_env)
assign("x", x, order_env)
i = eval(isub, order_env, parent.frame()) # for optimisation of 'order' to 'forder'
# that forder returns empty integer() is taken care of internally within forder
} else if (length(o <- .prepareFastSubset(isub = isub, x = x,
enclos = parent.frame(),
notjoin = notjoin, verbose = verbose))){
## redirect to the is.data.table(x) == TRUE branch.
## Additional flag to adapt things after bmerge:
optimizedSubset <- TRUE
notjoin <- o$notjoin
i <- o$i
on <- o$on
## the following two are ignored if i is not a data.table.
## Since we are converting i to data.table, it is important to set them properly.
nomatch <- 0L
mult <- "all"
}
else if (!is.name(isub)) {
i = tryCatch(eval(.massagei(isub), x, parent.frame()),
error = function(e) .checkTypos(e, names(x)))
} else {
# isub is a single symbol name such as B in DT[B]
i = try(eval(isub, parent.frame(), parent.frame()), silent=TRUE)
if (inherits(i,"try-error")) {
# must be "not found" since isub is a mere symbol
col = try(eval(isub, x), silent=TRUE) # is it a column name?
if (identical(typeof(col),"logical"))
stop(as.character(isub)," is not found in calling scope but it is a column of type logical. If you wish to select rows where that column is TRUE, either wrap the symbol with '()' or use ==TRUE to be clearest to readers of your code.")
else
stop(as.character(isub)," is not found in calling scope and it is not a column of type logical. When the first argument inside DT[...] is a single symbol, data.table looks for it in calling scope.")
}
}
if (restore.N) {
assign(".N", old.N, envir=parent.frame())
if (locked.N) lockBinding(".N", parent.frame())
}
if (remove.N) rm(list=".N", envir=parent.frame())
if (is.matrix(i)) {
if (is.numeric(i) && ncol(i)==1L) { # #826 - subset DT on single integer vector stored as matrix
i = as.integer(i)
} else {
stop("i is invalid type (matrix). Perhaps in future a 2 column matrix could return a list of elements of DT (in the spirit of A[B] in FAQ 2.14). Please report to data.table issue tracker if you'd like this, or add your comments to FR #657.")
}
}
if (is.logical(i)) {
if (notjoin) {
notjoin = FALSE
i = !i
}
}
if (is.null(i)) return( null.data.table() )
if (is.character(i)) {
isnull_inames = TRUE
i = data.table(V1=i) # for user convenience; e.g. DT["foo"] without needing DT[.("foo")]
} else if (identical(class(i),"list") && length(i)==1L && is.data.frame(i[[1L]])) { i = as.data.table(i[[1L]]) }
else if (identical(class(i),"data.frame")) { i = as.data.table(i) } # TO DO: avoid these as.data.table() and use a flag instead
else if (identical(class(i),"list")) {
isnull_inames = is.null(names(i))
i = as.data.table(i)
}
if (is.data.table(i)) {
if (!haskey(x) && missing(on) && is.null(xo)) {
stop("When i is a data.table (or character vector), the columns to join by must be specified either using 'on=' argument (see ?data.table) or by keying x (i.e. sorted, and, marked as sorted, see ?setkey). Keyed joins might have further speed benefits on very large data due to x being sorted in RAM.")
}
if (!missing(on)) {
# on = .() is now possible, #1257
on_ops = .parse_on(substitute(on), isnull_inames)
on = on_ops[[1L]]
ops = on_ops[[2L]]
# TODO: collect all '==' ops first to speeden up Cnestedid
rightcols = chmatch(names(on), names(x))
if (length(nacols <- which(is.na(rightcols))))
stop("Column(s) [", paste(names(on)[nacols], collapse=","), "] not found in x")
leftcols = chmatch(unname(on), names(i))
if (length(nacols <- which(is.na(leftcols))))
stop("Column(s) [", paste(unname(on)[nacols], collapse=","), "] not found in i")
# figure out the columns on which to compute groups on
non_equi = which.first(ops != 1L) # 1 is "==" operator
if (!is.na(non_equi)) {
# non-equi operators present.. investigate groups..
if (verbose) cat("Non-equi join operators detected ... \n")
if (!missingroll) stop("roll is not implemented for non-equi joins yet.")
if (verbose) {last.started.at=proc.time();cat(" forder took ... ");flush.console()}
# TODO: could check/reuse secondary indices, but we need 'starts' attribute as well!
xo = forderv(x, rightcols, retGrp=TRUE)
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
xg = attr(xo, 'starts')
resetcols = head(rightcols, non_equi-1L)
if (length(resetcols)) {
# TODO: can we get around having to reorder twice here?
# or at least reuse previous order?
if (verbose) {last.started.at=proc.time();cat(" Generating group lengths ... ");flush.console()}
resetlen = attr(forderv(x, resetcols, retGrp=TRUE), 'starts')
resetlen = .Call(Cuniqlengths, resetlen, nrow(x))
if (verbose) {cat("done in",timetaken(last.started.at),"\n"); flush.console()}
} else resetlen = integer(0L)
if (verbose) {last.started.at=proc.time();cat(" Generating non-equi group ids ... ");flush.console()}
nqgrp = .Call(Cnestedid, x, rightcols[non_equi:length(rightcols)], xo, xg, resetlen, mult)
if (verbose) {cat("done in",timetaken(last.started.at),"\n"); flush.console()}
if (length(nqgrp)) nqmaxgrp = max(nqgrp) # fix for #1986, when 'x' is 0-row table max(.) returns -Inf.
if (nqmaxgrp > 1L) { # got some non-equi join work to do
if ("_nqgrp_" %chin% names(x)) stop("Column name '_nqgrp_' is reserved for non-equi joins.")
if (verbose) {last.started.at=proc.time();cat(" Recomputing forder with non-equi ids ... ");flush.console()}
set(nqx<-shallow(x), j="_nqgrp_", value=nqgrp)
xo = forderv(nqx, c(ncol(nqx), rightcols))
if (verbose) {cat("done in",timetaken(last.started.at),"\n"); flush.console()}
} else nqgrp = integer(0L)
if (verbose) cat(" Found", nqmaxgrp, "non-equi group(s) ...\n")
}
if (is.na(non_equi)) {
# equi join. use existing key (#1825) or existing secondary index (#1439)
if ( identical(head(key(x), length(on)), names(on)) ) {
xo = integer(0L)
if (verbose) cat("on= matches existing key, using key\n")
} else {
if (isTRUE(getOption("datatable.use.index"))) {
xo = getindex(x, names(on))
if (verbose && !is.null(xo)) cat("on= matches existing index, using index\n")
}
if (is.null(xo)) {
if (verbose) {last.started.at=proc.time(); flush.console()}
xo = forderv(x, by = rightcols)
if (verbose) {cat("Calculated ad hoc index in",timetaken(last.started.at),"\n"); flush.console()}
# TODO: use setindex() instead, so it's cached for future reuse
}
}
}
} else if (is.null(xo)) {
rightcols = chmatch(key(x),names(x)) # NAs here (i.e. invalid data.table) checked in bmerge()
leftcols = if (haskey(i))
chmatch(head(key(i),length(rightcols)),names(i))
else
seq_len(min(length(i),length(rightcols)))
rightcols = head(rightcols,length(leftcols))
xo = integer(0L) ## signifies 1:.N
ops = rep(1L, length(leftcols))
}
# Implementation for not-join along with by=.EACHI, #604
if (notjoin && (byjoin || mult != "all")) { # mult != "all" needed for #1571 fix
notjoin = FALSE
if (verbose) {last.started.at=proc.time();cat("not-join called with 'by=.EACHI'; Replacing !i with i=setdiff_(x,i) ...");flush.console()}
orignames = copy(names(i))
i = setdiff_(x, i, rightcols, leftcols) # part of #547
if (verbose) {cat("done in",timetaken(last.started.at),"\n"); flush.console()}
setnames(i, orignames[leftcols])
setattr(i, 'sorted', names(i)) # since 'x' has key set, this'll always be sorted
}
i = .shallow(i, retain.key = TRUE)
ans = bmerge(i, x, leftcols, rightcols, xo, roll, rollends, nomatch, mult, ops, nqgrp, nqmaxgrp, verbose=verbose)
# temp fix for issue spotted by Jan, test #1653.1. TODO: avoid this
# 'setorder', as there's another 'setorder' in generating 'irows' below...
if (length(ans$indices)) setorder(setDT(ans[1L:3L]), indices)
allLen1 = ans$allLen1
f__ = ans$starts
len__ = ans$lens
allGrp1 = FALSE # was previously 'ans$allGrp1'. Fixing #1991. TODO: Revisit about allGrp1 possibility for speedups in certain cases when I find some time.
indices__ = if (length(ans$indices)) ans$indices else seq_along(f__) # also for #1991 fix
# length of input nomatch (single 0 or NA) is 1 in both cases.
# When no match, len__ is 0 for nomatch=0 and 1 for nomatch=NA, so len__ isn't .N
# If using secondary key of x, f__ will refer to xo
if (is.na(which)) {
w = if (notjoin) f__!=0L else is.na(f__)
return( if (length(xo)) fsort(xo[w], internal=TRUE) else which(w) )
}
if (mult=="all") {
# is by=.EACHI along with non-equi join?
nqbyjoin = byjoin && length(ans$indices) && !allGrp1
if (!byjoin || nqbyjoin) {
# Really, `anyDuplicated` in base is AWESOME!
# allow.cartesian shouldn't error if a) not-join, b) 'i' has no duplicates
if (verbose) {last.started.at=proc.time();cat("Constructing irows for '!byjoin || nqbyjoin' ... ");flush.console()}
irows = if (allLen1) f__ else vecseq(f__,len__,
if (allow.cartesian ||
notjoin || # #698. When notjoin=TRUE, ignore allow.cartesian. Rows in answer will never be > nrow(x).
!anyDuplicated(f__, incomparables = c(0L, NA_integer_))) {
NULL # #742. If 'i' has no duplicates, ignore
} else as.double(nrow(x)+nrow(i))) # rows in i might not match to x so old max(nrow(x),nrow(i)) wasn't enough. But this limit now only applies when there are duplicates present so the reason now for nrow(x)+nrow(i) is just to nail it down and be bigger than max(nrow(x),nrow(i)).
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
# Fix for #1092 and #1074
# TODO: implement better version of "any"/"all"/"which" to avoid
# unnecessary construction of logical vectors
if (identical(nomatch, 0L) && allLen1) irows = irows[irows != 0L]
} else {
if (length(xo) && missing(on))
stop("Internal error. Cannot by=.EACHI when joining to a secondary key, yet") # nocov
# since f__ refers to xo later in grouping, so xo needs to be passed through to dogroups too.
if (length(irows))
stop("Internal error. irows has length in by=.EACHI") # nocov
}
if (nqbyjoin) {
irows = if (length(xo)) xo[irows] else irows
xo = setorder(setDT(list(indices=rep.int(indices__, len__), irows=irows)))[["irows"]]
ans = .Call(CnqRecreateIndices, xo, len__, indices__, max(indices__))
f__ = ans[[1L]]; len__ = ans[[2L]]
allLen1 = FALSE # TODO; should this always be FALSE?
irows = NULL # important to reset
if (any_na(as_list(xo))) xo = xo[!is.na(xo)]
}
} else {
# turning on mult = "first"/"last" for non-equi joins again to test..
# if (nqmaxgrp>1L) stop("Non-equi joins aren't yet functional with mult='first' and mult='last'.")
# mult="first"/"last" logic moved to bmerge.c, also handles non-equi cases, #1452
if (!byjoin) { #1287 and #1271
irows = f__ # len__ is set to 1 as well, no need for 'pmin' logic
if (identical(nomatch,0L)) irows = irows[len__>0L] # 0s are len 0, so this removes -1 irows
}
# TODO: when nomatch=NA, len__ need not be allocated / set at all for mult="first"/"last"?
# TODO: how about when nomatch=0L, can we avoid allocating then as well?
}
if (length(xo) && length(irows)) {
irows = xo[irows] # TO DO: fsort here?
if (mult=="all" && !allGrp1) { # following #1991 fix, !allGrp1 will always be TRUE. TODO: revisit.
if (verbose) {last.started.at=proc.time();cat("Reorder irows for 'mult==\"all\" && !allGrp1' ... ");flush.console()}
irows = setorder(setDT(list(indices=rep.int(indices__, len__), irows=irows)))[["irows"]]
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
}
}
if (optimizedSubset){
## special treatment for calls like DT[x == 3] that are transformed into DT[J(x=3), on = "x==x"]
if(!.Call(CisOrderedSubset, irows, nrow(x))){
## restore original order. This is a very expensive operation.
## benchmarks have shown that starting with 1e6 irows, a tweak can significantly reduce time
## (see #2366)
if (verbose) {last.started.at=proc.time()[3];cat("Reordering", length(irows), "rows after bmerge done in ... ");flush.console()}
if(length(irows) < 1e6){
irows = fsort(irows, internal=TRUE) ## internally, fsort on integer falls back to forderv
} else {
irows = as.integer(fsort(as.numeric(irows))) ## nocov; parallelized for numeric, but overhead of type conversion
}
if (verbose) {cat(round(proc.time()[3]-last.started.at,3),"secs\n");flush.console()}
}
## make sure, all columns are taken from x and not from i.
## This is done by simply telling data.table to continue as if there was a simple subset
leftcols = integer(0L)
rightcols = integer(0L)
i <- irows ## important to make i not a data.table because otherwise Gforce doesn't kick in
}
}
else {
if (!missing(on)) {
stop("logical error. i is not a data.table, but 'on' argument is provided.")
}
# TO DO: TODO: Incorporate which_ here on DT[!i] where i is logical. Should avoid i = !i (above) - inefficient.
# i is not a data.table
if (!is.logical(i) && !is.numeric(i)) stop("i has not evaluated to logical, integer or double")
if (is.logical(i)) {
if (length(i)==1L # to avoid unname copy when length(i)==nrow (normal case we don't want to slow down)
&& isTRUE(unname(i))) { irows=i=NULL } # unname() for #2152 - length 1 named logical vector.
# NULL is efficient signal to avoid creating 1:nrow(x) but still return all rows, fixes #1249
else if (length(i)<=1L) { irows=i=integer(0L) }
# FALSE, NA and empty. All should return empty data.table. The NA here will be result of expression,
# where for consistency of edge case #1252 all NA to be removed. If NA is a single NA symbol, it
# was auto converted to NA_integer_ higher up for ease of use and convenience. We definitely
# don't want base R behaviour where DF[NA,] returns an entire copy filled with NA everywhere.
else if (length(i)==nrow(x)) { irows=i=which(i) }
# The which() here auto removes NA for convenience so user doesn't need to remember "!is.na() & ..."
# Also this which() is for consistenty of DT[colA>3,which=TRUE] and which(DT[,colA>3])
# Assigning to 'i' here as well to save memory, #926.
else stop("i evaluates to a logical vector length ", length(i), " but there are ", nrow(x), " rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle.")
} else {
irows = as.integer(i) # e.g. DT[c(1,3)] and DT[c(-1,-3)] ok but not DT[c(1,-3)] (caught as error)
irows = .Call(CconvertNegAndZeroIdx, irows, nrow(x), is.null(jsub) || root!=":=") # last argument is allowOverMax (NA when selecting, error when assigning)
# simplifies logic from here on: can assume positive subscripts (no zeros)
# maintains Arun's fix for #2697 (test 1042)
# efficient in C with more detailed helpful messages when user mixes positives and negatives
# falls through quickly (no R level allocs) if all items are within range [1,max] with no zeros or negatives
# minor TO DO: can we merge this with check_idx in fcast.c/subset ?
}
}
if (notjoin) {
if (byjoin || !is.integer(irows) || is.na(nomatch)) stop("Internal error: notjoin but byjoin or !integer or nomatch==NA") # nocov
irows = irows[irows!=0L]
if (verbose) {last.started.at=proc.time()[3];cat("Inverting irows for notjoin done in ... ");flush.console()}
i = irows = if (length(irows)) seq_len(nrow(x))[-irows] else NULL # NULL meaning all rows i.e. seq_len(nrow(x))
if (verbose) cat(round(proc.time()[3]-last.started.at, 3), "sec\n")
leftcols = integer() # proceed as if row subset from now on, length(leftcols) is switched on later
rightcols = integer()
# Doing this once here, helps speed later when repeatedly subsetting each column. R's [irows] would do this for each
# column when irows contains negatives.
}
if (which) return( if (is.null(irows)) seq_len(nrow(x)) else irows )
} else { # missing(i)
i = NULL
}
byval = NULL
xnrow = nrow(x)
xcols = xcolsAns = icols = icolsAns = integer()
xdotcols = FALSE
othervars = character(0L)
if (missing(j)) {
# missingby was already checked above before dealing with i
if (!length(x)) return(null.data.table())
if (!length(leftcols)) {
# basic x[i] subset, #2951
if (is.null(irows)) return(shallow(x)) # e.g. DT[TRUE] (#3214); otherwise CsubsetDT would materialize a deep copy
else return(.Call(CsubsetDT, x, irows, seq_along(x)) )
} else {
jisvars = names(i)[-leftcols]
tt = jisvars %chin% names(x)
if (length(tt)) jisvars[tt] = paste0("i.",jisvars[tt])
if (length(duprightcols <- rightcols[duplicated(rightcols)])) {
nx = c(names(x), names(x)[duprightcols])
rightcols = chmatchdup(names(x)[rightcols], nx)
nx = make.unique(nx)
} else nx = names(x)
ansvars = make.unique(c(nx, jisvars))
icols = c(leftcols, seq_along(i)[-leftcols])
icolsAns = c(rightcols, seq.int(length(nx)+1L, length.out=ncol(i)-length(unique(leftcols))))
xcols = xcolsAns = seq_along(x)[-rightcols]
}
ansvals = chmatch(ansvars, nx)
}
else {
if (is.data.table(i)) {
idotprefix = paste0("i.", names(i))
xdotprefix = paste0("x.", names(x))
} else idotprefix = xdotprefix = character(0L)
# j was substituted before dealing with i so that := can set allow.cartesian=FALSE (#800) (used above in i logic)
if (is.null(jsub)) return(NULL)
if (!with && is.call(jsub) && jsub[[1L]]==":=") {
# TODO: make these both errors (or single long error in both cases) in next release.
# i.e. using with=FALSE together with := at all will become an error. Eventually with will be removed.
if (is.null(names(jsub)) && is.name(jsub[[2L]])) {
warning("with=FALSE together with := was deprecated in v1.9.4 released Oct 2014. Please wrap the LHS of := with parentheses; e.g., DT[,(myVar):=sum(b),by=a] to assign to column name(s) held in variable myVar. See ?':=' for other examples. As warned in 2014, this is now a warning.")
jsub[[2L]] = eval(jsub[[2L]], parent.frame(), parent.frame())
} else {
warning("with=FALSE ignored, it isn't needed when using :=. See ?':=' for examples.")
}
with = TRUE
}
if (!with) {
# missingby was already checked above before dealing with i
if (is.call(jsub) && deparse(jsub[[1L]], 500L, backtick=FALSE) %chin% c("!", "-")) { # TODO is deparse avoidable here?
notj = TRUE
jsub = jsub[[2L]]
} else notj = FALSE
# fix for #1216, make sure the paranthesis are peeled from expr of the form (((1:4)))
while (is.call(jsub) && jsub[[1L]] == "(") jsub = as.list(jsub)[[-1L]]
if (is.call(jsub) && length(jsub) == 3L && jsub[[1L]] == ":") {
j = eval(jsub, setattr(as.list(seq_along(x)), 'names', names(x)), parent.frame()) # else j will be evaluated for the first time on next line
} else {
names(..syms) = ..syms
j = eval(jsub, lapply(substring(..syms,3L), get, pos=parent.frame()), parent.frame())
}
if (is.logical(j)) j <- which(j)
if (!length(j)) return( null.data.table() )
if (is.factor(j)) j = as.character(j) # fix for FR: #4867
if (is.character(j)) {
if (notj) {
w = chmatch(j, names(x))
if (anyNA(w)) warning("column(s) not removed because not found: ",paste(j[is.na(w)],collapse=","))
# all duplicates of the name in names(x) must be removed; e.g. data.table(x=1, y=2, x=3)[, !"x"] should just output 'y'.
w = !names(x) %chin% j
ansvars = names(x)[w]
ansvals = which(w)
} else {
# if DT[, c("x","x")] and "x" is duplicated in names(DT), we still subset only the first. Because dups are unusual and
# it's more common to select the same column a few times. A syntax would be needed to distinguish these intents.
ansvars = j # x. and i. prefixes may be in here, they'll result in NA and will be dealt with further below if length(leftcols)
ansvals = chmatch(ansvars, names(x)) # not chmatchdup()
}
if (!length(ansvals)) return(null.data.table())
if (!length(leftcols)) {
if (!anyNA(ansvals)) return(.Call(CsubsetDT, x, irows, ansvals))
else stop("column(s) not found: ", paste(ansvars[is.na(ansvals)],collapse=", "))
}
# else the NA in ansvals are for join inherited scope (test 1973), and NA could be in irows from join and data in i should be returned (test 1977)
# in both cases leave to the R-level subsetting of i and x together further below
} else if (is.numeric(j)) {
j = as.integer(j)
if (any(w<-(j>ncol(x)))) stop("Item ",which.first(w)," of j is ",j[which.first(w)]," which is outside the column number range [1,ncol=", ncol(x),"]")
j = j[j!=0L]
if (any(j<0L)) {
if (any(j>0L)) stop("j mixes positives and negatives")
j = seq_along(x)[j] # all j are <0 here
}
if (notj && length(j)) j = seq_along(x)[-j]
if (!length(j)) return(null.data.table())
return(.Call(CsubsetDT, x, irows, j))
} else {
stop("When with=FALSE, j-argument should be of type logical/character/integer indicating the columns to select.") # fix for #1440.
}
} else { # with=TRUE and byjoin could be TRUE
bynames = NULL
allbyvars = NULL
if (byjoin) {
bynames = names(x)[rightcols]
} else if (!missingby) {
# deal with by before j because we need byvars when j contains .SD
# may evaluate to NULL | character() | "" | list(), likely a result of a user expression where no-grouping is one case being loop'd through
bysubl = as.list.default(bysub)
bysuborig = bysub
if (is.name(bysub) && !(as.character(bysub) %chin% names(x))) { # TO DO: names(x),names(i),and i. and x. prefixes
bysub = eval(bysub, parent.frame(), parent.frame())
# fix for # 5106 - http://stackoverflow.com/questions/19983423/why-by-on-a-vector-not-from-a-data-table-column-is-very-slow
# case where by=y where y is not a column name, and not a call/symbol/expression, but an atomic vector outside of DT.
# note that if y is a list, this'll return an error (not sure if it should).
if (is.atomic(bysub)) bysubl = list(bysuborig) else bysubl = as.list.default(bysub)
}
if (length(bysubl) && identical(bysubl[[1L]],quote(eval))) { # TO DO: or by=..()
bysub = eval(bysubl[[2L]], parent.frame(), parent.frame())
bysub = replace_dot_alias(bysub) # fix for #1298
if (is.expression(bysub)) bysub=bysub[[1L]]
bysubl = as.list.default(bysub)
} else if (is.call(bysub) && as.character(bysub[[1L]]) %chin% c("c","key","names", "intersect", "setdiff")) {
# catch common cases, so we don't have to copy x[irows] for all columns
# *** TO DO ***: try() this eval first (as long as not list() or .()) and see if it evaluates to column names
# to avoid the explicit c,key,names which already misses paste("V",1:10) for example
# tried before but since not wrapped in try() it failed on some tests
# or look for column names used in this by (since if none it wouldn't find column names anyway
# when evaled within full x[irows]). Trouble is that colA%%2L is a call and should be within frame.
tt = eval(bysub, parent.frame(), parent.frame())
if (!is.character(tt)) stop("by=c(...), key(...) or names(...) must evaluate to 'character'")
bysub=tt
} else if (is.call(bysub) && !as.character(bysub[[1L]]) %chin% c("list", "as.list", "{", ".", ":")) {
# potential use of function, ex: by=month(date). catch it and wrap with "(", because we need to set "bysameorder" to FALSE as we don't know if the function will return ordered results just because "date" is ordered. Fixes #2670.
bysub = as.call(c(as.name('('), list(bysub)))
bysubl = as.list.default(bysub)
} else if (is.call(bysub) && bysub[[1L]] == ".") bysub[[1L]] = quote(list)
if (mode(bysub) == "character") {
if (length(grep(",", bysub, fixed = TRUE))) {
if (length(bysub)>1L) stop("'by' is a character vector length ",length(bysub)," but one or more items include a comma. Either pass a vector of column names (which can contain spaces, but no commas), or pass a vector length 1 containing comma separated column names. See ?data.table for other possibilities.")
bysub = strsplit(bysub,split=",")[[1L]]
}
backtick_idx = grep("^[^`]+$",bysub)
if (length(backtick_idx)) bysub[backtick_idx] = paste0("`",bysub[backtick_idx],"`")
backslash_idx = grep("\\", bysub, fixed = TRUE)
if (length(backslash_idx)) bysub[backslash_idx] = gsub('\\', '\\\\', bysub[backslash_idx], fixed = TRUE)
bysub = parse(text=paste0("list(",paste(bysub,collapse=","),")"))[[1L]]
bysubl = as.list.default(bysub)
}
allbyvars = intersect(all.vars(bysub),names(x))
orderedirows = .Call(CisOrderedSubset, irows, nrow(x)) # TRUE when irows is NULL (i.e. no i clause). Similar but better than is.sorted(f__)
bysameorder = byindex = FALSE
if (all(vapply_1b(bysubl, is.name))) {
bysameorder = orderedirows && haskey(x) && length(allbyvars) && identical(allbyvars,head(key(x),length(allbyvars)))
# either bysameorder or byindex can be true but not both. TODO: better name for bysameorder might be bykeyx
if (!bysameorder && keyby && !length(irows) && isTRUE(getOption("datatable.use.index"))) {
# TODO: could be allowed if length(irows)>1 but then the index would need to be squashed for use by uniqlist, #3062
# find if allbyvars is leading subset of any of the indices; add a trailing "__" to fix #3498 where a longer column name starts with a shorter column name
tt = paste0(c(allbyvars,""), collapse="__")
w = which.first(substring(paste0(indices(x),"__"),1L,nchar(tt)) == tt)
if (!is.na(w)) {
byindex = indices(x)[w]
if (!length(getindex(x, byindex))) {
if (verbose) cat("by index '", byindex, "' but that index has 0 length. Ignoring.\n", sep="")
byindex=FALSE
}
}
}
}
if (is.null(irows)) {
if (is.call(bysub) && length(bysub) == 3L && bysub[[1L]] == ":" && is.name(bysub[[2L]]) && is.name(bysub[[3L]])) {
byval = eval(bysub, setattr(as.list(seq_along(x)), 'names', names(x)), parent.frame())
byval = as.list(x)[byval]
} else byval = eval(bysub, x, parent.frame())
} else {
# length 0 when i returns no rows
if (!is.integer(irows)) stop("Internal error: irows isn't integer") # nocov
# Passing irows as i to x[] below has been troublesome in a rare edge case.
# irows may contain NA, 0, negatives and >nrow(x) here. That's all ok.
# But we may need i join column values to be retained (where those rows have no match), hence we tried eval(isub)
# in 1.8.3, but this failed test 876.
# TO DO: Add a test like X[i,sum(v),by=i.x2], or where by includes a join column (both where some i don't match).
# TO DO: Make xss directly, rather than recursive call.
if (!is.na(nomatch)) irows = irows[irows!=0L] # TO DO: can be removed now we have CisSortedSubset
if (length(allbyvars)) { ############### TO DO TO DO TO DO ###############
if (verbose) cat("i clause present and columns used in by detected, only these subset:",paste(allbyvars,collapse=","),"\n")
xss = x[irows,allbyvars,with=FALSE,nomatch=nomatch,mult=mult,roll=roll,rollends=rollends]
} else {
if (verbose) cat("i clause present but columns used in by not detected. Having to subset all columns before evaluating 'by': '",deparse(by),"'\n",sep="")
xss = x[irows,nomatch=nomatch,mult=mult,roll=roll,rollends=rollends]
}
if (is.call(bysub) && length(bysub) == 3L && bysub[[1L]] == ":") {
byval = eval(bysub, setattr(as.list(seq_along(xss)), 'names', names(xss)), parent.frame())
byval = as.list(xss)[byval]
} else byval = eval(bysub, xss, parent.frame())
xnrow = nrow(xss)
# TO DO: pass xss (x subset) through into dogroups. Still need irows there (for :=), but more condense
# and contiguous to use xss to form .SD in dogroups than going via irows
}
if (!length(byval) && xnrow>0L) {
# see missingby up above for comments
# by could be NULL or character(0L) for example (e.g. passed in as argument in a loop of different bys)
bysameorder = FALSE # 1st and only group is the entire table, so could be TRUE, but FALSE to avoid
# a key of empty character()
byval = list()
bynames = allbyvars = NULL
# the rest now fall through
} else bynames = names(byval)
if (is.atomic(byval)) {
if (is.character(byval) && length(byval)<=ncol(x) && !(is.name(bysub) && as.character(bysub)%chin%names(x)) ) {
stop("'by' appears to evaluate to column names but isn't c() or key(). Use by=list(...) if you can. Otherwise, by=eval",deparse(bysub)," should work. This is for efficiency so data.table can detect which columns are needed.")
} else {
# by may be a single unquoted column name but it must evaluate to list so this is a convenience to users. Could also be a single expression here such as DT[,sum(v),by=colA%%2]
byval = list(byval)
bysubl = c(as.name("list"),bysuborig) # for guessing the column name below
if (is.name(bysuborig))
bynames = as.character(bysuborig)
else
bynames = names(byval)
}
}
if (!is.list(byval)) stop("'by' or 'keyby' must evaluate to a vector or a list of vectors (where 'list' includes data.table and data.frame which are lists, too)")
if (length(byval)==1L && is.null(byval[[1L]])) bynull=TRUE #3530 when by=(function()NULL)()
if (!bynull) for (jj in seq_len(length(byval))) {
if (!typeof(byval[[jj]]) %chin% c("integer","logical","character","double")) stop("column or expression ",jj," of 'by' or 'keyby' is type ",typeof(byval[[jj]]),". Do not quote column names. Usage: DT[,sum(colC),by=list(colA,month(colB))]")
}
tt = vapply_1i(byval,length)
if (any(tt!=xnrow)) stop("The items in the 'by' or 'keyby' list are length (",paste(tt,collapse=","),"). Each must be length ", xnrow, "; the same length as there are rows in x (after subsetting if i is provided).")
if (is.null(bynames)) bynames = rep.int("",length(byval))
if (any(bynames=="") && !bynull) {
for (jj in seq_along(bynames)) {
if (bynames[jj]=="") {
# Best guess. Use "month" in the case of by=month(date), use "a" in the case of by=a%%2
byvars = all.vars(bysubl[[jj+1L]], functions = TRUE)
if (length(byvars) == 1L) tt = byvars
else {
tt = grep("^eval|^[^[:alpha:]. ]",byvars,invert=TRUE,value=TRUE)
if (length(tt)) tt = tt[1L] else all.vars(bysubl[[jj+1L]])[1L]
}
# fix for #497
if (length(byvars) > 1L && tt %chin% all.vars(jsub, FALSE)) {
bynames[jj] = deparse(bysubl[[jj+1L]])
if (verbose)
cat("by-expression '", bynames[jj], "' is not named, and the auto-generated name '", tt,
"' clashed with variable(s) in j. Therefore assigning the entire by-expression as name.\n", sep="")
}
else bynames[jj] = tt
# if user doesn't like this inferred name, user has to use by=list() to name the column
}
}
# Fix for #1334
if (any(duplicated(bynames))) {
bynames = make.unique(bynames)
}
}
setattr(byval, "names", bynames) # byval is just a list not a data.table hence setattr not setnames
}
jvnames = NULL
if (is.name(jsub)) {
# j is a single unquoted column name
if (jsub!=".SD") {
jvnames = gsub("^[.](N|I|GRP|BY)$","\\1",as.character(jsub))
# jsub is list()ed after it's eval'd inside dogroups.
}
} else if (is.call(jsub) && as.character(jsub[[1L]])[[1L]] %chin% c("list",".")) {
jsub[[1L]] = quote(list)
jsubl = as.list.default(jsub) # TO DO: names(jsub) and names(jsub)="" seem to work so make use of that
if (length(jsubl)>1L) {
jvnames = names(jsubl)[-1L] # check list(a=sum(v),v)
if (is.null(jvnames)) jvnames = rep.int("", length(jsubl)-1L)
for (jj in seq.int(2L,length(jsubl))) {
if (jvnames[jj-1L] == "" && mode(jsubl[[jj]])=="name") {
if (jsubl[[jj]]=="") stop("Item ", jj-1L, " of the .() or list() passed to j is missing") #3507
jvnames[jj-1L] = gsub("^[.](N|I|GRP|BY)$", "\\1", deparse(jsubl[[jj]]))
}
# TO DO: if call to a[1] for example, then call it 'a' too
}
setattr(jsubl, "names", NULL) # drops the names from the list so it's faster to eval the j for each group. We'll put them back aftwards on the result.
jsub = as.call(jsubl)
} # else empty list is needed for test 468: adding an empty list column
} # else maybe a call to transform or something which returns a list.
av = all.vars(jsub,TRUE) # TRUE fixes bug #1294 which didn't see b in j=fns[[b]](c)
use.I = ".I" %chin% av
# browser()
if (any(c(".SD","eval","get","mget") %chin% av)) {
if (missing(.SDcols)) {
# here we need to use 'dupdiff' instead of 'setdiff'. Ex: setdiff(c("x", "x"), NULL) will give 'x'.
ansvars = dupdiff(names(x),union(bynames,allbyvars)) # TO DO: allbyvars here for vars used by 'by'. Document.
# just using .SD in j triggers all non-by columns in the subset even if some of
# those columns are not used. It would be tricky to detect whether the j expression
# really does use all of the .SD columns or not, hence .SDcols for grouping
# over a subset of columns
# all duplicate columns must be matched, because nothing is provided
ansvals = chmatchdup(ansvars, names(x))
} else {
# FR #4979 - negative numeric and character indices for SDcols
colsub = substitute(.SDcols)
# fix for #5190. colsub[[1L]] gave error when it's a symbol.
if (is.call(colsub) && deparse(colsub[[1L]], 500L, backtick=FALSE) %chin% c("!", "-")) {
colm = TRUE
colsub = colsub[[2L]]
} else colm = FALSE
# fix for #1216, make sure the paranthesis are peeled from expr of the form (((1:4)))
while(is.call(colsub) && colsub[[1L]] == "(") colsub = as.list(colsub)[[-1L]]
if (is.call(colsub) && length(colsub) == 3L && colsub[[1L]] == ":") {
# .SDcols is of the format a:b
.SDcols = eval(colsub, setattr(as.list(seq_along(x)), 'names', names(x)), parent.frame())
} else {
if (is.call(colsub) && colsub[[1L]] == "patterns") {
# each pattern gives a new filter condition, intersect the end result
.SDcols = Reduce(intersect, do_patterns(colsub, names(x)))
} else {
.SDcols = eval(colsub, parent.frame(), parent.frame())
}
}
if (anyNA(.SDcols))
stop(".SDcols missing at the following indices: ", brackify(which(is.na(.SDcols))))
if (is.logical(.SDcols)) {
ansvals = which_(rep(.SDcols, length.out=length(x)), !colm)
ansvars = names(x)[ansvals]
} else if (is.numeric(.SDcols)) {
# if .SDcols is numeric, use 'dupdiff' instead of 'setdiff'
if (length(unique(sign(.SDcols))) > 1L) stop(".SDcols is numeric but has both +ve and -ve indices")
if (any(idx <- abs(.SDcols)>ncol(x) | abs(.SDcols)<1L))
stop(".SDcols is numeric but out of bounds [1, ", ncol(x), "] at: ", brackify(which(idx)))
if (colm) ansvars = dupdiff(names(x)[-.SDcols], bynames) else ansvars = names(x)[.SDcols]
ansvals = if (colm) setdiff(seq_along(names(x)), c(as.integer(.SDcols), which(names(x) %chin% bynames))) else as.integer(.SDcols)
} else {
if (!is.character(.SDcols)) stop(".SDcols should be column numbers or names")
if (!all(idx <- .SDcols %chin% names(x)))
stop("Some items of .SDcols are not column names: ", brackify(.SDcols[!idx]))
if (colm) ansvars = setdiff(setdiff(names(x), .SDcols), bynames) else ansvars = .SDcols
# dups = FALSE here. DT[, .SD, .SDcols=c("x", "x")] again doesn't really help with which 'x' to keep (and if '-' which x to remove)
ansvals = chmatch(ansvars, names(x))
}
}
# fix for long standing FR/bug, #495 and #484
allcols = c(names(x), xdotprefix, names(i), idotprefix)
if ( length(othervars <- setdiff(intersect(av, allcols), c(bynames, ansvars))) ) {
# we've a situation like DT[, c(sum(V1), lapply(.SD, mean)), by=., .SDcols=...] or
# DT[, lapply(.SD, function(x) x *v1), by=, .SDcols=...] etc.,
ansvars = union(ansvars, othervars)
ansvals = chmatch(ansvars, names(x))
}
# .SDcols might include grouping columns if users wants that, but normally we expect user not to include them in .SDcols
} else {
if (!missing(.SDcols)) warning("This j doesn't use .SD but .SDcols has been supplied. Ignoring .SDcols. See ?data.table.")
allcols = c(names(x), xdotprefix, names(i), idotprefix)
ansvars = setdiff(intersect(av,allcols), bynames)
if (verbose) cat("Detected that j uses these columns:",if (!length(ansvars)) "<none>" else paste(ansvars,collapse=","),"\n")
# using a few named columns will be faster
# Consider: DT[,max(diff(date)),by=list(month=month(date))]
# and: DT[,lapply(.SD,sum),by=month(date)]
# We don't want date in .SD in the latter, but we do in the former; hence the union() above.
ansvals = chmatch(ansvars, names(x))
}
# if (!length(ansvars)) Leave ansvars empty. Important for test 607.
# TODO remove as (m)get is now folded in above.
# added 'mget' - fix for #994
if (any(c("get", "mget") %chin% av)) {
if (verbose) {
cat("'(m)get' found in j. ansvars being set to all columns. Use .SDcols or a single j=eval(macro) instead. Both will detect the columns used which is important for efficiency.\nOld:", paste(ansvars,collapse=","),"\n")
# get('varname') is too difficult to detect which columns are used in general
# eval(macro) column names are detected via the if jsub[[1]]==eval switch earlier above.
}
# Do not include z in .SD when dt[, z := {.SD; get("x")}, .SDcols = "y"] (#2326, #2338)
if (is.call(jsub) && length(jsub[[1L]]) == 1L && jsub[[1L]] == ":=" && is.symbol(jsub[[2L]])) {
jsub_lhs_symbol <- as.character(jsub[[2L]])
if (jsub_lhs_symbol %chin% othervars) {
ansvars <- setdiff(ansvars, jsub_lhs_symbol)
}
}
if (length(ansvars)) othervars = ansvars # #1744 fix
allcols = c(names(x), xdotprefix, names(i), idotprefix)
ansvars = setdiff(allcols,bynames) # fix for bug #5443
ansvals = chmatch(ansvars, names(x))
if (length(othervars)) othervars = setdiff(ansvars, othervars) # #1744 fix
if (verbose) cat("New:",paste(ansvars,collapse=","),"\n")
}
lhs = NULL
newnames = NULL
suppPrint = identity
if (length(av) && av[1L] == ":=") {
if (identical(attr(x,".data.table.locked"),TRUE)) stop(".SD is locked. Using := in .SD's j is reserved for possible future use; a tortuously flexible way to modify by group. Use := in j directly to modify by group by reference.")
suppPrint <- function(x) { .global$print=address(x); x }
# Suppress print when returns ok not on error, bug #2376. Thanks to: http://stackoverflow.com/a/13606880/403310
# All appropriate returns following this point are wrapped; i.e. return(suppPrint(x)).
if (is.null(names(jsub))) {
# regular LHS:=RHS usage, or `:=`(...) with no named arguments (an error)
# `:=`(LHS,RHS) is valid though, but more because can't see how to detect that, than desire
if (length(jsub)!=3L) stop("In `:=`(col1=val1, col2=val2, ...) form, all arguments must be named.")
lhs = jsub[[2L]]
jsub = jsub[[3L]]
if (is.name(lhs)) {
lhs = as.character(lhs)
} else {
# e.g. (MyVar):= or get("MyVar"):=
lhs = eval(lhs, parent.frame(), parent.frame())
}
} else {
# `:=`(c2=1L,c3=2L,...)
lhs = names(jsub)[-1L]
if (any(lhs=="")) stop("In `:=`(col1=val1, col2=val2, ...) form, all arguments must be named.")
names(jsub)=""
jsub[[1L]]=as.name("list")
}
av = all.vars(jsub,TRUE)
if (!is.atomic(lhs)) stop("LHS of := must be a symbol, or an atomic vector (column names or positions).")
if (is.character(lhs)) {
m = chmatch(lhs,names(x))
} else if (is.numeric(lhs)) {
m = as.integer(lhs)
if (any(m<1L | ncol(x)<m)) stop("LHS of := appears to be column positions but are outside [1,ncol] range. New columns can only be added by name.")
lhs = names(x)[m]
} else
stop("LHS of := isn't column names ('character') or positions ('integer' or 'numeric')")
if (all(!is.na(m))) {
# updates by reference to existing columns
cols = as.integer(m)
newnames=NULL
if (identical(irows, integer())) {
# Empty integer() means no rows e.g. logical i with only FALSE and NA
# got converted to empty integer() by the which() above
# Short circuit and do-nothing since columns already exist. If some don't
# exist then for consistency with cases where irows is non-empty, we need to create
# them of the right type and populate with NA. Which will happen via the regular
# alternative branches below, to cover #759.
# We need this short circuit at all just for convenience. Otherwise users may need to
# fix errors in their RHS when called on empty edge cases, even when the result won't be
# used anyway (so it would be annoying to have to fix it.)
if (verbose) {
cat("No rows match i. No new columns to add so not evaluating RHS of :=\n")
cat("Assigning to 0 row subset of",nrow(x),"rows\n")
}
.Call(Cassign, x, irows, NULL, NULL, NULL, FALSE) # only purpose is to write 0 to .Last.updated
.global$print = address(x)
return(invisible(x))
}
} else {
# Adding new column(s). TO DO: move after the first eval in case the jsub has an error.
newnames=setdiff(lhs,names(x))
m[is.na(m)] = ncol(x)+seq_len(length(newnames))
cols = as.integer(m)
# don't pass verbose to selfrefok here -- only activated when
# ok=-1 which will trigger alloc.col with verbose in the next
# branch, which again calls _selfrefok and returns the message then
if ((ok<-selfrefok(x, verbose=FALSE))==0L) # ok==0 so no warning when loaded from disk (-1) [-1 considered TRUE by R]
warning("Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.")
if ((ok<1L) || (truelength(x) < ncol(x)+length(newnames))) {
DT = x # in case getOption contains "ncol(DT)" as it used to. TODO: warn and then remove
n = length(newnames) + eval(getOption("datatable.alloccol")) # TODO: warn about expressions and then drop the eval()
# i.e. reallocate at the size as if the new columns were added followed by alloc.col().
name = substitute(x)
if (is.name(name) && ok && verbose) { # && NAMED(x)>0 (TO DO) # ok here includes -1 (loaded from disk)
cat("Growing vector of column pointers from truelength ", truelength(x), " to ", n, ". A shallow copy has been taken, see ?alloc.col. Only a potential issue if two variables point to the same data (we can't yet detect that well) and if not you can safely ignore this. To avoid this message you could alloc.col() first, deep copy first using copy(), wrap with suppressWarnings() or increase the 'datatable.alloccol' option.\n")
# #1729 -- copying to the wrong environment here can cause some confusion
if (ok == -1L) cat("Note that the shallow copy will assign to the environment from which := was called. That means for example that if := was called within a function, the original table may be unaffected.\n")
# Verbosity should not issue warnings, so cat rather than warning.
# TO DO: Add option 'datatable.pedantic' to turn on warnings like this.
# TO DO ... comments moved up from C ...
# Note that the NAMED(dt)>1 doesn't work because .Call
# always sets to 2 (see R-ints), it seems. Work around
# may be possible but not yet working. When the NAMED test works, we can drop allocwarn argument too
# because that's just passed in as FALSE from [<- where we know `*tmp*` isn't really NAMED=2.
# Note also that this growing will happen for missing columns assigned NULL, too. But so rare, we
# don't mind.
}
alloc.col(x, n, verbose=verbose) # always assigns to calling scope; i.e. this scope
if (is.name(name)) {
assign(as.character(name),x,parent.frame(),inherits=TRUE)
} else if (is.call(name) && (name[[1L]] == "$" || name[[1L]] == "[[") && is.name(name[[2L]])) {
k = eval(name[[2L]], parent.frame(), parent.frame())
if (is.list(k)) {
origj = j = if (name[[1L]] == "$") as.character(name[[3L]]) else eval(name[[3L]], parent.frame(), parent.frame())
if (is.character(j)) {
if (length(j)!=1L) stop("L[[i]][,:=] syntax only valid when i is length 1, but it's length %d",length(j))
j = match(j, names(k))
if (is.na(j)) stop("Item '",origj,"' not found in names of list")
}
.Call(Csetlistelt,k,as.integer(j), x)
} else if (is.environment(k) && exists(as.character(name[[3L]]), k)) {
assign(as.character(name[[3L]]), x, k, inherits=FALSE)
}
} # TO DO: else if env$<- or list$<-
}
}
}
}
if (length(ansvars)) {
w = ansvals
if (length(rightcols) && missingby) {
w[ w %in% rightcols ] = NA
}
# patch for #1615. Allow 'x.' syntax. Only useful during join op when x's join col needs to be used.
# Note that I specifically have not implemented x[y, aa, on=c(aa="bb")] to refer to x's join column
# as well because x[i, col] == x[i][, col] will not be TRUE anymore..
if ( any(xdotprefixvals <- ansvars %chin% xdotprefix)) {
w[xdotprefixvals] = chmatch(ansvars[xdotprefixvals], xdotprefix)
xdotcols = TRUE
}
if (!any(wna <- is.na(w))) {
xcols = w
xcolsAns = seq_along(ansvars)
icols = icolsAns = integer()
} else {
if (!length(leftcols)) stop("column(s) not found: ", paste(ansvars[wna],collapse=", "))
xcols = w[!wna]
xcolsAns = which(!wna)
ivars = names(i)
ivars[leftcols] = names(x)[rightcols]
w2 = chmatch(ansvars[wna], ivars)
if (any(w2na <- is.na(w2))) {
ivars = paste0("i.",ivars)
ivars[leftcols] = names(i)[leftcols]
w2[w2na] = chmatch(ansvars[wna][w2na], ivars)
if (any(w2na <- is.na(w2))) {
ivars[leftcols] = paste0("i.",ivars[leftcols])
w2[w2na] = chmatch(ansvars[wna][w2na], ivars)
if (any(w2na <- is.na(w2))) stop("column(s) not found: ", paste(ansvars[wna][w2na],sep=", "))
}
}
icols = w2
icolsAns = which(wna)
}
}
} # end of if !missing(j)
SDenv = new.env(parent=parent.frame())
# taking care of warnings for posixlt type, #646
SDenv$strptime <- function(x, ...) {
warning("POSIXlt column type detected and converted to POSIXct. We do not recommend use of POSIXlt at all because it uses 40 bytes to store one date. Use as.POSIXct to avoid this warning.")
as.POSIXct(base::strptime(x, ...))
}
syms = all.vars(jsub)
syms = syms[ substring(syms,1L,2L)==".." ]
syms = syms[ substring(syms,3L,3L)!="." ] # exclude ellipsis
for (sym in syms) {
if (sym %chin% names(x)) {
# if "..x" exists as column name, use column, for backwards compatibility; e.g. package socialmixr in rev dep checks #2779
next
# TODO in future, as warned in NEWS item for v1.11.0 :
# warning(sym," in j is looking for ",getName," in calling scope, but a column '", sym, "' exists. Column names should not start with ..")
}
getName = substring(sym, 3L)
if (!exists(getName, parent.frame())) {
if (exists(sym, parent.frame())) next # user did 'manual' prefix; i.e. variable in calling scope has .. prefix
stop("Variable '",getName,"' is not found in calling scope. Looking in calling scope because this symbol was prefixed with .. in the j= parameter.")
}
assign(sym, get(getName, parent.frame()), SDenv)
}
# hash=TRUE (the default) does seem better as expected using e.g. test 645. TO DO experiment with 'size' argument
if (missingby || bynull || (!byjoin && !length(byval))) {
# No grouping: 'by' = missing | NULL | character() | "" | list()
# Considered passing a one-group to dogroups but it doesn't do the recycling of i within group, that's done here
if (length(ansvars)) {
if (!(length(i) && length(icols))) {
# new in v1.12.0 to redirect to CsubsetDT in this case
if (!identical(xcolsAns, seq_along(xcolsAns)) || length(xcols)!=length(xcolsAns) || length(ansvars)!=length(xcolsAns)) {
stop("Internal error: xcolAns does not pass checks: ", length(xcolsAns), length(ansvars), length(xcols), paste(xcolsAns,collapse=",")) # nocov
}
# Retained from old R way below (test 1542.01 checks shallow at this point)
# ' Temp fix for #921 - skip COPY until after evaluating 'jval' (scroll down).
# ' Unless 'with=FALSE' - can not be expressions but just column names.
ans = if (with && is.null(irows)) shallow(x, xcols) else .Call(CsubsetDT, x, irows, xcols)
setattr(ans, "names", ansvars)
} else {
# length(i) && length(icols)
if (is.null(irows)) {
stop("Internal error: irows is NULL when making join result at R level. Should no longer happen now we use CsubsetDT earlier.") # nocov
# TODO: Make subsetDT do a shallow copy when irows is NULL (it currently copies). Then copy only when user uses := or set* on the result
# by using NAMED/REFCNT on columns, with warning if they copy. Since then, even foo = DT$b would cause the next set or := to copy that
# column (so the warning is needed). To tackle that, we could have our own DT.NAMED attribute, perhaps.
# Or keep the rule that [.data.table always returns new memory, and create view() or view= as well, maybe cleaner.
}
ans = vector("list", length(ansvars))
ii = rep.int(indices__, len__) # following #1991 fix
# TODO: if (allLen1 && allGrp1 && (is.na(nomatch) || !any(f__==0L))) then ii will be 1:nrow(i) [nomatch=0 should drop rows in i that have no match]
# But rather than that complex logic here at R level to catch that and do a shallow copy for efficiency, just do the check inside CsubsetDT
# to see if it passed 1:nrow(x) and then CsubsetDT should do the shallow copy safely and centrally.
# That R level branch was taken out in PR #3213
# TO DO: use CsubsetDT twice here and then remove this entire R level branch
for (s in seq_along(icols)) {
target = icolsAns[s]
source = icols[s]
ans[[target]] = .Call(CsubsetVector,i[[source]],ii) # i.e. i[[source]][ii]
}
for (s in seq_along(xcols)) {
target = xcolsAns[s]
source = xcols[s]
ans[[target]] = .Call(CsubsetVector,x[[source]],irows) # i.e. x[[source]][irows], but guaranteed new memory even for singleton logicals from R 3.1.0
}
setattr(ans, "names", ansvars)
if (haskey(x)) {
keylen = which.first(!key(x) %chin% ansvars)-1L
if (is.na(keylen)) keylen = length(key(x))
len = length(rightcols)
# fix for #1268, #1704, #1766 and #1823
chk = if (len && !missing(on)) !identical(head(key(x), len), names(on)) else FALSE
if ( (keylen>len || chk) && !.Call(CisOrderedSubset, irows, nrow(x))) {
keylen = if (!chk) len else 0L # fix for #1268
}
## check key on i as well!
ichk = is.data.table(i) && haskey(i) &&
identical(head(key(i), length(leftcols)), names(i)[leftcols]) # i has the correct key, #3061
if (keylen && (ichk || is.logical(i) || (.Call(CisOrderedSubset, irows, nrow(x)) && ((roll == FALSE) || length(irows) == 1L)))) # see #1010. don't set key when i has no key, but irows is ordered and roll != FALSE
setattr(ans,"sorted",head(key(x),keylen))
}
setattr(ans, "class", class(x)) # fix for #5296
setattr(ans, "row.names", .set_row_names(nrow(ans)))
alloc.col(ans)
}
if (!with || missing(j)) return(ans)
SDenv$.SDall = ans
SDenv$.SD = if (!length(othervars)) SDenv$.SDall else shallow(SDenv$.SDall, setdiff(ansvars, othervars))
SDenv$.N = nrow(SDenv$.SD)
} else {
SDenv$.SDall = SDenv$.SD = null.data.table() # no columns used by j so .SD can be empty. Only needs to exist so that we can rely on it being there when locking it below for example. If .SD were used by j, of course then xvars would be the columns and we wouldn't be in this leaf.
SDenv$.N = if (is.null(irows)) nrow(x) else length(irows) * !identical(suppressWarnings(max(irows)), 0L)
# Fix for #963.
# When irows is integer(0L), length(irows) = 0 will result in 0 (as expected).
# Binary search can return all 0 irows when none of the input matches. Instead of doing all(irows==0L) (previous method), which has to allocate a logical vector the size of irows, we can make use of 'max'. If max is 0, we return 0. The condition where only some irows > 0 won't occur.
}
# Temp fix for #921. Allocate `.I` only if j-expression uses it.
SDenv$.I = if (!missing(j) && use.I) seq_len(SDenv$.N) else 0L
SDenv$.GRP = 1L
setattr(SDenv$.SD,".data.table.locked",TRUE) # used to stop := modifying .SD via j=f(.SD), bug#1727. The more common case of j=.SD[,subcol:=1] was already caught when jsub is inspected for :=.
setattr(SDenv$.SDall,".data.table.locked",TRUE)
lockBinding(".SD",SDenv)
lockBinding(".SDall",SDenv)
lockBinding(".N",SDenv)
lockBinding(".I",SDenv)
lockBinding(".GRP",SDenv)
for (ii in ansvars) assign(ii, SDenv$.SDall[[ii]], SDenv)
# Since .SD is inside SDenv, alongside its columns as variables, R finds .SD symbol more quickly, if used.
# There isn't a copy of the columns here, the xvar symbols point to the SD columns (copy-on-write).
if (is.name(jsub) && is.null(lhs) && !exists(jsubChar<-as.character(jsub), SDenv, inherits=FALSE)) {
stop("j (the 2nd argument inside [...]) is a single symbol but column name '",jsubChar,"' is not found. Perhaps you intended DT[, ..",jsubChar,"]. This difference to data.frame is deliberate and explained in FAQ 1.1.")
}
jval = eval(jsub, SDenv, parent.frame())
# copy 'jval' when required
# More speedup - only check + copy if irows is NULL
# Temp fix for #921 - check address and copy *after* evaluating 'jval'
if (is.null(irows)) {
if (!is.list(jval)) { # performance improvement when i-arg is S4, but not list, #1438, Thanks @DCEmilberg.
jcpy = address(jval) %in% vapply_1c(SDenv$.SD, address) # %chin% errors when RHS is list()
if (jcpy) jval = copy(jval)
} else if (address(jval) == address(SDenv$.SD)) {
jval = copy(jval)
} else if ( length(jcpy <- which(vapply_1c(jval, address) %in% vapply_1c(SDenv, address))) ) {
for (jidx in jcpy) jval[[jidx]] = copy(jval[[jidx]])
} else if (is.call(jsub) && jsub[[1L]] == "get" && is.list(jval)) {
jval = copy(jval) # fix for #1212
}
} else {
if (is.data.table(jval)) {
setattr(jval, '.data.table.locked', NULL) # fix for #1341
if (!truelength(jval)) alloc.col(jval)
}
}
if (!is.null(lhs)) {
# TODO?: use set() here now that it can add new columns. Then remove newnames and alloc logic above.
.Call(Cassign,x,irows,cols,newnames,jval,verbose)
return(suppPrint(x))
}
if ((is.call(jsub) && is.list(jval) && jsub[[1L]] != "get" && !is.object(jval)) || !missingby) {
# is.call: selecting from a list column should return list
# is.object: for test 168 and 168.1 (S4 object result from ggplot2::qplot). Just plain list results should result in data.table
# Fix for #813 and #758. Ex: DT[c(FALSE, FALSE), list(integer(0L), y)]
# where DT = data.table(x=1:2, y=3:4) should return an empty data.table!!
if (!is.null(irows) && `||`(
identical(irows, integer(0L)) && !bynull,
length(irows) && !anyNA(irows) && all(irows==0L) ## anyNA() because all() returns NA (not FALSE) when irows is all-NA. TODO: any way to not check all 'irows' values?
))
if (is.atomic(jval)) jval = jval[0L] else jval = lapply(jval, `[`, 0L)
if (is.atomic(jval)) {
setattr(jval,"names",NULL)
jval = data.table(jval) # TO DO: should this be setDT(list(jval)) instead?
} else {
if (is.null(jvnames)) jvnames=names(jval)
# avoid copy if all vectors are already of same lengths, use setDT
lenjval = vapply(jval, length, 0L)
if (any(lenjval != lenjval[1L])) {
jval = as.data.table.list(jval) # does the vector expansion to create equal length vectors
jvnames = jvnames[lenjval != 0L] # fix for #1477
} else setDT(jval)
}
if (is.null(jvnames)) jvnames = character(length(jval)-length(bynames))
ww = which(jvnames=="")
if (any(ww)) jvnames[ww] = paste0("V",ww)
setnames(jval, jvnames)
}
# fix for bug #5114 from GSee's - .data.table.locked=TRUE. # TO DO: more efficient way e.g. address==address (identical will do that but then proceed to deep compare if !=, wheras we want just to stop?)
# Commented as it's taken care of above, along with #921 fix. Kept here for the bug fix info and TO DO.
# if (identical(jval, SDenv$.SD)) return(copy(jval))
if (is.data.table(jval)) {
setattr(jval, 'class', class(x)) # fix for #5296
if (haskey(x) && all(key(x) %chin% names(jval)) && suppressWarnings(is.sorted(jval, by=key(x)))) # TO DO: perhaps this usage of is.sorted should be allowed internally then (tidy up and make efficient)
setattr(jval, 'sorted', key(x))
# postponed to v1.12.4 because package eplusr creates a NULL column and then runs setcolorder on the result which fails if there are fewer columns
# w = sapply(jval, is.null)
# if (any(w)) jval = jval[,!w,with=FALSE] # no !..w due to 'Undefined global functions or variables' note from R CMD check
}
return(jval)
}
###########################################################################
# Grouping ...
###########################################################################
o__ = integer()
if (".N" %chin% ansvars) stop("The column '.N' can't be grouped because it conflicts with the special .N variable. Try setnames(DT,'.N','N') first.")
if (".I" %chin% ansvars) stop("The column '.I' can't be grouped because it conflicts with the special .I variable. Try setnames(DT,'.I','I') first.")
SDenv$.iSD = NULL # null.data.table()
SDenv$.xSD = NULL # null.data.table() - introducing for FR #2693 and Gabor's post on fixing for FAQ 2.8
assign("print", function(x,...){base::print(x,...);NULL}, SDenv)
# Now ggplot2 returns data from print, we need a way to throw it away otherwise j accumulates the result
SDenv$.SDall = SDenv$.SD = null.data.table() # e.g. test 607. Grouping still proceeds even though no .SD e.g. grouping key only tables, or where j consists of .N only
SDenv$.N = vector("integer", 1L) # explicit new vector (not 0L or as.integer() which might return R's internal small-integer global)
SDenv$.GRP = vector("integer", 1L) # because written to by reference at C level (one write per group). TODO: move this alloc to C level
if (byjoin) {
# The groupings come instead from each row of the i data.table.
# Much faster for a few known groups vs a 'by' for all followed by a subset
if (!is.data.table(i)) stop("logical error. i is not data.table, but mult='all' and 'by'=.EACHI")
byval = i
bynames = if (missing(on)) head(key(x),length(leftcols)) else names(on)
allbyvars = NULL
bysameorder = haskey(i) || (is.sorted(f__) && ((roll == FALSE) || length(f__) == 1L)) # Fix for #1010
## 'av' correct here ?? *** TO DO ***
xjisvars = intersect(av, names(x)[rightcols]) # no "x." for xvars.
# if 'get' is in 'av' use all cols in 'i', fix for bug #5443
# added 'mget' - fix for #994
jisvars = if (any(c("get", "mget") %chin% av)) names(i) else intersect(gsub("^i[.]","", setdiff(av, xjisvars)), names(i))
# JIS (non join cols) but includes join columns too (as there are named in i)
if (length(jisvars)) {
tt = min(nrow(i),1L)
SDenv$.iSD = i[tt,jisvars,with=FALSE]
for (ii in jisvars) {
assign(ii, SDenv$.iSD[[ii]], SDenv)
assign(paste0("i.",ii), SDenv$.iSD[[ii]], SDenv)
}
}
} else {
# Find the groups, using 'byval' ...
if (missingby) stop("Internal error: by= is missing") # nocov
if (length(byval) && length(byval[[1L]])) {
if (!bysameorder && isFALSE(byindex)) {
if (verbose) {last.started.at=proc.time();cat("Finding groups using forderv ... ");flush.console()}
o__ = forderv(byval, sort=keyby, retGrp=TRUE)
# The sort= argument is called sortGroups at C level. It's primarily for saving the sort of unique strings at
# C level for efficiency when by= not keyby=. Other types also retain appearance order, but at byte level to
# minimize data movement and benefit from skipping subgroups which happen to be grouped but not sorted. This byte
# appearance order is not the same as the order of group values within by= columns, so the 2nd forder below is
# still needed to get the group appearance order. Always passing sort=TRUE above won't change any result at all
# (tested and confirmed), it'll just make by= slower. It must be TRUE when keyby= though since the key is just
# marked afterwards.
# forderv() returns empty integer() if already ordered to save allocating 1:xnrow
bysameorder = orderedirows && !length(o__)
if (verbose) {
cat(timetaken(last.started.at),"\n")
last.started.at=proc.time()
cat("Finding group sizes from the positions (can be avoided to save RAM) ... ")
flush.console() # for windows
}
f__ = attr(o__, "starts")
len__ = uniqlengths(f__, xnrow)
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
if (!bysameorder && !keyby) {
# TO DO: lower this into forder.c
if (verbose) {last.started.at=proc.time();cat("Getting back original order ... ");flush.console()}
firstofeachgroup = o__[f__]
if (length(origorder <- forderv(firstofeachgroup))) {
f__ = f__[origorder]
len__ = len__[origorder]
}
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
}
if (!orderedirows && !length(o__)) o__ = seq_len(xnrow) # temp fix. TODO: revist orderedirows
} else {
if (verbose) last.started.at=proc.time();
if (bysameorder) {
if (verbose) {cat("Finding groups using uniqlist on key ... ");flush.console()}
f__ = uniqlist(byval)
} else {
if (!is.character(byindex) || length(byindex)!=1L) stop("Internal error: byindex not the index name") # nocov
if (verbose) {cat("Finding groups using uniqlist on index '", byindex, "' ... ", sep="");flush.console()}
o__ = getindex(x, byindex)
if (is.null(o__)) stop("Internal error: byindex not found") # nocov
f__ = uniqlist(byval, order=o__)
}
if (verbose) {
cat(timetaken(last.started.at),"\n")
last.started.at=proc.time()
cat("Finding group sizes from the positions (can be avoided to save RAM) ... ")
flush.console() # for windows
}
len__ = uniqlengths(f__, xnrow)
# TO DO: combine uniqlist and uniquelengths into one call. Or, just set len__ to NULL when dogroups infers that.
if (verbose) { cat(timetaken(last.started.at),"\n"); flush.console() }
}
} else {
f__=NULL
len__=0L
bysameorder=TRUE # for test 724
}
# TO DO: allow secondary keys to be stored, then we see if our by matches one, if so use it, and no need to sort again. TO DO: document multiple keys.
}
if (length(xcols)) {
# TODO add: if (max(len__)==nrow) stop("There is no need to deep copy x in this case")
# TODO move down to dogroup.c, too.
SDenv$.SDall = .Call(CsubsetDT, x, if (length(len__)) seq_len(max(len__)) else 0L, xcols) # must be deep copy when largest group is a subset
if (xdotcols) setattr(SDenv$.SDall, 'names', ansvars[xcolsAns]) # now that we allow 'x.' prefix in 'j', #2313 bug fix - [xcolsAns]
SDenv$.SD = if (!length(othervars)) SDenv$.SDall else shallow(SDenv$.SDall, setdiff(ansvars, othervars))
}
if (nrow(SDenv$.SDall)==0L) {
setattr(SDenv$.SDall,"row.names",c(NA_integer_,0L))
setattr(SDenv$.SD,"row.names",c(NA_integer_,0L))
}
# .set_row_names() basically other than not integer() for 0 length, otherwise dogroups has no [1] to modify to -.N
setattr(SDenv$.SD,".data.table.locked",TRUE) # used to stop := modifying .SD via j=f(.SD), bug#1727. The more common case of j=.SD[,subcol:=1] was already caught when jsub is inspected for :=.
setattr(SDenv$.SDall,".data.table.locked",TRUE)
lockBinding(".SD",SDenv)
lockBinding(".SDall",SDenv)
lockBinding(".N",SDenv)
lockBinding(".GRP",SDenv)
lockBinding(".iSD",SDenv)
GForce = FALSE
if ( getOption("datatable.optimize")>=1 && (is.call(jsub) || (is.name(jsub) && as.character(jsub)[[1L]] %chin% c(".SD",".N"))) ) { # Ability to turn off if problems or to benchmark the benefit
# Optimization to reduce overhead of calling lapply over and over for each group
ansvarsnew = setdiff(ansvars, othervars)
oldjsub = jsub
funi = 1L # Fix for #985
# convereted the lapply(.SD, ...) to a function and used below, easier to implement FR #2722 then.
.massageSD <- function(jsub) {
txt = as.list(jsub)[-1L]
if (length(names(txt))>1L) .Call(Csetcharvec, names(txt), 2L, "") # fixes bug #4839
fun = txt[[2L]]
if (is.call(fun) && fun[[1L]]=="function") {
# Fix for #2381: added SDenv$.SD to 'eval' to take care of cases like: lapply(.SD, function(x) weighted.mean(x, bla)) where "bla" is a column in DT
# http://stackoverflow.com/questions/13441868/data-table-and-stratified-means
# adding this does not compromise in speed (that is, not any lesser than without SDenv$.SD)
# replaced SDenv$.SD to SDenv to deal with Bug #5007 reported by Ricardo (Nice catch!)
thisfun = paste0("..FUN", funi) # Fix for #985
assign(thisfun,eval(fun, SDenv, SDenv), SDenv) # to avoid creating function() for each column of .SD
lockBinding(thisfun,SDenv)
txt[[1L]] = as.name(thisfun)
} else {
if (is.character(fun)) fun = as.name(fun)
txt[[1L]] = fun
}
ans = vector("list",length(ansvarsnew)+1L)
ans[[1L]] = as.name("list")
for (ii in seq_along(ansvarsnew)) {
txt[[2L]] = as.name(ansvarsnew[ii])
ans[[ii+1L]] = as.call(txt)
}
jsub = as.call(ans) # important no names here
jvnames = ansvarsnew # but here instead
list(jsub, jvnames)
# It may seem inefficient to constuct a potentially long expression. But, consider calling
# lapply 100000 times. The C code inside lapply does the LCONS stuff anyway, every time it
# is called, involving small memory allocations.
# The R level lapply calls as.list which needs a shallow copy.
# lapply also does a setAttib of names (duplicating the same names over and over again
# for each group) which is terrible for our needs. We replace all that with a
# (ok, long, but not huge in memory terms) list() which is primitive (so avoids symbol
# lookup), and the eval() inside dogroups hardly has to do anything. All this results in
# overhead minimised. We don't need to worry about the env passed to the eval in a possible
# lapply replacement, or how to pass ... efficiently to it.
# Plus we optimize lapply first, so that mean() can be optimized too as well, next.
}
if (is.name(jsub)) {
if (jsub == ".SD") {
jsub = as.call(c(quote(list), lapply(ansvarsnew, as.name)))
jvnames = ansvarsnew
}
} else if (length(as.character(jsub[[1L]])) == 1L) { # Else expect problems with <jsub[[1L]] == >
subopt = length(jsub) == 3L && jsub[[1L]] == "[" && (is.numeric(jsub[[3L]]) || jsub[[3L]] == ".N")
headopt = jsub[[1L]] == "head" || jsub[[1L]] == "tail"
firstopt = jsub[[1L]] == "first" || jsub[[1L]] == "last" # fix for #2030
if ((length(jsub) >= 2L && jsub[[2L]] == ".SD") &&
(subopt || headopt || firstopt)) {
if (headopt && length(jsub)==2L) jsub[["n"]] = 6L # head-tail n=6 when missing #3462
# optimise .SD[1] or .SD[2L]. Not sure how to test .SD[a] as to whether a is numeric/integer or a data.table, yet.
jsub = as.call(c(quote(list), lapply(ansvarsnew, function(x) { jsub[[2L]] = as.name(x); jsub })))
jvnames = ansvarsnew
} else if (jsub[[1L]]=="lapply" && jsub[[2L]]==".SD" && length(xcols)) {
deparse_ans = .massageSD(jsub)
jsub = deparse_ans[[1L]]
jvnames = deparse_ans[[2L]]
} else if (jsub[[1L]] == "c" && length(jsub) > 1L) {
# TODO, TO DO: raise the checks for 'jvnames' earlier (where jvnames is set by checking 'jsub') and set 'jvnames' already.
# FR #2722 is just about optimisation of j=c(.N, lapply(.SD, .)) that is taken care of here.
# FR #735 tries to optimise j-expressions of the form c(...) as long as ... contains
# 1) lapply(.SD, ...), 2) simply .SD or .SD[..], 3) .N, 4) list(...) and 5) functions that normally return a single value*
# On 5)* the IMPORTANT point to note is that things that are not wrapped within "list(...)" should *always*
# return length 1 output for us to optimise. Else, there's no equivalent to optimising c(...) to list(...) AFAICT.
# One issue could be that these functions (e.g., mean) can be "re-defined" by the OP to produce a length > 1 output
# Of course this is worrying too much though. If the issue comes up, we'll just remove the relevant optimisations.
# For now, we optimise all functions mentioned in 'optfuns' below.
optfuns = c("max", "min", "mean", "length", "sum", "median", "sd", "var")
is_valid = TRUE
any_SD = FALSE
jsubl = as.list.default(jsub)
oldjvnames = jvnames
jvnames = NULL # TODO: not let jvnames grow, maybe use (number of lapply(.SD, .))*lenght(ansvarsnew) + other jvars ?? not straightforward.
# Fix for #744. Don't use 'i' in for-loops. It masks the 'i' from the input!!
for (i_ in 2L:length(jsubl)) {
this = jsub[[i_]]
if (is.name(this)) { # no need to check length(this)==1L; is.name() returns single TRUE or FALSE (documented); can't have a vector of names
if (this == ".SD") { # optimise '.SD' alone
any_SD = TRUE
jsubl[[i_]] = lapply(ansvarsnew, as.name)
jvnames = c(jvnames, ansvarsnew)
} else if (this == ".N") {
# don't optimise .I in c(.SD, .I), it's length can be > 1
# only c(.SD, list(.I)) should be optimised!! .N is always length 1.
jvnames = c(jvnames, gsub("^[.]([N])$", "\\1", this))
} else {
# jvnames = c(jvnames, if (is.null(names(jsubl))) "" else names(jsubl)[i_])
is_valid=FALSE
break
}
} else if (is.call(this)) {
if (this[[1L]] == "lapply" && this[[2L]] == ".SD" && length(xcols)) {
any_SD = TRUE
deparse_ans = .massageSD(this)
funi = funi + 1L # Fix for #985
jsubl[[i_]] = as.list(deparse_ans[[1L]][-1L]) # just keep the '.' from list(.)
jvnames = c(jvnames, deparse_ans[[2L]])
} else if (this[[1L]] == "list") {
# also handle c(lapply(.SD, sum), list()) - silly, yes, but can happen
if (length(this) > 1L) {
jl__ = as.list(jsubl[[i_]])[-1L] # just keep the '.' from list(.)
jn__ = if (is.null(names(jl__))) rep("", length(jl__)) else names(jl__)
idx = unlist(lapply(jl__, function(x) is.name(x) && x == ".I"))
if (any(idx)) jn__[idx & (jn__ == "")] = "I"
jvnames = c(jvnames, jn__)
jsubl[[i_]] = jl__
}
} else if (is.call(this) && length(this) > 1L && as.character(this[[1L]]) %chin% optfuns) {
jvnames = c(jvnames, if (is.null(names(jsubl))) "" else names(jsubl)[i_])
} else if ( length(this) == 3L && (this[[1L]] == "[" || this[[1L]] == "head") &&
this[[2L]] == ".SD" && (is.numeric(this[[3L]]) || this[[3L]] == ".N") ) {
# optimise .SD[1] or .SD[2L]. Not sure how to test .SD[a] as to whether a is numeric/integer or a data.table, yet.
any_SD = TRUE
jsubl[[i_]] = lapply(ansvarsnew, function(x) { this[[2L]] = as.name(x); this })
jvnames = c(jvnames, ansvarsnew)
} else if (any(all.vars(this) == ".SD")) {
# TODO, TO DO: revisit complex cases (as illustrated below)
# complex cases like DT[, c(.SD[x>1], .SD[J(.)], c(.SD), a + .SD, lapply(.SD, sum)), by=grp]
# hard to optimise such cases (+ difficulty in counting exact columns and therefore names). revert back to no optimisation.
is_valid=FALSE
break
} else { # just to be sure that any other case (I've overlooked) runs smoothly, without optimisation
# TO DO, TODO: maybe a message/warning here so that we can catch the overlooked cases, if any?
is_valid=FALSE
break
}
} else {
is_valid = FALSE
break
}
}
if (!is_valid || !any_SD) { # restore if c(...) doesn't contain lapply(.SD, ..) or if it's just invalid
jvnames = oldjvnames # reset jvnames
jsub = oldjsub # reset jsub
jsubl = as.list.default(jsubl) # reset jsubl
} else {
setattr(jsubl, 'names', NULL)
jsub = as.call(unlist(jsubl, use.names=FALSE))
jsub[[1L]] = quote(list)
}
}
}
if (verbose) {
if (!identical(oldjsub, jsub))
cat("lapply optimization changed j from '",deparse(oldjsub),"' to '",deparse(jsub,width.cutoff=200L),"'\n",sep="")
else
cat("lapply optimization is on, j unchanged as '",deparse(jsub,width.cutoff=200L),"'\n",sep="")
}
dotN <- function(x) is.name(x) && x == ".N" # For #5760
# FR #971, GForce kicks in on all subsets, no joins yet. Although joins could work with
# nomatch=0L even now.. but not switching it on yet, will deal it separately.
if (getOption("datatable.optimize")>=2 && !is.data.table(i) && !byjoin && length(f__) && !length(lhs)) {
if (!length(ansvars) && !use.I) {
GForce = FALSE
if ( (is.name(jsub) && jsub == ".N") || (is.call(jsub) && length(jsub)==2L && length(as.character(jsub[[1L]])) && as.character(jsub[[1L]])[1L] == "list" && length(as.character(jsub[[2L]])) && as.character(jsub[[2L]])[1L] == ".N") ) {
GForce = TRUE
if (verbose) cat("GForce optimized j to '",deparse(jsub,width.cutoff=200L),"'\n",sep="")
}
} else {
# Apply GForce
gfuns = c("sum", "prod", "mean", "median", "var", "sd", ".N", "min", "max", "head", "last", "first", "tail", "[") # added .N for #5760
.ok <- function(q) {
if (dotN(q)) return(TRUE) # For #5760
# run GForce for simple f(x) calls and f(x, na.rm = TRUE)-like calls where x is a column of .SD
# is.symbol() is for #1369, #1974 and #2949
if (!(is.call(q) && is.symbol(q[[1L]]) && is.symbol(q[[2L]]) && (q1c <- as.character(q[[1L]])) %chin% gfuns)) return(FALSE)
if (!(q2c<-as.character(q[[2L]])) %chin% names(SDenv$.SDall) && q2c!=".I") return(FALSE) # 875
if ((length(q)==2L || identical("na",substring(names(q)[3L], 1L, 2L))) && (!q1c %chin% c("head","tail"))) return(TRUE)
# ... head-tail uses default value n=6 which as of now should not go gforce ^^
# otherwise there must be three arguments, and only in two cases:
# 1) head/tail(x, 1) or 2) x[n], n>0
length(q)==3L && length(q3 <- q[[3L]])==1L && is.numeric(q3) &&
( (q1c %chin% c("head", "tail") && q3==1L) || (q1c == "[" && q3>0L) )
}
if (jsub[[1L]]=="list") {
GForce = TRUE
for (ii in seq_along(jsub)[-1L]) if (!.ok(jsub[[ii]])) GForce = FALSE
} else GForce = .ok(jsub)
if (GForce) {
if (jsub[[1L]]=="list")
for (ii in seq_along(jsub)[-1L]) {
if (dotN(jsub[[ii]])) next; # For #5760
jsub[[ii]][[1L]] = as.name(paste0("g", jsub[[ii]][[1L]]))
if (length(jsub[[ii]])==3L) jsub[[ii]][[3L]] = eval(jsub[[ii]][[3L]], parent.frame()) # tests 1187.2 & 1187.4
}
else {
jsub[[1L]] = as.name(paste0("g", jsub[[1L]]))
if (length(jsub)==3L) jsub[[3L]] = eval(jsub[[3L]], parent.frame()) # tests 1187.3 & 1187.5
}
if (verbose) cat("GForce optimized j to '",deparse(jsub,width.cutoff=200L),"'\n",sep="")
} else if (verbose) cat("GForce is on, left j unchanged\n");
}
}
if (!GForce && !is.name(jsub)) {
# Still do the old speedup for mean, for now
nomeanopt=FALSE # to be set by .optmean() using <<- inside it
oldjsub = jsub
if (jsub[[1L]]=="list") {
for (ii in seq_along(jsub)[-1L]) {
this_jsub = jsub[[ii]]
if (dotN(this_jsub)) next; # For #5760
# Addressing #1369, #2949 and #1974. Added is.symbol() check to handle cases where expanded function definition is used insead of function names. #1369 results in (function(x) sum(x)) as jsub[[.]] from dcast.data.table.
if (is.call(this_jsub) && is.symbol(this_jsub[[1L]]) && this_jsub[[1L]]=="mean")
jsub[[ii]] = .optmean(this_jsub)
}
} else if (jsub[[1L]]=="mean") {
jsub = .optmean(jsub)
}
if (nomeanopt) {
warning("Unable to optimize call to mean() and could be very slow. You must name 'na.rm' like that otherwise if you do mean(x,TRUE) the TRUE is taken to mean 'trim' which is the 2nd argument of mean. 'trim' is not yet optimized.",immediate.=TRUE)
}
if (verbose) {
if (!identical(oldjsub, jsub))
cat("Old mean optimization changed j from '",deparse(oldjsub),"' to '",deparse(jsub,width.cutoff=200),"'\n",sep="")
else
cat("Old mean optimization is on, left j unchanged.\n")
}
assign("Cfastmean", Cfastmean, SDenv)
# Old comments still here for now ...
# Here in case nomeanopt=TRUE or some calls to mean weren't detected somehow. Better but still slow.
# Maybe change to :
# assign("mean", fastmean, SDenv) # neater than the hard work above, but slower
# when fastmean can do trim.
}
} else if (verbose) {
if (getOption("datatable.optimize")<1) cat("All optimizations are turned off\n")
else cat("Optimization is on but left j unchanged (single plain symbol): '",deparse(jsub,width.cutoff=200),"'\n",sep="")
}
if (byjoin) {
groups = i
grpcols = leftcols # 'leftcols' are the columns in i involved in the join (either head of key(i) or head along i)
jiscols = chmatch(jisvars,names(i)) # integer() if there are no jisvars (usually there aren't, advanced feature)
xjiscols = chmatch(xjisvars, names(x))
SDenv$.xSD = x[min(nrow(i), 1L), xjisvars, with=FALSE]
if (!missing(on)) o__ = xo else o__ = integer(0L)
} else {
groups = byval
grpcols = seq_along(byval)
jiscols = NULL # NULL rather than integer() is used in C to know when using by
xjiscols = NULL
}
lockBinding(".xSD", SDenv)
grporder = o__
# for #971, added !GForce. if (GForce) we do it much more (memory) efficiently than subset of order vector below.
if (length(irows) && !isTRUE(irows) && !GForce) {
# any zeros in irows were removed by convertNegAndZeroIdx earlier above; no need to check for zeros again. Test 1058-1061 check case #2758.
if (length(o__) && length(irows)!=length(o__)) stop("Internal error: length(irows)!=length(o__)") # nocov
o__ = if (length(o__)) irows[o__] # better do this once up front (even though another alloc) than deep repeated branch in dogroups.c
else irows
} # else grporder is left bound to same o__ memory (no cost of copy)
if (is.null(lhs)) cols=NULL
if (!length(f__)) {
# for consistency of empty case in test 184
f__=len__=0L
}
if (verbose) {last.started.at=proc.time();cat("Making each group and running j (GForce ",GForce,") ... ",sep="");flush.console()}
if (GForce) {
thisEnv = new.env() # not parent=parent.frame() so that gsum is found
for (ii in ansvars) assign(ii, x[[ii]], thisEnv)
assign(".N", len__, thisEnv) # For #5760
#fix for #1683
if (use.I) assign(".I", seq_len(nrow(x)), thisEnv)
ans = gforce(thisEnv, jsub, o__, f__, len__, irows) # irows needed for #971.
gi = if (length(o__)) o__[f__] else f__
g = lapply(grpcols, function(i) groups[[i]][gi])
ans = c(g, ans)
} else {
ans = .Call(Cdogroups, x, xcols, groups, grpcols, jiscols, xjiscols, grporder, o__, f__, len__, jsub, SDenv, cols, newnames, !missing(on), verbose)
}
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
# TO DO: xrows would be a better name for irows: irows means the rows of x that i joins to
# Grouping by i: icols the joins columns (might not need), isdcols (the non join i and used by j), all __ are length x
# Grouping by by: i is by val, icols NULL, o__ may be subset of x, f__ points to o__ (or x if !length o__)
# TO DO: setkey could mark the key whether it is unique or not.
if (!is.null(lhs)) {
if (any(names(x)[cols] %chin% key(x)))
setkey(x,NULL)
# fixes #1479. Take care of secondary indices, TODO: cleaner way of doing this
attrs = attr(x, 'index')
skeys = names(attributes(attrs))
if (!is.null(skeys)) {
hits = unlist(lapply(paste0("__", names(x)[cols]), function(x) grep(x, skeys, fixed = TRUE)))
hits = skeys[unique(hits)]
for (i in seq_along(hits)) setattr(attrs, hits[i], NULL) # does by reference
}
if (keyby) {
cnames = as.character(bysubl)[-1L]
cnames = gsub('^`|`$', '', cnames) # the wrapping backticks that were added above can be removed now, #3378
if (all(cnames %chin% names(x))) {
if (verbose) {last.started.at=proc.time();cat("setkey() after the := with keyby= ... ");flush.console()}
setkeyv(x,cnames) # TO DO: setkey before grouping to get memcpy benefit.
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
}
else warning(":= keyby not straightforward character column names or list() of column names, treating as a by:",paste(cnames,collapse=","),"\n")
}
return(suppPrint(x))
}
if (is.null(ans)) {
ans = as.data.table.list(lapply(groups,"[",0L)) # side-effects only such as test 168
setnames(ans,seq_along(bynames),bynames) # TO DO: why doesn't groups have bynames in the first place?
return(ans)
}
setattr(ans,"row.names",.set_row_names(length(ans[[1L]])))
setattr(ans,"class",class(x)) # fix for #5296
if (is.null(names(ans))) {
# Efficiency gain of dropping names has been successful. Ordinarily this will run.
if (is.null(jvnames)) jvnames = character(length(ans)-length(bynames))
if (length(bynames)+length(jvnames)!=length(ans))
stop("Internal error: jvnames is length ",length(jvnames), " but ans is ",length(ans)," and bynames is ", length(bynames)) # nocov
ww = which(jvnames=="")
if (any(ww)) jvnames[ww] = paste0("V",ww)
setattr(ans, "names", c(bynames, jvnames))
} else {
setnames(ans,seq_along(bynames),bynames) # TO DO: reinvestigate bynames flowing from dogroups here and simplify
}
if (byjoin && keyby && !bysameorder) {
if (verbose) {last.started.at=proc.time();cat("setkey() afterwards for keyby=.EACHI ... ");flush.console()}
setkeyv(ans,names(ans)[seq_along(byval)])
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
} else if (keyby || (haskey(x) && bysameorder && (byjoin || (length(allbyvars) && identical(allbyvars,head(key(x),length(allbyvars))))))) {
setattr(ans,"sorted",names(ans)[seq_along(grpcols)])
}
alloc.col(ans) # TODO: overallocate in dogroups in the first place and remove this line
}
.optmean <- function(expr) { # called by optimization of j inside [.data.table only. Outside for a small speed advantage.
if (length(expr)==2L) # no parameters passed to mean, so defaults of trim=0 and na.rm=FALSE
return(call(".External",quote(Cfastmean),expr[[2L]], FALSE))
# return(call(".Internal",expr)) # slightly faster than .External, but R now blocks .Internal in coerce.c from apx Sep 2012
if (length(expr)==3L && identical("na",substring(names(expr)[3L], 1L, 2L))) # one parameter passed to mean()
return(call(".External",quote(Cfastmean),expr[[2L]], expr[[3L]])) # faster than .Call
assign("nomeanopt",TRUE,parent.frame())
expr # e.g. trim is not optimized, just na.rm
}
# [[.data.frame is now dispatched due to inheritance.
# The code below tried to avoid that but made things
# very slow (462 times faster down to 1 in the timings test).
# TO DO. Reintroduce velow but dispatch straight to
# .C("do_subset2") or better. Tests 604-608 test
# that this doesn't regress.
#"[[.data.table" <- function(x,...) {
# if (!cedta()) return(`[[.data.frame`(x,...))
# .subset2(x,...)
# #class(x)=NULL # awful, copy
# #x[[...]]
#}
#"[[<-.data.table" <- function(x,i,j,value) {
# if (!cedta()) return(`[[<-.data.frame`(x,i,j,value))
# if (!missing(j)) stop("[[i,j]] assignment not available in data.table, put assignment(s) in [i,{...}] instead, more powerful")
# cl = oldClass(x) # [[<-.data.frame uses oldClass rather than class, don't know why but we'll follow suit
# class(x) = NULL
# x[[i]] = value
# class(x) = cl
# x
#}
as.matrix.data.table <- function(x, rownames=NULL, rownames.value=NULL, ...) {
# rownames = the rownames column (most common usage)
if (!is.null(rownames)) {
if (!is.null(rownames.value)) stop("rownames and rownames.value cannot both be used at the same time")
if (length(rownames)>1L) {
# TODO in future as warned in NEWS for 1.11.6:
# warning("length(rownames)>1 is deprecated. Please use rownames.value= instead")
if (length(rownames)!=nrow(x))
stop("length(rownames)==", length(rownames), " but nrow(DT)==", nrow(x),
". The rownames argument specifies a single column name or number. Consider rownames.value= instead.")
rownames.value = rownames
rownames = NULL
} else if (length(rownames)==0L) {
stop("length(rownames)==0 but should be a single column name or number, or NULL")
} else {
if (isTRUE(rownames)) {
if (length(key(x))>1L) {
warning("rownames is TRUE but key has multiple columns ",
brackify(key(x)), "; taking first column x[,1] as rownames")
}
rownames = if (length(key(x))==1L) chmatch(key(x),names(x)) else 1L
}
else if (is.logical(rownames) || is.na(rownames)) {
# FALSE, NA, NA_character_ all mean the same as NULL
rownames = NULL
}
else if (is.character(rownames)) {
w = chmatch(rownames, names(x))
if (is.na(w)) stop("'", rownames, "' is not a column of x")
rownames = w
}
else { # rownames is a column number already
rownames <- as.integer(rownames)
if (is.na(rownames) || rownames<1L || rownames>ncol(x))
stop("as.integer(rownames)==", rownames,
" which is outside the column number range [1,ncol=", ncol(x), "].")
}
}
} else if (!is.null(rownames.value)) {
if (length(rownames.value)!=nrow(x))
stop("length(rownames.value)==", length(rownames.value),
" but should be nrow(x)==", nrow(x))
}
if (!is.null(rownames)) {
# extract that column and drop it.
rownames.value <- x[[rownames]]
dm <- dim(x) - c(0, 1)
cn <- names(x)[-rownames]
X <- x[, .SD, .SDcols = cn]
} else {
dm <- dim(x)
cn <- names(x)
X <- x
}
if (any(dm == 0L))
return(array(NA, dim = dm, dimnames = list(rownames.value, cn)))
p <- dm[2L]
n <- dm[1L]
collabs <- as.list(cn)
class(X) <- NULL
non.numeric <- non.atomic <- FALSE
all.logical <- TRUE
for (j in seq_len(p)) {
if (is.ff(X[[j]])) X[[j]] <- X[[j]][] # to bring the ff into memory, since we need to create a matrix in memory
xj <- X[[j]]
if (length(dj <- dim(xj)) == 2L && dj[2L] > 1L) {
if (inherits(xj, "data.table"))
xj <- X[[j]] <- as.matrix(X[[j]])
dnj <- dimnames(xj)[[2L]]
collabs[[j]] <- paste(collabs[[j]], if (length(dnj) >
0L)
dnj
else seq_len(dj[2L]), sep = ".")
}
if (!is.logical(xj))
all.logical <- FALSE
if (length(levels(xj)) > 0L || !(is.numeric(xj) || is.complex(xj) || is.logical(xj)) ||
(!is.null(cl <- attr(xj, "class")) && any(cl %chin%
c("Date", "POSIXct", "POSIXlt"))))
non.numeric <- TRUE
if (!is.atomic(xj))
non.atomic <- TRUE
}
if (non.atomic) {
for (j in seq_len(p)) {
xj <- X[[j]]
if (is.recursive(xj)) { }
else X[[j]] <- as.list(as.vector(xj))
}
}
else if (all.logical) { }
else if (non.numeric) {
for (j in seq_len(p)) {
if (is.character(X[[j]])) next
xj <- X[[j]]
miss <- is.na(xj)
xj <- if (length(levels(xj))) as.vector(xj) else format(xj)
is.na(xj) <- miss
X[[j]] <- xj
}
}
X <- unlist(X, recursive = FALSE, use.names = FALSE)
dim(X) <- c(n, length(X)/n)
dimnames(X) <- list(rownames.value, unlist(collabs, use.names = FALSE))
X
}
# bug #2375. fixed. same as head.data.frame and tail.data.frame to deal with negative indices
head.data.table <- function(x, n=6L, ...) {
if (!cedta()) return(NextMethod())
stopifnot(length(n) == 1L)
i = seq_len(if (n<0L) max(nrow(x)+n, 0L) else min(n,nrow(x)))
x[i, , ]
}
tail.data.table <- function(x, n=6L, ...) {
if (!cedta()) return(NextMethod())
stopifnot(length(n) == 1L)
n <- if (n<0L) max(nrow(x) + n, 0L) else min(n, nrow(x))
i = seq.int(to=nrow(x), length.out=n)
x[i]
}
"[<-.data.table" <- function (x, i, j, value) {
# [<- is provided for consistency, but := is preferred as it allows by group and by reference to subsets of columns
# with no copy of the (very large, say 10GB) columns at all. := is like an UPDATE in SQL and we like and want two symbols to change.
if (!cedta()) {
x = if (nargs()<4L) `[<-.data.frame`(x, i, value=value)
else `[<-.data.frame`(x, i, j, value)
return(alloc.col(x)) # over-allocate (again). Avoid all this by using :=.
}
# TO DO: warning("Please use DT[i,j:=value] syntax instead of DT[i,j]<-value, for efficiency. See ?':='")
if (!missing(i)) {
isub=substitute(i)
i = eval(.massagei(isub), x, parent.frame())
if (is.matrix(i)) {
if (!missing(j)) stop("When i is a matrix in DT[i]<-value syntax, it doesn't make sense to provide j")
x = `[<-.data.frame`(x, i, value=value)
return(alloc.col(x))
}
i = x[i, which=TRUE]
# Tried adding ... after value above, and passing ... in here (e.g. for mult="first") but R CMD check
# then gives "The argument of a replacement function which corresponds to the right hand side must be
# named 'value'". So, users have to use := for that.
} else i = NULL # meaning (to C code) all rows, without allocating 1L:nrow(x) vector
if (missing(j)) j=names(x)
if (!is.atomic(j)) stop("j must be an atomic vector, see ?is.atomic")
if (anyNA(j)) stop("NA in j")
if (is.character(j)) {
newnames = setdiff(j,names(x))
cols = as.integer(chmatch(j, c(names(x),newnames)))
# We can now mix existing columns and new columns
} else {
if (!is.numeric(j)) stop("j must be vector of column name or positions")
if (any(j>ncol(x))) stop("Attempt to assign to column position greater than ncol(x). Create the column by name, instead. This logic intends to catch (most likely) user errors.")
cols = as.integer(j) # for convenience e.g. to convert 1 to 1L
newnames = NULL
}
reinstatekey=NULL
if (haskey(x) && identical(key(x),key(value)) &&
identical(names(x),names(value)) &&
is.sorted(i) &&
identical(substitute(x),quote(`*tmp*`))) {
# DT["a",]$y <- 1.1 winds up creating `*tmp*` subset of rows and assigning _all_ the columns into x and
# over-writing the key columns with the same value (not just the single 'y' column).
# That isn't good for speed; it's an R thing. Solution is to use := instead to avoid all this, but user
# expects key to be retained in this case because _he_ didn't assign to a key column (the internal base R
# code did).
reinstatekey=key(x)
}
if (!selfrefok(x) || truelength(x) < ncol(x)+length(newnames)) {
x = alloc.col(x,length(x)+length(newnames)) # because [<- copies via *tmp* and main/duplicate.c copies at length but copies truelength over too
# search for one other .Call to assign in [.data.table to see how it differs
}
verbose=getOption("datatable.verbose")
x = .Call(Cassign,copy(x),i,cols,newnames,value,verbose) # From 3.1.0, DF[2,"b"] = 7 no longer copies DF$a (so in this [<-.data.table method we need to copy)
alloc.col(x) # can maybe avoid this realloc, but this is (slow) [<- anyway, so just be safe.
if (length(reinstatekey)) setkeyv(x,reinstatekey)
invisible(x)
# no copy at all if user calls directly; i.e. `[<-.data.table`(x,i,j,value)
# or uses data.table := syntax; i.e. DT[i,j:=value]
# but, there is one copy by R in [<- dispatch to `*tmp*`; i.e. DT[i,j]<-value. *Update: not from R > 3.0.2, yay*
# That copy is via main/duplicate.c which preserves truelength but copies length amount. Hence alloc.col(x,length(x)).
# No warn passed to assign here because we know it'll be copied via *tmp*.
# := allows subassign to a column with no copy of the column at all, and by group, etc.
}
"$<-.data.table" <- function(x, name, value) {
if (!cedta()) {
ans = `$<-.data.frame`(x, name, value)
return(alloc.col(ans)) # over-allocate (again)
}
x = copy(x)
`[<-.data.table`(x,j=name,value=value) # important i is missing here
}
as.data.frame.data.table <- function(x, ...)
{
ans = copy(x)
setattr(ans,"row.names",.set_row_names(nrow(x))) # since R 2.4.0, data.frames can have non-character row names
setattr(ans,"class","data.frame")
setattr(ans,"sorted",NULL) # remove so if you convert to df, do something, and convert back, it is not sorted
setattr(ans,".internal.selfref",NULL)
# leave tl intact, no harm,
ans
}
as.list.data.table <- function(x, ...) {
# Similar to as.list.data.frame in base. Although a data.table/frame is a list, too, it may be
# being coerced to raw list type (by calling code) so that "[" and "[[" work in their raw list form,
# such as lapply does for data.frame. So we do have to remove the class attributes (and thus shallow
# copy is almost instant way to achieve that, without risking compatibility).
#if (sys.call(-2L)[[1L]]=="lapply")
# return(x)
ans = shallow(x)
setattr(ans, "class", NULL)
setattr(ans, "row.names", NULL)
setattr(ans, "sorted", NULL)
setattr(ans,".internal.selfref", NULL) # needed to pass S4 tests for example
ans
}
dimnames.data.table <- function(x) {
if (!cedta()) {
if (!inherits(x, "data.frame"))
stop("data.table inherits from data.frame (from v1.5), but this data.table does not. Has it been created manually (e.g. by using 'structure' rather than 'data.table') or saved to disk using a prior version of data.table?")
return(`dimnames.data.frame`(x))
}
list(NULL, names(x))
}
"dimnames<-.data.table" = function (x, value) # so that can do colnames(dt)=<..> as well as names(dt)=<..>
{
if (!cedta()) return(`dimnames<-.data.frame`(x,value)) # nocov ; will drop key but names<-.data.table (below) is more common usage and does retain the key
if (!is.list(value) || length(value) != 2L) stop("attempting to assign invalid object to dimnames of a data.table")
if (!is.null(value[[1L]])) stop("data.tables do not have rownames")
if (ncol(x) != length(value[[2L]])) stop("Can't assign ", length(value[[2L]]), " colnames to a ", ncol(x), "-column data.table")
setnames(x,as.character(value[[2L]]))
x # this returned value is now shallow copied by R 3.1.0 via *tmp*. A very welcome change.
}
"names<-.data.table" <- function(x,value)
{
# When non data.table aware packages change names, we'd like to maintain the key.
# If call is names(DT)[2]="newname", R will call this names<-.data.table function (notice no i) with 'value' already prepared to be same length as ncol
x = shallow(x) # `names<-` should not modify by reference. Related to #1015, #476 and #825. Needed for R v3.1.0+. TO DO: revisit
if (is.null(value))
setattr(x,"names",NULL) # e.g. plyr::melt() calls base::unname()
else
setnames(x,value)
x # this returned value is now shallow copied by R 3.1.0 via *tmp*. A very welcome change.
}
within.data.table <- function (data, expr, ...)
# basically within.list but retains key (if any)
# will be slower than using := or a regular query (see ?within for further info).
{
if (!cedta()) return(NextMethod())
parent <- parent.frame()
e <- evalq(environment(), data, parent)
eval(substitute(expr), e) # might (and it's known that some user code does) contain rm()
l <- as.list(e)
l <- l[!vapply_1b(l, is.null)]
nD <- length(del <- setdiff(names(data), (nl <- names(l))))
ans = copy(data)
if (length(nl)) ans[,nl] <- l
if (nD) ans[,del] <- NULL
if (haskey(data) && all(key(data) %chin% names(ans))) {
x = TRUE
for (i in key(data)) {
x = identical(data[[i]],ans[[i]])
if (!x) break
}
if (x) setattr(ans,"sorted",key(data))
}
ans
}
transform.data.table <- function (`_data`, ...)
# basically transform.data.frame with data.table instead of data.frame, and retains key
{
if (!cedta()) return(NextMethod())
e <- eval(substitute(list(...)), `_data`, parent.frame())
tags <- names(e)
inx <- chmatch(tags, names(`_data`))
matched <- !is.na(inx)
if (any(matched)) {
if (isTRUE(attr(`_data`, ".data.table.locked", TRUE))) setattr(`_data`, ".data.table.locked", NULL) # fix for #1641
`_data`[,inx[matched]] <- e[matched]
`_data` <- data.table(`_data`)
}
if (!all(matched)) {
ans <- do.call("data.table", c(list(`_data`), e[!matched]))
} else {
ans <- `_data`
}
key.cols <- key(`_data`)
if (!any(tags %chin% key.cols)) {
setattr(ans, "sorted", key.cols)
}
ans
}
subset.data.table <- function (x, subset, select, ...)
{
key.cols <- key(x)
if (missing(subset)) {
r <- TRUE
} else {
e <- substitute(subset)
r <- eval(e, x, parent.frame())
if (!is.logical(r))
stop("'subset' must evaluate to logical")
r <- r & !is.na(r)
}
if (missing(select)) {
vars <- seq_len(ncol(x))
} else {
nl <- as.list(seq_len(ncol(x)))
setattr(nl,"names",names(x))
vars <- eval(substitute(select), nl, parent.frame()) # e.g. select=colF:colP
# #891 fix - don't convert numeric vars to column names - will break when there are duplicate columns
key.cols <- intersect(key.cols, names(x)[vars]) ## Only keep key.columns found in the select clause
}
ans <- x[r, vars, with = FALSE]
if (nrow(ans) > 0L) {
if (!missing(select) && length(key.cols)) {
## Set the key on the returned data.table as long as the key
## columns that "remain" are the same as the original, or a
## prefix of it.
is.prefix <- all(key(x)[seq_len(length(key.cols))] == key.cols)
if (is.prefix) {
setattr(ans, "sorted", key.cols)
}
}
} else {
setkey(ans,NULL)
}
ans
}
# Equivalent of 'rowSums(is.na(dt) > 0L)' but much faster and memory efficient.
# Also called "complete.cases" in base. Unfortunately it's not a S3 generic.
# Also handles bit64::integer64. TODO: export this?
# For internal use only. 'by' requires integer input. No argument checks here yet.
is_na <- function(x, by=seq_along(x)) .Call(Cdt_na, x, by)
any_na <- function(x, by=seq_along(x)) .Call(CanyNA, x, by)
na.omit.data.table <- function (object, cols = seq_along(object), invert = FALSE, ...) {
# compare to stats:::na.omit.data.frame
if (!cedta()) return(NextMethod())
if ( !missing(invert) && is.na(as.logical(invert)) )
stop("Argument 'invert' must be logical TRUE/FALSE")
if (is.character(cols)) {
old = cols
cols = chmatch(cols, names(object), nomatch=0L)
if (any(idx <- cols==0L))
stop("Column", if (sum(idx)>1L) "s " else " ", brackify(old[idx]), if (sum(idx)>1L) " don't" else " doesn't", " exist in the input data.table")
}
cols = as.integer(cols)
ix = .Call(Cdt_na, object, cols)
# forgot about invert with no NA case, #2660
if (invert) {
if (all(ix))
object
else
.Call(CsubsetDT, object, which_(ix, bool = TRUE), seq_along(object))
} else {
if (any(ix))
.Call(CsubsetDT, object, which_(ix, bool = FALSE), seq_along(object))
else
object
}
}
which_ <- function(x, bool = TRUE) {
# fix for #1467, quotes result in "not resolved in current namespace" error
.Call(Cwhichwrapper, x, bool)
}
is.na.data.table <- function (x) {
if (!cedta()) return(`is.na.data.frame`(x))
do.call("cbind", lapply(x, "is.na"))
}
# not longer needed as inherits ...
# t.data.table <- t.data.frame
# Math.data.table <- Math.data.frame
# summary.data.table <- summary.data.frame
Ops.data.table <- function(e1, e2 = NULL)
{
ans = NextMethod()
if (cedta() && is.data.frame(ans))
ans = as.data.table(ans)
ans
}
split.data.table <- function(x, f, drop = FALSE, by, sorted = FALSE, keep.by = TRUE, flatten = TRUE, ..., verbose = getOption("datatable.verbose")) {
if (!is.data.table(x)) stop("x argument must be a data.table")
stopifnot(is.logical(drop), is.logical(sorted), is.logical(keep.by), is.logical(flatten))
# split data.frame way, using `f` and not `by` argument
if (!missing(f)) {
if (!length(f) && nrow(x))
stop("group length is 0 but data nrow > 0")
if (!missing(by))
stop("passing 'f' argument together with 'by' is not allowed, use 'by' when split by column in data.table and 'f' when split by external factor")
# same as split.data.frame - handling all exceptions, factor orders etc, in a single stream of processing was a nightmare in factor and drop consistency
return(lapply(split(x = seq_len(nrow(x)), f = f, drop = drop, ...), function(ind) x[ind]))
}
if (missing(by)) stop("Either 'by' or 'f' argument must be supplied")
# check reserved column names during processing
if (".ll.tech.split" %chin% names(x)) stop("Column '.ll.tech.split' is reserved for split.data.table processing")
if (".nm.tech.split" %chin% by) stop("Column '.nm.tech.split' is reserved for split.data.table processing")
if (!all(by %chin% names(x))) stop("Argument 'by' must refer to column names in x")
if (!all(by.atomic <- vapply_1b(by, function(.by) is.atomic(x[[.by]])))) stop("Argument 'by' must refer only to atomic-type columns, but the following columns are non-atomic: ", brackify(by[!by.atomic]))
# list of data.tables (flatten) or list of lists of ... data.tables
make.levels = function(x, cols, sorted) {
by.order = if (!sorted) x[, funique(.SD), .SDcols=cols] # remember order of data, only when not sorted=FALSE
ul = lapply(setNames(cols, nm=cols), function(col) {
if (!is.factor(x[[col]])) unique(x[[col]]) else {
.x_lev = levels(x[[col]])
#need to keep as a factor or order will be lost, #2082
factor(.x_lev, levels = .x_lev)
}
})
r = do.call("CJ", c(ul, sorted=sorted, unique=TRUE))
if (!sorted && nrow(by.order)) {
ii = r[by.order, on=cols, which=TRUE]
r = rbindlist(list(
r[ii], # original order from data
r[-ii] # empty levels at the end
))
}
r
}
.by = by[1L]
# this builds data.table call - is much more cleaner than handling each case one by one
dtq = as.list(call("[", as.name("x")))
join = FALSE
flatten_any = flatten && any(vapply_1b(by, function(col) is.factor(x[[col]])))
nested_current = !flatten && is.factor(x[[.by]])
if (!drop && (flatten_any || nested_current)) {
# create 'levs' here to avoid lexical scoping glitches, see #3151
levs = make.levels(x=x, cols=if (flatten) by else .by, sorted=sorted)
dtq[["i"]] = quote(levs)
join = TRUE
}
dtq[["j"]] = substitute(
list(.ll.tech.split=list(.expr)),
list(.expr = if (join) quote(if(.N == 0L) .SD[0L] else .SD) else as.name(".SD")) # simplify when `nomatch` accept NULL #857 ?
)
by.or.keyby = if (join) "by" else c("by"[!sorted], "keyby"[sorted])[1L]
dtq[[by.or.keyby]] = substitute( # retain order, for `join` and `sorted` it will use order of `i` data.table instead of `keyby`.
.expr,
list(.expr = if(join) {as.name(".EACHI")} else if (flatten) by else .by)
)
dtq[[".SDcols"]] = if (keep.by) names(x) else setdiff(names(x), if (flatten) by else .by)
if (join) dtq[["on"]] = if (flatten) by else .by
dtq = as.call(dtq)
if (isTRUE(verbose)) cat("Processing split.data.table with: ", deparse(dtq, width.cutoff=500L), "\n", sep="")
tmp = eval(dtq)
# add names on list
setattr(ll <- tmp$.ll.tech.split,
"names",
as.character(
if (!flatten) tmp[[.by]] else tmp[, list(.nm.tech.split=paste(unlist(lapply(.SD, as.character)), collapse = ".")), by=by, .SDcols=by]$.nm.tech.split
))
# handle nested split
if (flatten || length(by) == 1L) {
lapply(lapply(ll, setattr, '.data.table.locked', NULL), setDT)
# alloc.col could handle DT in list as done in: c9c4ff80bdd4c600b0c4eff23b207d53677176bd
} else if (length(by) > 1L) {
lapply(ll, split.data.table, drop=drop, by=by[-1L], sorted=sorted, keep.by=keep.by, flatten=flatten)
}
}
# TO DO, add more warnings e.g. for by.data.table(), telling user what the data.table syntax is but letting them dispatch to data.frame if they want
copy <- function(x) {
newx = .Call(Ccopy,x) # copies at length but R's duplicate() also copies truelength over.
# TO DO: inside Ccopy it could reset tl to 0 or length, but no matter as selfrefok detects it
# TO DO: revisit duplicate.c in R 3.0.3 and see where it's at
if (!is.data.table(x)) {
# fix for #1476. TODO: find if a cleaner fix is possible..
if (is.list(x)) {
anydt = vapply(x, is.data.table, TRUE, USE.NAMES=FALSE)
if (sum(anydt)) {
newx[anydt] = lapply(newx[anydt], function(x) {
setattr(x, ".data.table.locked", NULL)
alloc.col(x)
})
}
}
return(newx) # e.g. in as.data.table.list() the list is copied before changing to data.table
}
setattr(newx,".data.table.locked",NULL)
alloc.col(newx)
}
point <- function(to, to_idx, from, from_idx) {
.Call(CpointWrapper, to, to_idx, from, from_idx)
}
.shallow <- function(x, cols = NULL, retain.key = FALSE, unlock = FALSE) {
isnull = is.null(cols)
if (!isnull) cols = validate(cols, x) # NULL is default = all columns
ans = .Call(Cshallowwrapper, x, cols) # copies VECSXP only
if(retain.key){
if (isnull) return(ans) # handle most frequent case first
## get correct key if cols are present
cols = names(x)[cols]
keylength <- which.first(!key(ans) %chin% cols) - 1L
if (is.na(keylength)) keylength <- length(key(ans))
if (!keylength) {
setattr(ans, "sorted", NULL) ## no key remaining
} else {
setattr(ans, "sorted", head(key(ans), keylength)) ## keep what can be kept
}
## take care of attributes.
indices <- names(attributes(attr(ans, "index")))
for(index in indices) {
indexcols <- strsplit(index, split = "__")[[1L]][-1L]
indexlength <- which.first(!indexcols %chin% cols) - 1L
if (is.na(indexlength)) next ## all columns are present, nothing to be done
reducedindex <- paste0("__", indexcols[seq_len(indexlength)], collapse="") ## the columns until the first missing from the new index
if (reducedindex %chin% indices || !indexlength) {
## Either reduced index already present or no columns of the original index remain.
## Drop the original index completely
setattr(attr(ans, "index", exact = TRUE), index, NULL)
} else if(length(attr(attr(ans, "index"), index))) {
## index is not length 0. Drop it since shortening could lead to spurious reordering in discarded columns (#2336)
setattr(attr(ans, "index", exact = TRUE), index, NULL)
} else {
## rename index to reducedindex
names(attributes(attr(ans, "index")))[names(attributes(attr(ans, "index"))) == index] <- reducedindex
}
}
} else { # retain.key == FALSE
setattr(ans, "sorted", NULL)
setattr(ans, "index", NULL)
}
if (unlock) setattr(ans, '.data.table.locked', NULL)
ans
}
shallow <- function(x, cols=NULL) {
if (!is.data.table(x))
stop("x is not a data.table. Shallow copy is a copy of the vector of column pointers (only), so is only meaningful for data.table")
ans = .shallow(x, cols=cols, retain.key = TRUE)
ans
}
alloc.col <- function(DT, n=getOption("datatable.alloccol"), verbose=getOption("datatable.verbose"))
{
name = substitute(DT)
if (identical(name,quote(`*tmp*`))) stop("alloc.col attempting to modify `*tmp*`")
ans = .Call(Calloccolwrapper, DT, eval(n), verbose)
if (is.name(name)) {
name = as.character(name)
assign(name,ans,parent.frame(),inherits=TRUE)
}
.Call(Csetmutable,ans)
}
selfrefok <- function(DT,verbose=getOption("datatable.verbose")) {
.Call(Cselfrefokwrapper,DT,verbose)
}
truelength <- function(x) .Call(Ctruelength,x)
# deliberately no "truelength<-" method. alloc.col is the mechanism for that.
# settruelength() no longer need (and so removed) now that data.table depends on R 2.14.0
# which initializes tl to zero rather than leaving uninitialized.
setattr <- function(x,name,value) {
# Wrapper for setAttrib internal R function
# Sets attribute by reference (no copy)
# Named setattr (rather than setattrib) at R level to more closely resemble attr<-
# And as from 1.7.8 is made exported in NAMESPACE for use in user attributes.
# User can also call `attr<-` function directly, but that copies (maybe just when NAMED>0, which is always for data.frame, I think). See "Confused by NAMED" thread on r-devel 24 Nov 2011.
# We tend to use setattr() internally in data.table.R because often we construct a data.table and it hasn't
# got names yet. setnames() is the user interface which checks integrity and doesn't let you drop names for example.
if (name=="names" && is.data.table(x) && length(attr(x,"names")) && !is.null(value))
setnames(x,value)
# Using setnames here so that truelength of names can be retained, to carry out integrity checks such as not
# creating names longer than the number of columns of x, and to change the key, too
# For convenience so that setattr(DT,"names",allnames) works as expected without requiring a switch to setnames.
else {
ans = .Call(Csetattrib, x, name, value)
# If name=="names" and this is the first time names are assigned (e.g. in data.table()), this will be grown by alloc.col very shortly afterwards in the caller.
if (!is.null(ans)) {
warning("Input is a length=1 logical that points to the same address as R's global value. Therefore the attribute has not been set by reference, rather on a copy. You will need to assign the result back to a variable. See issue #1281.")
x = ans
}
}
# fix for #1142 - duplicated levels for factors
if (name == "levels" && is.factor(x) && anyDuplicated(value))
.Call(Csetlevels, x, (value <- as.character(value)), unique(value))
invisible(x)
}
setnames <- function(x,old,new,skip_absent=FALSE) {
# Sets by reference, maintains truelength, no copy of table at all.
# But also more convenient than names(DT)[i]="newname" because we can also do setnames(DT,"oldname","newname")
# without an onerous match() ourselves. old can be positions, too, but we encourage by name for robustness.
if (!is.data.frame(x)) stop("x is not a data.table or data.frame")
if (length(names(x)) != length(x)) stop("x is length ",length(x)," but its names are length ",length(names(x)))
stopifnot(isTRUEorFALSE(skip_absent))
if (missing(new)) {
# for setnames(DT,new); e.g., setnames(DT,c("A","B")) where ncol(DT)==2
if (!is.character(old)) stop("Passed a vector of type '",typeof(old),"'. Needs to be type 'character'.")
if (length(old) != ncol(x)) stop("Can't assign ",length(old)," names to a ",ncol(x)," column data.table")
nx <- names(x)
# note that duplicate names are permitted to be created in this usage only
if (anyNA(nx)) {
# if x somehow has some NA names, which() needs help to return them, #2475
w = which((nx != old) | (is.na(nx) & !is.na(old)))
} else {
w = which(nx != old)
}
if (!length(w)) return(invisible(x)) # no changes
new = old[w]
i = w
} else {
if (missing(old)) stop("When 'new' is provided, 'old' must be provided too")
if (!is.character(new)) stop("'new' is not a character vector")
if (is.numeric(old)) {
if (length(sgn <- unique(sign(old))) != 1L)
stop("Items of 'old' is numeric but has both +ve and -ve indices.")
tt = abs(old)<1L | abs(old)>length(x) | is.na(old)
if (any(tt)) stop("Items of 'old' either NA or outside range [1,",length(x),"]: ",paste(old[tt],collapse=","))
i = if (sgn == 1L) as.integer(old) else seq_along(x)[as.integer(old)]
if (any(duplicated(i))) stop("Some duplicates exist in 'old': ",paste(i[duplicated(i)],collapse=","))
} else {
if (!is.character(old)) stop("'old' is type ",typeof(old)," but should be integer, double or character")
if (any(duplicated(old))) stop("Some duplicates exist in 'old': ", paste(old[duplicated(old)],collapse=","))
i = chmatch(old,names(x))
if (anyNA(i)) {
if (isTRUE(skip_absent)) {
w <- old %chin% names(x)
old = old[w]
new = new[w]
i = i[w]
} else {
stop("Items of 'old' not found in column names: ",paste(old[is.na(i)],collapse=","), ". Consider skip_absent=TRUE.")
}
}
if (any(tt<-!is.na(chmatch(old,names(x)[-i])))) stop("Some items of 'old' are duplicated (ambiguous) in column names: ",paste(old[tt],collapse=","))
}
if (length(new)!=length(i)) stop("'old' is length ",length(i)," but 'new' is length ",length(new))
}
# update the key if the column name being change is in the key
m = chmatch(names(x)[i], key(x))
w = which(!is.na(m))
if (length(w))
.Call(Csetcharvec, attr(x,"sorted"), m[w], new[w])
# update secondary keys
idx = attr(x,"index")
for (k in names(attributes(idx))) {
tt = strsplit(k,split="__")[[1L]][-1L]
m = chmatch(names(x)[i], tt)
w = which(!is.na(m))
if (length(w)) {
tt[m[w]] = new[w]
newk = paste0("__",tt,collapse="")
setattr(idx, newk, attr(idx, k))
setattr(idx, k, NULL)
}
}
.Call(Csetcharvec, attr(x,"names"), as.integer(i), new)
invisible(x)
}
setcolorder <- function(x, neworder=key(x))
{
if (anyDuplicated(neworder)) stop("neworder contains duplicates")
# if (!is.data.table(x)) stop("x is not a data.table")
if (length(neworder) != length(x)) {
if (length(neworder) > length(x))
stop("neworder is length ", length(neworder),
" but x has only ", length(x), " columns.")
#if shorter than length(x), pad by the missing
# elements (checks below will catch other mistakes)
neworder = c(neworder, setdiff(if (is.character(neworder)) names(x)
else seq_along(x), neworder))
}
if (is.character(neworder)) {
if (any(duplicated(names(x)))) stop("x has some duplicated column name(s): ", paste(names(x)[duplicated(names(x))], collapse=","), ". Please remove or rename the duplicate(s) and try again.")
o = as.integer(chmatch(neworder, names(x)))
if (anyNA(o)) stop("Names in neworder not found in x: ", paste(neworder[is.na(o)], collapse=","))
} else {
if (!is.numeric(neworder)) stop("neworder is not a character or numeric vector")
o = as.integer(neworder)
m = !(o %in% seq_len(length(x)))
if (any(m)) stop("Column numbers in neworder out of bounds: ", paste(o[m], collapse=","))
}
.Call(Csetcolorder, x, o)
invisible(x)
}
set <- function(x,i=NULL,j,value) # low overhead, loopable
{
if (is.atomic(value)) {
# protect NAMED of atomic value from .Call's NAMED=2 by wrapping with list()
l = vector("list", 1L)
.Call(Csetlistelt,l,1L,value) # to avoid the copy by list() in R < 3.1.0
value = l
}
.Call(Cassign,x,i,j,NULL,value,FALSE) # verbose=FALSE for speed to avoid getOption() TO DO: somehow read getOption("datatable.verbose") from C level
invisible(x)
}
chmatch <- function(x, table, nomatch=NA_integer_)
.Call(Cchmatch, x, table, as.integer(nomatch[1L])) # [1L] to fix #1672
# chmatchdup() behaves like 'pmatch' but only the 'exact' matching part; i.e. a value in
# 'x' is matched to 'table' only once. No index will be present more than once. For example:
# chmatchdup(c("a", "a"), c("a", "a")) # 1,2 - the second 'a' in 'x' has a 2nd match in 'table'
# chmatchdup(c("a", "a"), c("a", "b")) # 1,NA - the second one doesn't 'see' the first 'a'
# chmatchdup(c("a", "a"), c("a", "a.1")) # 1,NA - this is where it differs from pmatch - we don't need the partial match.
chmatchdup <- function(x, table, nomatch=NA_integer_)
.Call(Cchmatchdup, x, table, as.integer(nomatch[1L]))
"%chin%" <- function(x, table)
.Call(Cchin, x, table) # TO DO if table has 'ul' then match to that
chorder <- function(x) {
o = forderv(x, sort=TRUE, retGrp=FALSE)
if (length(o)) o else seq_along(x)
}
chgroup <- function(x) {
# TO DO: deprecate and remove this. It's exported but doubt anyone uses it. Think the plan was to use it internally, but forderv superceded.
o = forderv(x, sort=FALSE, retGrp=TRUE)
if (length(o)) as.vector(o) else seq_along(x) # as.vector removes the attributes
}
.rbind.data.table <- function(..., use.names=TRUE, fill=FALSE, idcol=NULL) {
# See FAQ 2.23
# Called from base::rbind.data.frame
# fix for #1626.. because some packages (like psych) bind an input
# data.frame/data.table with a matrix..
l = lapply(list(...), function(x) if (is.list(x)) x else as.data.table(x))
rbindlist(l, use.names, fill, idcol)
}
rbindlist <- function(l, use.names="check", fill=FALSE, idcol=NULL) {
if (isFALSE(idcol)) { idcol = NULL }
else if (!is.null(idcol)) {
if (isTRUE(idcol)) idcol = ".id"
if (!is.character(idcol)) stop("idcol must be a logical or character vector of length 1. If logical TRUE the id column will named '.id'.")
idcol = idcol[1L]
}
miss = missing(use.names)
# more checking of use.names happens at C level; this is just minimal to massage 'check' to NA
if (identical(use.names, NA)) stop("use.names=NA invalid") # otherwise use.names=NA could creep in an usage equivalent to use.names='check'
if (identical(use.names,"check")) {
if (!miss) stop("use.names='check' cannot be used explicitly because the value 'check' is new in v1.12.2 and subject to change. It is just meant to convey default behavior. See ?rbindlist.")
use.names = NA
}
ans = .Call(Crbindlist, l, use.names, fill, idcol)
if (!length(ans)) return(null.data.table())
setDT(ans)[]
}
vecseq <- function(x,y,clamp) .Call(Cvecseq,x,y,clamp)
# .Call(Caddress, x) increments NAM() when x is vector with NAM(1). Referring object within non-primitive function is enough to increment reference.
address <- function(x) .Call(Caddress, eval(substitute(x), parent.frame()))
":=" <- function(...) stop('Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").')
setDF <- function(x, rownames=NULL) {
if (!is.list(x)) stop("setDF only accepts data.table, data.frame or list of equal length as input")
if (anyDuplicated(rownames)) stop("rownames contains duplicates")
if (is.data.table(x)) {
# copied from as.data.frame.data.table
if (is.null(rownames)) {
rn <- .set_row_names(nrow(x))
} else {
if (length(rownames) != nrow(x))
stop("rownames incorrect length; expected ", nrow(x), " names, got ", length(rownames))
rn <- rownames
}
setattr(x, "row.names", rn)
setattr(x, "class", "data.frame")
setattr(x, "sorted", NULL)
setattr(x, ".internal.selfref", NULL)
} else if (is.data.frame(x)) {
if (!is.null(rownames)) {
if (length(rownames) != nrow(x))
stop("rownames incorrect length; expected ", nrow(x), " names, got ", length(rownames))
setattr(x, "row.names", rownames)
}
x
} else {
n = vapply(x, length, 0L)
mn = max(n)
if (any(n<mn))
stop("All elements in argument 'x' to 'setDF' must be of same length")
xn = names(x)
if (is.null(xn)) {
setattr(x, "names", paste0("V",seq_len(length(x))))
} else {
idx = xn %chin% ""
if (any(idx)) {
xn[idx] = paste0("V", seq_along(which(idx)))
setattr(x, "names", xn)
}
}
if (is.null(rownames)) {
rn <- .set_row_names(mn)
} else {
if (length(rownames) != mn)
stop("rownames incorrect length; expected ", mn, " names, got ", length(rownames))
rn <- rownames
}
setattr(x,"row.names", rn)
setattr(x,"class","data.frame")
}
invisible(x)
}
setDT <- function(x, keep.rownames=FALSE, key=NULL, check.names=FALSE) {
name = substitute(x)
if (is.name(name)) {
home <- function(x, env) {
if (identical(env, emptyenv()))
stop("Cannot find symbol ", cname, call. = FALSE)
else if (exists(x, env, inherits=FALSE)) env
else home(x, parent.env(env))
}
cname = as.character(name)
envir = home(cname, parent.frame())
if (bindingIsLocked(cname, envir)) {
stop("Can not convert '", cname, "' to data.table by reference because binding is locked. It is very likely that '", cname, "' resides within a package (or an environment) that is locked to prevent modifying its variable bindings. Try copying the object to your current environment, ex: var <- copy(var) and then using setDT again.")
}
}
if (is.data.table(x)) {
# fix for #1078 and #1128, see .resetclass() for explanation.
setattr(x, 'class', .resetclass(x, 'data.table'))
if (!missing(key)) setkeyv(x, key) # fix for #1169
if (check.names) setattr(x, "names", make.names(names(x), unique=TRUE))
if (selfrefok(x) > 0) return(invisible(x)) else alloc.col(x)
} else if (is.data.frame(x)) {
rn = if (!identical(keep.rownames, FALSE)) rownames(x) else NULL
setattr(x, "row.names", .set_row_names(nrow(x)))
if (check.names) setattr(x, "names", make.names(names(x), unique=TRUE))
# fix for #1078 and #1128, see .resetclass() for explanation.
setattr(x, "class", .resetclass(x, 'data.frame'))
alloc.col(x)
if (!is.null(rn)) {
nm = c(if (is.character(keep.rownames)) keep.rownames[1L] else "rn", names(x))
x[, (nm[1L]) := rn]
setcolorder(x, nm)
}
} else if (is.null(x) || (is.list(x) && !length(x))) {
x = null.data.table()
} else if (is.list(x)) {
# copied from as.data.table.list - except removed the copy
for (i in seq_along(x)) {
if (inherits(x[[i]], "POSIXlt"))
stop("Column ", i, " is of POSIXlt type. Please convert it to POSIXct using as.POSIXct and run setDT again. We do not recommend use of POSIXlt at all because it uses 40 bytes to store one date.")
}
n = vapply(x, length, 0L)
n_range = range(n)
if (n_range[1L] != n_range[2L]) {
tbl = sort(table(n))
stop("All elements in argument 'x' to 'setDT' must be of same length, ",
"but the profile of input lengths (length:frequency) is: ",
brackify(sprintf('%s:%d', names(tbl), tbl)),
"\nThe first entry with fewer than ", n_range[2L],
" entries is ", which.max(n<n_range[2L]))
}
xn = names(x)
if (is.null(xn)) {
setattr(x, "names", paste0("V",seq_len(length(x))))
} else {
idx = xn %chin% "" # names can be NA - test 1006 caught that!
if (any(idx)) {
xn[idx] = paste0("V", seq_along(which(idx)))
setattr(x, "names", xn)
}
if (check.names) setattr(x, "names", make.names(xn, unique=TRUE))
}
setattr(x,"row.names",.set_row_names(n_range[2L]))
setattr(x,"class",c("data.table","data.frame"))
alloc.col(x)
} else {
stop("Argument 'x' to 'setDT' should be a 'list', 'data.frame' or 'data.table'")
}
if (!is.null(key)) setkeyv(x, key)
if (is.name(name)) {
name = as.character(name)
assign(name, x, parent.frame(), inherits=TRUE)
} else if (is.call(name) && (name[[1L]] == "$" || name[[1L]] == "[[") && is.name(name[[2L]])) {
# common case is call from 'lapply()'
k = eval(name[[2L]], parent.frame(), parent.frame())
if (is.list(k)) {
origj = j = if (name[[1L]] == "$") as.character(name[[3L]]) else eval(name[[3L]], parent.frame(), parent.frame())
if (length(j) == 1L) {
if (is.character(j)) {
j = match(j, names(k))
if (is.na(j))
stop("Item '", origj, "' not found in names of input list")
}
}
.Call(Csetlistelt,k,as.integer(j), x)
} else if (is.environment(k) && exists(as.character(name[[3L]]), k)) {
assign(as.character(name[[3L]]), x, k, inherits=FALSE)
}
}
.Call(CexpandAltRep, x) # issue#2866 and PR#2882
invisible(x)
}
as_list <- function(x) {
lx = vector("list", 1L)
.Call(Csetlistelt, lx, 1L, x)
lx
}
# FR #1353
rowid <- function(..., prefix=NULL) {
rowidv(list(...), prefix=prefix)
}
rowidv <- function(x, cols=seq_along(x), prefix=NULL) {
if (!is.null(prefix) && (!is.character(prefix) || length(prefix) != 1L))
stop("prefix must be NULL or a character vector of length=1.")
if (is.atomic(x)) {
if (!missing(cols) && !is.null(cols))
stop("x is a single vector, non-NULL 'cols' doesn't make sense.")
cols = 1L
x = as_list(x)
} else {
if (!length(cols))
stop("x is a list, 'cols' can not be on 0-length.")
if (is.character(cols))
cols = chmatch(cols, names(x))
cols = as.integer(cols)
}
xorder = forderv(x, by=cols, sort=FALSE, retGrp=TRUE) # speedup on char with sort=FALSE
xstart = attr(xorder, 'start')
if (!length(xorder)) xorder = seq_along(x[[1L]])
ids = .Call(Cfrank, xorder, xstart, uniqlengths(xstart, length(xorder)), "sequence")
if (!is.null(prefix))
ids = paste0(prefix, ids)
ids
}
# FR #686
rleid <- function(..., prefix=NULL) {
rleidv(list(...), prefix=prefix)
}
rleidv <- function(x, cols=seq_along(x), prefix=NULL) {
if (!is.null(prefix) && (!is.character(prefix) || length(prefix) != 1L))
stop("prefix must be NULL or a character vector of length=1.")
if (is.atomic(x)) {
if (!missing(cols) && !is.null(cols))
stop("x is a single vector, non-NULL 'cols' doesn't make sense.")
cols = 1L
x = as_list(x)
} else {
if (!length(cols))
stop("x is a list, 'cols' can not be 0-length.")
if (is.character(cols))
cols = chmatch(cols, names(x))
cols = as.integer(cols)
}
ids = .Call(Crleid, x, cols)
if (!is.null(prefix)) ids = paste0(prefix, ids)
ids
}
# GForce functions
`g[` <- function(x, n) .Call(Cgnthvalue, x, as.integer(n)) # n is of length=1 here.
ghead <- function(x, n) .Call(Cghead, x, as.integer(n)) # n is not used at the moment
gtail <- function(x, n) .Call(Cgtail, x, as.integer(n)) # n is not used at the moment
gfirst <- function(x) .Call(Cgfirst, x)
glast <- function(x) .Call(Cglast, x)
gsum <- function(x, na.rm=FALSE) .Call(Cgsum, x, na.rm)
gmean <- function(x, na.rm=FALSE) .Call(Cgmean, x, na.rm)
gprod <- function(x, na.rm=FALSE) .Call(Cgprod, x, na.rm)
gmedian <- function(x, na.rm=FALSE) .Call(Cgmedian, x, na.rm)
gmin <- function(x, na.rm=FALSE) .Call(Cgmin, x, na.rm)
gmax <- function(x, na.rm=FALSE) .Call(Cgmax, x, na.rm)
gvar <- function(x, na.rm=FALSE) .Call(Cgvar, x, na.rm)
gsd <- function(x, na.rm=FALSE) .Call(Cgsd, x, na.rm)
gforce <- function(env, jsub, o, f, l, rows) .Call(Cgforce, env, jsub, o, f, l, rows)
isReallyReal <- function(x) {
.Call(CisReallyReal, x)
}
.prepareFastSubset <- function(isub, x, enclos, notjoin, verbose = FALSE){
## helper that decides, whether a fast binary search can be performed, if i is a call
## For details on the supported queries, see \code{\link{datatable-optimize}}
## Additional restrictions are imposed if x is .SD, or if options indicate that no optimization
## is to be performed
#' @param isub the substituted i
#' @param x the data.table
#' @param enclos The environment where to evaluate when RHS is not a column of x
#' @param notjoin boolean that is set before, indicating whether i started with '!'.
#' @param verbose TRUE for detailed output
#' @return If i is not fast subsettable, NULL. Else, a list with entries:
#' out$i: a data.table that will be used as i with proper column names and key.
#' out$on: the correct 'on' statement that will be used for x[i, on =...]
#' out$notjoin Bool. In some cases, notjoin is updated within the function.
#' ATTENTION: If nothing else helps, an auto-index is created on x unless options prevent this.
if(getOption("datatable.optimize") < 3L) return(NULL) ## at least level three optimization required.
if (!is.call(isub)) return(NULL)
if (!is.null(attr(x, '.data.table.locked'))) return(NULL) # fix for #958, don't create auto index on '.SD'.
## a list of all possible operators with their translations into the 'on' clause
validOps <- list(op = c("==", "%in%", "%chin%"),
on = c("==", "==", "=="))
## Determine, whether the nature of isub in general supports fast binary search
remainingIsub <- isub
i <- list()
on <- character(0)
nonEqui = FALSE
while(length(remainingIsub)){
if(is.call(remainingIsub)){
if (length(remainingIsub[[1L]]) != 1L) return(NULL) ## only single symbol, either '&' or one of validOps allowed.
if (remainingIsub[[1L]] != "&"){ ## only a single expression present or a different connection.
stub <- remainingIsub
remainingIsub <- NULL ## there is no remainder to be evaluated after stub.
} else {
## multiple expressions with & connection.
if (notjoin) return(NULL) ## expressions of type DT[!(a==1 & b==2)] currently not supported
stub <- remainingIsub[[3L]] ## the single column expression like col == 4
remainingIsub <- remainingIsub[[2L]] ## the potentially longer expression with potential additional '&'
}
} else { ## single symbol present
stub <- remainingIsub
remainingIsub <- NULL
}
## check the stub if it is fastSubsettable
if(is.symbol(stub)){
## something like DT[x & y]. If x and y are logical columns, we can optimize.
col <- as.character(stub)
if(!col %chin% names(x)) return(NULL)
if(!is.logical(x[[col]])) return(NULL)
## redirect to normal DT[x == TRUE]
stub <- call("==", as.symbol(col), TRUE)
}
if (length(stub[[1L]]) != 1) return(NULL) ## Whatever it is, definitely not one of the valid operators
operator <- as.character(stub[[1L]])
if (!operator %chin% validOps$op) return(NULL) ## operator not supported
if (!is.name(stub[[2L]])) return(NULL)
col <- as.character(stub[[2L]])
if (!col %chin% names(x)) return(NULL) ## any non-column name prevents fast subsetting
if(col %chin% names(i)) return(NULL) ## repeated appearance of the same column not suported (e.g. DT[x < 3 & x < 5])
## now check the RHS of stub
RHS = eval(stub[[3L]], x, enclos)
if (is.list(RHS)) RHS = as.character(RHS) # fix for #961
if (length(RHS) != 1L && !operator %chin% c("%in%", "%chin%")){
if (length(RHS) != nrow(x)) stop("RHS of ", operator, " is length ",length(RHS)," which is not 1 or nrow (",nrow(x),"). For robustness, no recycling is allowed (other than of length 1 RHS). Consider %in% instead.")
return(NULL) # DT[colA == colB] regular element-wise vector scan
}
if ( mode(x[[col]]) != mode(RHS) || # mode() so that doubleLHS/integerRHS and integerLHS/doubleRHS!isReallyReal are optimized (both sides mode 'numeric')
is.factor(x[[col]])+is.factor(RHS) == 1L || # but factor is also mode 'numeric' so treat that separately
is.integer(x[[col]]) && isReallyReal(RHS) ) { # and if RHS contains fractions then don't optimize that as bmerge truncates the fractions to match to the target integer type
# re-direct non-matching type cases to base R, as data.table's binary
# search based join is strict in types. #957, #961 and #1361
# the mode() checks also deals with NULL since mode(NULL)=="NULL" and causes this return, as one CRAN package (eplusr 0.9.1) relies on
return(NULL)
}
if(is.character(x[[col]]) && !operator %chin% c("==", "%in%", "%chin%")) return(NULL) ## base R allows for non-equi operators on character columns, but these can't be optimized.
if (!operator %chin% c("%in%", "%chin%")) {
# addional requirements for notjoin and NA values. Behaviour is different for %in%, %chin% compared to other operators
# RHS is of length=1 or n
if (any_na(as_list(RHS))) {
## dt[x == NA] or dt[x <= NA] will always return empty
notjoin = FALSE
RHS = RHS[0L]
} else if (notjoin) {
## dt[!x == 3] must not return rows where x is NA
RHS = c(RHS, if (is.double(RHS)) c(NA, NaN) else NA)
}
}
## if it passed until here, fast subset can be done for this stub
i <- c(i, setNames(list(RHS), col))
on <- c(on, setNames(paste0(col, validOps$on[validOps$op == operator], col), col))
## loop continues with remainingIsub
}
if (length(i) == 0L) stop("Internal error in .isFastSubsettable. Please report to data.table developers") # nocov
## convert i to data.table with all combinations in rows.
if(length(i) > 1L && prod(vapply(i, length, integer(1L))) > 1e4){
## CJ would result in more than 1e4 rows. This would be inefficient, especially memory-wise #2635
if (verbose) {cat("Subsetting optimization disabled because the cross-product of RHS values exceeds 1e4, causing memory problems.\n");flush.console()}
return(NULL)
}
## Care is needed with names as we construct i
## with 'CJ' and 'do.call' and this would cause problems if colNames were 'sorted' or 'unique'
## as these two would be interpreted as args for CJ
colNames <- names(i)
names(i) <- NULL
i$sorted <- FALSE
i$unique <- TRUE
i <- do.call(CJ, i)
setnames(i, colNames)
idx <- NULL
if(is.null(idx)){
## check whether key fits the columns in i.
## order of key columns makes no difference, as long as they are all upfront in the key, I believe.
if (all(names(i) %chin% head(key(x), length(i)))){
if (verbose) {cat("Optimized subsetting with key '", paste0( head(key(x), length(i)), collapse = ", "),"'\n",sep="");flush.console()}
idx <- integer(0L) ## integer(0L) not NULL! Indicates that x is ordered correctly.
idxCols <- head(key(x), length(i)) ## in correct order!
}
}
if (is.null(idx)){
if (!getOption("datatable.use.index")) return(NULL) # #1422
## check whether an exising index can be used
## An index can be used if it corresponds exactly to the columns in i (similar to the key above)
candidates <- indices(x, vectors = TRUE)
idx <- NULL
for (cand in candidates){
if (all(names(i) %chin% cand) && length(cand) == length(i)){
idx <- attr(attr(x, "index"), paste0("__", cand, collapse = ""))
idxCols <- cand
break
}
}
if (!is.null(idx)){
if (verbose) {cat("Optimized subsetting with index '", paste0( idxCols, collapse = "__"),"'\n",sep="");flush.console()}
}
}
if (is.null(idx)){
## if nothing else helped, auto create a new index that can be used
if (!getOption("datatable.auto.index")) return(NULL)
if (verbose) {cat("Creating new index '", paste0(names(i), collapse = "__"),"'\n",sep="");flush.console()}
if (verbose) {last.started.at=proc.time();cat("Creating index", paste0(names(i), collapse = "__"), "done in ... ");flush.console()}
setindexv(x, names(i))
if (verbose) {cat(timetaken(last.started.at),"\n");flush.console()}
if (verbose) {cat("Optimized subsetting with index '", paste0(names(i), collapse = "__"),"'\n",sep="");flush.console()}
idx <- attr(attr(x, "index"), paste0("__", names(i), collapse = ""))
idxCols <- names(i)
}
if(!is.null(idxCols)){
setkeyv(i, idxCols)
on <- on[idxCols] ## make sure 'on' is in the correct order. Otherwise the logic won't recognise that a key / index already exists.
}
return(list(i = i,
on = on,
notjoin = notjoin
)
)
}
.parse_on <- function(onsub, isnull_inames) {
## helper that takes the 'on' string(s) and extracts comparison operators and column names from it.
#' @param onsub the substituted on
#' @param isnull_inames bool; TRUE if i has no names.
#' @return List with two entries:
#' 'on' : character vector providing the column names for the join.
#' Names correspond to columns in x, entries correspond to columns in i
#' 'ops': integer vector. Gives the indices of the operators that connect the columns in x and i.
ops = c("==", "<=", "<", ">=", ">", "!=")
pat = paste0("(", ops, ")", collapse="|")
if (is.call(onsub) && onsub[[1L]] == "eval") {
onsub = eval(onsub[[2L]], parent.frame(2L), parent.frame(2L))
if (is.call(onsub) && onsub[[1L]] == "eval") { onsub = onsub[[2L]] }
}
if (is.call(onsub) && as.character(onsub[[1L]]) %chin% c("list", ".")) {
spat = paste0("[ ]+(", pat, ")[ ]+")
onsub = lapply(as.list(onsub)[-1L], function(x) gsub(spat, "\\1", deparse(x, width.cutoff=500L)))
onsub = as.call(c(quote(c), onsub))
}
on = eval(onsub, parent.frame(2L), parent.frame(2L))
if (!is.character(on))
stop("'on' argument should be a named atomic vector of column names indicating which columns in 'i' should be joined with which columns in 'x'.")
## extract the operators and potential variable names from 'on'.
## split at backticks to take care about variable names like `col1<=`.
pieces <- strsplit(on, "(?=[`])", perl = TRUE)
xCols <- character(length(on))
## if 'on' is named, the names are the xCols for sure
if(!is.null(names(on))){
xCols <- names(on)
}
iCols <- character(length(on))
operators <- character(length(on))
## loop over the elements and extract operators and column names.
for(i in seq_along(pieces)){
thisCols <- character(0)
thisOperators <- character(0)
j <- 1
while(j <= length(pieces[[i]])){
if(pieces[[i]][j] == "`"){
## start of a variable name with backtick.
thisCols <- c(thisCols, pieces[[i]][j+1])
j <- j+3 # +1 is the column name, +2 is delimiting "`", +3 is next relevant entry.`
} else {
## no backtick
## search for operators
thisOperators <- c(thisOperators,
unlist(regmatches(pieces[[i]][j], gregexpr(pat, pieces[[i]][j])),
use.names = FALSE))
## search for column names
thisCols <- c(thisCols, trimws(strsplit(pieces[[i]][j], pat)[[1]]))
## there can be empty string column names because of trimws, remove them
thisCols <- thisCols[thisCols != ""]
j <- j+1
}
}
if (length(thisOperators) == 0) {
## if no operator is given, it must be ==
operators[i] <- "=="
} else if (length(thisOperators) == 1) {
operators[i] <- thisOperators
} else {
## multiple operators found in one 'on' part. Something is wrong.
stop("Found more than one operator in one 'on' statement: ", on[i], ". Please specify a single operator.")
}
if (length(thisCols) == 2){
## two column names found, first is xCol, second is iCol for sure
xCols[i] <- thisCols[1]
iCols[i] <- thisCols[2]
} else if (length(thisCols) == 1){
## a single column name found. Can mean different things
if(xCols[i] != ""){
## xCol is given by names(on). thisCols must be iCol
iCols[i] <- thisCols[1]
} else if (isnull_inames){
## i has no names. It will be given the names V1, V2, ... automatically.
## The single column name is the x column. It will match to the ith column in i.
xCols[i] <- thisCols[1]
iCols[i] <- paste0("V", i)
} else {
## i has names and one single column name is given by on.
## This means that xCol and iCol have the same name.
xCols[i] <- thisCols[1]
iCols[i] <- thisCols[1]
}
} else if (length(thisCols) == 0){
stop("'on' contains no column name: ", on[i], ". Each 'on' clause must contain one or two column names.")
} else {
stop("'on' contains more than 2 column names: ", on[i], ". Each 'on' clause must contain one or two column names.")
}
}
idx_op = match(operators, ops, nomatch=0L)
if (any(idx_op %in% c(0L, 6L)))
stop("Invalid operators ", paste(operators[idx_op %in% c(0L, 6L)], collapse=","), ". Only allowed operators are ", paste(ops[1:5], collapse=""), ".")
## the final on will contain the xCol as name, the iCol as value
on <- iCols
names(on) <- xCols
return(list(on = on, ops = idx_op))
}
| /data.table.R | no_license | Fahimforhad496/Rdatatable-data.table | R | false | false | 170,862 | r | if (!exists("trimws", "package:base")) {
# trimws was new in R 3.2.0. Backport it for internal data.table use in R 3.1.0
trimws <- function(x) {
mysub <- function(re, x) sub(re, "", x, perl = TRUE)
mysub("[ \t\r\n]+$", mysub("^[ \t\r\n]+", x))
}
}
dim.data.table <- function(x)
{
.Call(Cdim, x)
}
.global <- new.env() # thanks to: http://stackoverflow.com/a/12605694/403310
setPackageName("data.table",.global)
.global$print = ""
.SD = .N = .I = .GRP = .BY = .EACHI = NULL
# These are exported to prevent NOTEs from R CMD check, and checkUsage via compiler.
# But also exporting them makes it clear (to users and other packages) that data.table uses these as symbols.
# And NULL makes it clear (to the R's mask check on loading) that they're variables not functions.
# utils::globalVariables(c(".SD",".N")) was tried as well, but exporting seems better.
# So even though .BY doesn't appear in this file, it should still be NULL here and exported because it's
# defined in SDenv and can be used by users.
is.data.table <- function(x) inherits(x, "data.table")
is.ff <- function(x) inherits(x, "ff") # define this in data.table so that we don't have to require(ff), but if user is using ff we'd like it to work
#NCOL <- function(x) {
# # copied from base, but additionally covers data.table via is.list()
# # because NCOL in base explicitly tests using is.data.frame()
# if (is.list(x) && !is.ff(x)) return(length(x))
# if (is.array(x) && length(dim(x)) > 1L) ncol(x) else as.integer(1L)
#}
#NROW <- function(x) {
# if (is.data.frame(x) || is.data.table(x)) return(nrow(x))
# if (is.list(x) && !is.ff(x)) stop("List is not a data.frame or data.table. Convert first before using NROW") # list may have different length elements, which data.table and data.frame's resolve.
# if (is.array(x)) nrow(x) else length(x)
#}
null.data.table <-function() {
ans = list()
setattr(ans,"class",c("data.table","data.frame"))
setattr(ans,"row.names",.set_row_names(0L))
alloc.col(ans)
}
data.table <-function(..., keep.rownames=FALSE, check.names=FALSE, key=NULL, stringsAsFactors=FALSE)
{
# NOTE: It may be faster in some circumstances to create a data.table by creating a list l first, and then setattr(l,"class",c("data.table","data.frame")) at the expense of checking.
# TO DO: rewrite data.table(), one of the oldest functions here. Many people use data.table() to convert data.frame rather than
# as.data.table which is faster; speed could be better. Revisit how many copies are taken in for example data.table(DT1,DT2) which
# cbind directs to. And the nested loops for recycling lend themselves to being C level.
x <- list(...) # doesn't copy named inputs as from R >= 3.1.0 (a very welcome change)
.Call(CcopyNamedInList,x) # to maintain pre-Rv3.1.0 behaviour, for now. See test 548.2. TODO: revist
# TODO Something strange with NAMED on components of `...` to investigate. Or, just port data.table() to C.
if (length(x) < 1L)
return( null.data.table() )
# fix for #5377 - data.table(null list, data.frame and data.table) should return null data.table. Simple fix: check all scenarios here at the top.
if (identical(x, list(NULL)) || identical(x, list(list())) ||
identical(x, list(data.frame(NULL))) || identical(x, list(data.table(NULL)))) return( null.data.table() )
nd = name_dots(...)
myNCOL = function(x) if (is.null(x)) 0L else NCOL(x) # tmp fix (since NCOL(NULL)==1) until PR#3471 goes ahread in v1.12.4
if (any(nocols<-sapply(x, myNCOL)==0L)) { tt=!nocols; x=x[tt]; nd=lapply(nd,'[',tt); } # data.table(data.table(), data.table(a=integer())), #3445
vnames = nd$vnames
novname = nd$novname # novname used later to know which were explicitly supplied in the call
n <- length(x)
if (length(vnames) != n) stop("logical error in vnames") # nocov
# cast to a list to facilitate naming of columns with dimension --
# unlist() at the end automatically handles the need to "push" names
# to accommodate the "new" columns
vnames <- as.list.default(vnames)
nrows = integer(n) # vector of lengths of each column. may not be equal if silent repetition is required.
numcols = integer(n) # the ncols of each of the inputs (e.g. if inputs contain matrix or data.table)
for (i in seq_len(n)) {
xi = x[[i]]
if (is.null(xi)) stop("Internal error: NULL item ", i," should have been removed from list above") # nocov
if ("POSIXlt" %chin% class(xi)) {
warning("POSIXlt column type detected and converted to POSIXct. We do not recommend use of POSIXlt at all because it uses 40 bytes to store one date. Use as.POSIXct to avoid this warning.")
x[[i]] = as.POSIXct(xi)
} else if (is.matrix(xi) || is.data.frame(xi)) { # including data.table (a data.frame, too)
xi = as.data.table(xi, keep.rownames=keep.rownames) # TO DO: allow a matrix to be a column of a data.table. This could allow a key'd lookup to a matrix, not just by a single rowname vector, but by a combination of several columns. A matrix column could be stored either by row or by column contiguous in memory.
x[[i]] = xi
numcols[i] = length(xi)
} else if (is.table(xi)) {
x[[i]] = xi = as.data.table.table(xi, keep.rownames=keep.rownames)
numcols[i] = length(xi)
} else if (is.function(xi)) {
x[[i]] = xi = list(xi)
}
nrows[i] <- NROW(xi) # for a vector (including list() columns) returns the length
if (numcols[i]>0L) {
namesi <- names(xi) # works for both data.frame's, matrices and data.tables's
if (length(namesi)==0L) namesi = rep.int("",ncol(xi))
namesi[is.na(namesi)] = ""
tt = namesi==""
if (any(tt)) namesi[tt] = paste0("V", which(tt))
if (novname[i]) vnames[[i]] = namesi
else vnames[[i]] = paste(vnames[[i]], namesi, sep=".")
}
}
nr <- max(nrows)
ckey = NULL
recycledkey = FALSE
for (i in seq_len(n)) {
xi = x[[i]]
if (is.data.table(xi) && haskey(xi)) {
if (nrows[i]<nr) recycledkey = TRUE
else ckey = c(ckey, key(xi))
}
}
for (i in which(nrows < nr)) {
# TO DO ... recycle in C, but not high priority as large data already regular from database or file
xi <- x[[i]]
if (identical(xi,list())) {
x[[i]] = vector("list", nr)
next
}
if (nrows[i]==0L) stop("Item ",i," has no length. Provide at least one item (such as NA, NA_integer_ etc) to be repeated to match the ",nr," row", if (nr > 1L) "s", " in the longest column. Or, all columns can be 0 length, for insert()ing rows into.")
# Implementing FR #4813 - recycle with warning when nr %% nrows[i] != 0L
if (nr%%nrows[i] != 0L) warning("Item ", i, " is of size ", nrows[i], " but maximum size is ", nr, " (recycled leaving remainder of ", nr%%nrows[i], " items)")
if (is.data.frame(xi)) { # including data.table
..i = rep(seq_len(nrow(xi)), length.out = nr)
x[[i]] = xi[..i,,drop=FALSE]
next
}
if (is.atomic(xi) || is.list(xi)) {
# TO DO: surely use set() here, or avoid the coercion
x[[i]] = rep(xi, length.out = nr)
next
}
stop("problem recycling column ",i,", try a simpler type")
}
if (any(numcols>0L)) {
value = vector("list",sum(pmax(numcols,1L)))
k = 1L
for(i in seq_len(n)) {
if (is.list(x[[i]]) && !is.ff(x[[i]])) {
for(j in seq_len(length(x[[i]]))) {
value[[k]] = x[[i]][[j]]
k=k+1L
}
} else {
value[[k]] = x[[i]]
k=k+1L
}
}
} else {
value = x
}
vnames <- unlist(vnames)
if (check.names) # default FALSE
vnames <- make.names(vnames, unique = TRUE)
setattr(value,"names",vnames)
setattr(value,"row.names",.set_row_names(nr))
setattr(value,"class",c("data.table","data.frame"))
if (!is.null(key)) {
if (!is.character(key)) stop("key argument of data.table() must be character")
if (length(key)==1L) {
key = strsplit(key,split=",")[[1L]]
# eg key="A,B"; a syntax only useful in key argument to data.table(), really.
}
setkeyv(value,key)
} else {
# retain key of cbind(DT1, DT2, DT3) where DT2 is keyed but not DT1. cbind calls data.table().
# If DT inputs with keys have been recycled then can't retain key
if (length(ckey)
&& !recycledkey
&& !any(duplicated(ckey))
&& all(ckey %chin% names(value))
&& !any(duplicated(names(value)[names(value) %chin% ckey])))
setattr(value, "sorted", ckey)
}
if (isTRUE(stringsAsFactors)) {
for (j in which(vapply(value, is.character, TRUE))) set(value, NULL, j, as_factor(.subset2(value, j)))
# as_factor is internal function in fread.R currently
}
alloc.col(value) # returns a NAMED==0 object, unlike data.frame()
}
replace_dot_alias <- function(e) {
# we don't just simply alias .=list because i) list is a primitive (faster to iterate) and ii) we test for use
# of "list" in several places so it saves having to remember to write "." || "list" in those places
if (is.call(e) && !is.function(e[[1L]])) {
# . alias also used within bquote, #1912
if (e[[1L]] == 'bquote') return(e)
if (e[[1L]] == ".") e[[1L]] = quote(list)
for (i in seq_along(e)[-1L]) if (!is.null(e[[i]])) e[[i]] = replace_dot_alias(e[[i]])
}
e
}
.massagei <- function(x) {
# J alias for list as well in i, just if the first symbol
# if x = substitute(base::order) then as.character(x[[1L]]) == c("::", "base", "order")
if (is.call(x) && as.character(x[[1L]])[[1L]] %chin% c("J","."))
x[[1L]] = quote(list)
x
}
.checkTypos = function(err, ref) {
if (grepl('object.*not found', err$message)) {
used = gsub(".*object '([^']+)'.*", "\\1", err$message)
found = agrep(used, ref, value=TRUE, ignore.case=TRUE, fixed=TRUE)
if (length(found)) {
stop("Object '", used, "' not found. Perhaps you intended ",
paste(head(found, 5L), collapse=", "),
if (length(found)<=5L) "" else paste(" or",length(found)-5L, "more"))
} else {
stop("Object '", used, "' not found amongst ",
paste(head(ref, 5L), collapse=', '),
if (length(ref)<=5L) "" else paste(" and", length(ref)-5L, "more"))
}
} else {
stop(err$message, call.=FALSE)
}
}
"[.data.table" <- function (x, i, j, by, keyby, with=TRUE, nomatch=getOption("datatable.nomatch"), mult="all", roll=FALSE, rollends=if (roll=="nearest") c(TRUE,TRUE) else if (roll>=0) c(FALSE,TRUE) else c(TRUE,FALSE), which=FALSE, .SDcols, verbose=getOption("datatable.verbose"), allow.cartesian=getOption("datatable.allow.cartesian"), drop=NULL, on=NULL)
{
# ..selfcount <<- ..selfcount+1 # in dev, we check no self calls, each of which doubles overhead, or could
# test explicitly if the caller is [.data.table (even stronger test. TO DO.)
# the drop=NULL is to sink drop argument when dispatching to [.data.frame; using '...' stops test 147
if (!cedta()) {
# Fix for #5070 (to do)
Nargs = nargs() - (!missing(drop))
ans = if (Nargs<3L) { `[.data.frame`(x,i) } # drop ignored anyway by DF[i]
else if (missing(drop)) `[.data.frame`(x,i,j)
else `[.data.frame`(x,i,j,drop)
# added is.data.table(ans) check to fix bug #5069
if (!missing(i) & is.data.table(ans)) setkey(ans,NULL) # See test 304
return(ans)
}
.global$print=""
missingby = missing(by) && missing(keyby) # for tests 359 & 590 where passing by=NULL results in data.table not vector
if (!missing(keyby)) {
if (!missing(by)) stop("Provide either by= or keyby= but not both")
if (missing(j)) { warning("Ignoring keyby= because j= is not supplied"); keyby=NULL; }
by=bysub=substitute(keyby)
keyby=TRUE
# Assign to 'by' so that by is no longer missing and we can proceed as if there were one by
} else {
if (!missing(by) && missing(j)) { warning("Ignoring by= because j= is not supplied"); by=NULL; }
by=bysub= if (missing(by)) NULL else substitute(by)
keyby=FALSE
}
bynull = !missingby && is.null(by) #3530
byjoin = !is.null(by) && is.symbol(bysub) && bysub==".EACHI"
if (missing(i) && missing(j)) {
tt_isub = substitute(i)
tt_jsub = substitute(j)
if (!is.null(names(sys.call())) && # not relying on nargs() as it considers DT[,] to have 3 arguments, #3163
tryCatch(!is.symbol(tt_isub), error=function(e)TRUE) && # a symbol that inherits missingness from caller isn't missing for our purpose; test 1974
tryCatch(!is.symbol(tt_jsub), error=function(e)TRUE)) {
warning("i and j are both missing so ignoring the other arguments. This warning will be upgraded to error in future.")
}
return(x)
}
if (!mult %chin% c("first","last","all")) stop("mult argument can only be 'first','last' or 'all'")
missingroll = missing(roll)
if (length(roll)!=1L || is.na(roll)) stop("roll must be a single TRUE, FALSE, positive/negative integer/double including +Inf and -Inf or 'nearest'")
if (is.character(roll)) {
if (roll!="nearest") stop("roll is '",roll,"' (type character). Only valid character value is 'nearest'.")
} else {
roll = if (isTRUE(roll)) +Inf else as.double(roll)
}
force(rollends)
if (!is.logical(rollends)) stop("rollends must be a logical vector")
if (length(rollends)>2L) stop("rollends must be length 1 or 2")
if (length(rollends)==1L) rollends=rep.int(rollends,2L)
# TO DO (document/faq/example). Removed for now ... if ((roll || rolltolast) && missing(mult)) mult="last" # for when there is exact match to mult. This does not control cases where the roll is mult, that is always the last one.
missingnomatch = missing(nomatch)
if (is.null(nomatch)) nomatch = 0L # allow nomatch=NULL API already now, part of: https://github.com/Rdatatable/data.table/issues/857
if (!is.na(nomatch) && nomatch!=0L) stop("nomatch= must be either NA or NULL (or 0 for backwards compatibility which is the same as NULL)")
nomatch = as.integer(nomatch)
if (!is.logical(which) || length(which)>1L) stop("which= must be a logical vector length 1. Either FALSE, TRUE or NA.")
if ((isTRUE(which)||is.na(which)) && !missing(j)) stop("which==",which," (meaning return row numbers) but j is also supplied. Either you need row numbers or the result of j, but only one type of result can be returned.")
if (!is.na(nomatch) && is.na(which)) stop("which=NA with nomatch=0 would always return an empty vector. Please change or remove either which or nomatch.")
if (!with && missing(j)) stop("j must be provided when with=FALSE")
if (missing(i) && !missing(on)) warning("ignoring on= because it is only relevant to i but i is not provided")
irows = NULL # Meaning all rows. We avoid creating 1:nrow(x) for efficiency.
notjoin = FALSE
rightcols = leftcols = integer()
optimizedSubset = FALSE ## flag: tells whether a normal query was optimized into a join.
..syms = NULL
av = NULL
jsub = NULL
if (!missing(j)) {
jsub = replace_dot_alias(substitute(j))
root = if (is.call(jsub)) as.character(jsub[[1L]])[1L] else ""
if (root == ":" ||
(root %chin% c("-","!") && is.call(jsub[[2L]]) && jsub[[2L]][[1L]]=="(" && is.call(jsub[[2L]][[2L]]) && jsub[[2L]][[2L]][[1L]]==":") ||
( (!length(av<-all.vars(jsub)) || all(substring(av,1L,2L)=="..")) &&
root %chin% c("","c","paste","paste0","-","!") &&
missingby )) { # test 763. TODO: likely that !missingby iff with==TRUE (so, with can be removed)
# When no variable names (i.e. symbols) occur in j, scope doesn't matter because there are no symbols to find.
# If variable names do occur, but they are all prefixed with .., then that means look up in calling scope.
# Automatically set with=FALSE in this case so that DT[,1], DT[,2:3], DT[,"someCol"] and DT[,c("colB","colD")]
# work as expected. As before, a vector will never be returned, but a single column data.table
# for type consistency with >1 cases. To return a single vector use DT[["someCol"]] or DT[[3]].
# The root==":" is to allow DT[,colC:colH] even though that contains two variable names.
# root == "-" or "!" is for tests 1504.11 and 1504.13 (a : with a ! or - modifier root)
# We don't want to evaluate j at all in making this decision because i) evaluating could itself
# increment some variable and not intended to be evaluated a 2nd time later on and ii) we don't
# want decisions like this to depend on the data or vector lengths since that can introduce
# inconistency reminiscent of drop=TRUE in [.data.frame that we seek to avoid.
with=FALSE
if (length(av)) {
for (..name in av) {
name = substring(..name, 3L)
if (name=="") stop("The symbol .. is invalid. The .. prefix must be followed by at least one character.")
if (!exists(name, where=parent.frame())) {
stop("Variable '",name,"' is not found in calling scope. Looking in calling scope because you used the .. prefix.",
if (exists(..name, where=parent.frame()))
paste0(" Variable '..",name,"' does exist in calling scope though, so please just removed the .. prefix from that variable name in calling scope.")
# We have recommended 'manual' .. prefix in the past, so try to be helpful
else
""
)
} else if (exists(..name, where=parent.frame())) {
warning("Both '",name,"' and '..", name, "' exist in calling scope. Please remove the '..", name,"' variable in calling scope for clarity.")
}
}
..syms = av
}
} else if (is.name(jsub)) {
if (substring(jsub, 1L, 2L) == "..") stop("Internal error: DT[, ..var] should be dealt with by the branch above now.") # nocov
if (!with && !exists(as.character(jsub), where=parent.frame()))
stop("Variable '",jsub,"' is not found in calling scope. Looking in calling scope because you set with=FALSE. Also, please use .. symbol prefix and remove with=FALSE.")
}
if (root=="{") {
if (length(jsub) == 2L) {
jsub = jsub[[2L]] # to allow {} wrapping of := e.g. [,{`:=`(...)},] [#376]
root = if (is.call(jsub)) as.character(jsub[[1L]])[1L] else ""
} else if (length(jsub) > 2L && is.call(jsub[[2L]]) && jsub[[2L]][[1L]] == ":=") {
#2142 -- j can be {} and have length 1
stop("You have wrapped := with {} which is ok but then := must be the only thing inside {}. You have something else inside {} as well. Consider placing the {} on the RHS of := instead; e.g. DT[,someCol:={tmpVar1<-...;tmpVar2<-...;tmpVar1*tmpVar2}")
}
}
if (root=="eval" && !any(all.vars(jsub[[2L]]) %chin% names(x))) {
# TODO: this && !any depends on data. Can we remove it?
# Grab the dynamic expression from calling scope now to give the optimizer a chance to optimize it
# Only when top level is eval call. Not nested like x:=eval(...) or `:=`(x=eval(...), y=eval(...))
jsub = eval(jsub[[2L]], parent.frame(), parent.frame()) # this evals the symbol to return the dynamic expression
if (is.expression(jsub)) jsub = jsub[[1L]] # if expression, convert it to call
# Note that the dynamic expression could now be := (new in v1.9.7)
root = if (is.call(jsub)) {
jsub = replace_dot_alias(jsub)
as.character(jsub[[1L]])[1L]
} else ""
}
if (root == ":=") {
allow.cartesian=TRUE # (see #800)
if (!missing(i) && keyby)
stop(":= with keyby is only possible when i is not supplied since you can't setkey on a subset of rows. Either change keyby to by or remove i")
if (!missingnomatch) {
warning("nomatch isn't relevant together with :=, ignoring nomatch")
nomatch=0L
}
}
}
# setdiff removes duplicate entries, which'll create issues with duplicated names. Use %chin% instead.
dupdiff <- function(x, y) x[!x %chin% y]
if (!missing(i)) {
xo = NULL
isub = substitute(i)
if (identical(isub, NA)) {
# only possibility *isub* can be NA (logical) is the symbol NA itself; i.e. DT[NA]
# replace NA in this case with NA_integer_ as that's almost surely what user intended to
# return a single row with NA in all columns. (DT[0] returns an empty table, with correct types.)
# Any expression (including length 1 vectors) that evaluates to a single NA logical will
# however be left as NA logical since that's important for consistency to return empty in that
# case; e.g. DT[Col==3] where DT is 1 row and Col contains NA.
# Replacing the NA symbol makes DT[NA] and DT[c(1,NA)] consistent and provides
# an easy way to achieve a single row of NA as users expect rather than requiring them
# to know and change to DT[NA_integer_].
isub=NA_integer_
}
isnull_inames = FALSE
nqgrp = integer(0L) # for non-equi join
nqmaxgrp = 1L # for non-equi join
# Fixes 4994: a case where quoted expression with a "!", ex: expr = quote(!dt1); dt[eval(expr)] requires
# the "eval" to be checked before `as.name("!")`. Therefore interchanged.
restore.N = remove.N = FALSE
if (exists(".N", envir=parent.frame(), inherits=FALSE)) {
old.N = get(".N", envir=parent.frame(), inherits=FALSE)
locked.N = bindingIsLocked(".N", parent.frame())
if (locked.N) eval(call("unlockBinding", ".N", parent.frame())) # eval call to pass R CMD check NOTE until we find cleaner way
assign(".N", nrow(x), envir=parent.frame(), inherits=FALSE)
restore.N = TRUE
# the comment below is invalid hereafter (due to fix for #1145)
# binding locked when .SD[.N] but that's ok as that's the .N we want anyway
# TO DO: change isub at C level s/.N/nrow(x); changing a symbol to a constant should be ok
} else {
assign(".N", nrow(x), envir=parent.frame(), inherits=FALSE)
remove.N = TRUE
}
if (is.call(isub) && isub[[1L]]=="eval") { # TO DO: or ..()
isub = eval(.massagei(isub[[2L]]), parent.frame(), parent.frame())
if (is.expression(isub)) isub=isub[[1L]]
}
if (is.call(isub) && isub[[1L]] == as.name("!")) {
notjoin = TRUE
if (!missingnomatch) stop("not-join '!' prefix is present on i but nomatch is provided. Please remove nomatch.");
nomatch = 0L
isub = isub[[2L]]
# #932 related so that !(v1 == 1) becomes v1 == 1 instead of (v1 == 1) after removing "!"
if (is.call(isub) && isub[[1L]] == "(" && !is.name(isub[[2L]]))
isub = isub[[2L]]
}
if (is.call(isub) && isub[[1L]] == as.name("order") && getOption("datatable.optimize") >= 1) { # optimize here so that we can switch it off if needed
if (verbose) cat("order optimisation is on, i changed from 'order(...)' to 'forder(DT, ...)'.\n")
isub = as.list(isub)
isub = as.call(c(list(quote(forder), quote(x)), isub[-1L]))
}
if (is.null(isub)) return( null.data.table() )
if (is.call(isub) && isub[[1L]] == quote(forder)) {
order_env = new.env(parent=parent.frame()) # until 'forder' is exported
assign("forder", forder, order_env)
assign("x", x, order_env)
i = eval(isub, order_env, parent.frame()) # for optimisation of 'order' to 'forder'
# that forder returns empty integer() is taken care of internally within forder
} else if (length(o <- .prepareFastSubset(isub = isub, x = x,
enclos = parent.frame(),
notjoin = notjoin, verbose = verbose))){
## redirect to the is.data.table(x) == TRUE branch.
## Additional flag to adapt things after bmerge:
optimizedSubset <- TRUE
notjoin <- o$notjoin
i <- o$i
on <- o$on
## the following two are ignored if i is not a data.table.
## Since we are converting i to data.table, it is important to set them properly.
nomatch <- 0L
mult <- "all"
}
else if (!is.name(isub)) {
i = tryCatch(eval(.massagei(isub), x, parent.frame()),
error = function(e) .checkTypos(e, names(x)))
} else {
# isub is a single symbol name such as B in DT[B]
i = try(eval(isub, parent.frame(), parent.frame()), silent=TRUE)
if (inherits(i,"try-error")) {
# must be "not found" since isub is a mere symbol
col = try(eval(isub, x), silent=TRUE) # is it a column name?
if (identical(typeof(col),"logical"))
stop(as.character(isub)," is not found in calling scope but it is a column of type logical. If you wish to select rows where that column is TRUE, either wrap the symbol with '()' or use ==TRUE to be clearest to readers of your code.")
else
stop(as.character(isub)," is not found in calling scope and it is not a column of type logical. When the first argument inside DT[...] is a single symbol, data.table looks for it in calling scope.")
}
}
if (restore.N) {
assign(".N", old.N, envir=parent.frame())
if (locked.N) lockBinding(".N", parent.frame())
}
if (remove.N) rm(list=".N", envir=parent.frame())
if (is.matrix(i)) {
if (is.numeric(i) && ncol(i)==1L) { # #826 - subset DT on single integer vector stored as matrix
i = as.integer(i)
} else {
stop("i is invalid type (matrix). Perhaps in future a 2 column matrix could return a list of elements of DT (in the spirit of A[B] in FAQ 2.14). Please report to data.table issue tracker if you'd like this, or add your comments to FR #657.")
}
}
if (is.logical(i)) {
if (notjoin) {
notjoin = FALSE
i = !i
}
}
if (is.null(i)) return( null.data.table() )
if (is.character(i)) {
isnull_inames = TRUE
i = data.table(V1=i) # for user convenience; e.g. DT["foo"] without needing DT[.("foo")]
} else if (identical(class(i),"list") && length(i)==1L && is.data.frame(i[[1L]])) { i = as.data.table(i[[1L]]) }
else if (identical(class(i),"data.frame")) { i = as.data.table(i) } # TO DO: avoid these as.data.table() and use a flag instead
else if (identical(class(i),"list")) {
isnull_inames = is.null(names(i))
i = as.data.table(i)
}
if (is.data.table(i)) {
if (!haskey(x) && missing(on) && is.null(xo)) {
stop("When i is a data.table (or character vector), the columns to join by must be specified either using 'on=' argument (see ?data.table) or by keying x (i.e. sorted, and, marked as sorted, see ?setkey). Keyed joins might have further speed benefits on very large data due to x being sorted in RAM.")
}
if (!missing(on)) {
# on = .() is now possible, #1257
on_ops = .parse_on(substitute(on), isnull_inames)
on = on_ops[[1L]]
ops = on_ops[[2L]]
# TODO: collect all '==' ops first to speeden up Cnestedid
rightcols = chmatch(names(on), names(x))
if (length(nacols <- which(is.na(rightcols))))
stop("Column(s) [", paste(names(on)[nacols], collapse=","), "] not found in x")
leftcols = chmatch(unname(on), names(i))
if (length(nacols <- which(is.na(leftcols))))
stop("Column(s) [", paste(unname(on)[nacols], collapse=","), "] not found in i")
# figure out the columns on which to compute groups on
non_equi = which.first(ops != 1L) # 1 is "==" operator
if (!is.na(non_equi)) {
# non-equi operators present.. investigate groups..
if (verbose) cat("Non-equi join operators detected ... \n")
if (!missingroll) stop("roll is not implemented for non-equi joins yet.")
if (verbose) {last.started.at=proc.time();cat(" forder took ... ");flush.console()}
# TODO: could check/reuse secondary indices, but we need 'starts' attribute as well!
xo = forderv(x, rightcols, retGrp=TRUE)
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
xg = attr(xo, 'starts')
resetcols = head(rightcols, non_equi-1L)
if (length(resetcols)) {
# TODO: can we get around having to reorder twice here?
# or at least reuse previous order?
if (verbose) {last.started.at=proc.time();cat(" Generating group lengths ... ");flush.console()}
resetlen = attr(forderv(x, resetcols, retGrp=TRUE), 'starts')
resetlen = .Call(Cuniqlengths, resetlen, nrow(x))
if (verbose) {cat("done in",timetaken(last.started.at),"\n"); flush.console()}
} else resetlen = integer(0L)
if (verbose) {last.started.at=proc.time();cat(" Generating non-equi group ids ... ");flush.console()}
nqgrp = .Call(Cnestedid, x, rightcols[non_equi:length(rightcols)], xo, xg, resetlen, mult)
if (verbose) {cat("done in",timetaken(last.started.at),"\n"); flush.console()}
if (length(nqgrp)) nqmaxgrp = max(nqgrp) # fix for #1986, when 'x' is 0-row table max(.) returns -Inf.
if (nqmaxgrp > 1L) { # got some non-equi join work to do
if ("_nqgrp_" %chin% names(x)) stop("Column name '_nqgrp_' is reserved for non-equi joins.")
if (verbose) {last.started.at=proc.time();cat(" Recomputing forder with non-equi ids ... ");flush.console()}
set(nqx<-shallow(x), j="_nqgrp_", value=nqgrp)
xo = forderv(nqx, c(ncol(nqx), rightcols))
if (verbose) {cat("done in",timetaken(last.started.at),"\n"); flush.console()}
} else nqgrp = integer(0L)
if (verbose) cat(" Found", nqmaxgrp, "non-equi group(s) ...\n")
}
if (is.na(non_equi)) {
# equi join. use existing key (#1825) or existing secondary index (#1439)
if ( identical(head(key(x), length(on)), names(on)) ) {
xo = integer(0L)
if (verbose) cat("on= matches existing key, using key\n")
} else {
if (isTRUE(getOption("datatable.use.index"))) {
xo = getindex(x, names(on))
if (verbose && !is.null(xo)) cat("on= matches existing index, using index\n")
}
if (is.null(xo)) {
if (verbose) {last.started.at=proc.time(); flush.console()}
xo = forderv(x, by = rightcols)
if (verbose) {cat("Calculated ad hoc index in",timetaken(last.started.at),"\n"); flush.console()}
# TODO: use setindex() instead, so it's cached for future reuse
}
}
}
} else if (is.null(xo)) {
rightcols = chmatch(key(x),names(x)) # NAs here (i.e. invalid data.table) checked in bmerge()
leftcols = if (haskey(i))
chmatch(head(key(i),length(rightcols)),names(i))
else
seq_len(min(length(i),length(rightcols)))
rightcols = head(rightcols,length(leftcols))
xo = integer(0L) ## signifies 1:.N
ops = rep(1L, length(leftcols))
}
# Implementation for not-join along with by=.EACHI, #604
if (notjoin && (byjoin || mult != "all")) { # mult != "all" needed for #1571 fix
notjoin = FALSE
if (verbose) {last.started.at=proc.time();cat("not-join called with 'by=.EACHI'; Replacing !i with i=setdiff_(x,i) ...");flush.console()}
orignames = copy(names(i))
i = setdiff_(x, i, rightcols, leftcols) # part of #547
if (verbose) {cat("done in",timetaken(last.started.at),"\n"); flush.console()}
setnames(i, orignames[leftcols])
setattr(i, 'sorted', names(i)) # since 'x' has key set, this'll always be sorted
}
i = .shallow(i, retain.key = TRUE)
ans = bmerge(i, x, leftcols, rightcols, xo, roll, rollends, nomatch, mult, ops, nqgrp, nqmaxgrp, verbose=verbose)
# temp fix for issue spotted by Jan, test #1653.1. TODO: avoid this
# 'setorder', as there's another 'setorder' in generating 'irows' below...
if (length(ans$indices)) setorder(setDT(ans[1L:3L]), indices)
allLen1 = ans$allLen1
f__ = ans$starts
len__ = ans$lens
allGrp1 = FALSE # was previously 'ans$allGrp1'. Fixing #1991. TODO: Revisit about allGrp1 possibility for speedups in certain cases when I find some time.
indices__ = if (length(ans$indices)) ans$indices else seq_along(f__) # also for #1991 fix
# length of input nomatch (single 0 or NA) is 1 in both cases.
# When no match, len__ is 0 for nomatch=0 and 1 for nomatch=NA, so len__ isn't .N
# If using secondary key of x, f__ will refer to xo
if (is.na(which)) {
w = if (notjoin) f__!=0L else is.na(f__)
return( if (length(xo)) fsort(xo[w], internal=TRUE) else which(w) )
}
if (mult=="all") {
# is by=.EACHI along with non-equi join?
nqbyjoin = byjoin && length(ans$indices) && !allGrp1
if (!byjoin || nqbyjoin) {
# Really, `anyDuplicated` in base is AWESOME!
# allow.cartesian shouldn't error if a) not-join, b) 'i' has no duplicates
if (verbose) {last.started.at=proc.time();cat("Constructing irows for '!byjoin || nqbyjoin' ... ");flush.console()}
irows = if (allLen1) f__ else vecseq(f__,len__,
if (allow.cartesian ||
notjoin || # #698. When notjoin=TRUE, ignore allow.cartesian. Rows in answer will never be > nrow(x).
!anyDuplicated(f__, incomparables = c(0L, NA_integer_))) {
NULL # #742. If 'i' has no duplicates, ignore
} else as.double(nrow(x)+nrow(i))) # rows in i might not match to x so old max(nrow(x),nrow(i)) wasn't enough. But this limit now only applies when there are duplicates present so the reason now for nrow(x)+nrow(i) is just to nail it down and be bigger than max(nrow(x),nrow(i)).
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
# Fix for #1092 and #1074
# TODO: implement better version of "any"/"all"/"which" to avoid
# unnecessary construction of logical vectors
if (identical(nomatch, 0L) && allLen1) irows = irows[irows != 0L]
} else {
if (length(xo) && missing(on))
stop("Internal error. Cannot by=.EACHI when joining to a secondary key, yet") # nocov
# since f__ refers to xo later in grouping, so xo needs to be passed through to dogroups too.
if (length(irows))
stop("Internal error. irows has length in by=.EACHI") # nocov
}
if (nqbyjoin) {
irows = if (length(xo)) xo[irows] else irows
xo = setorder(setDT(list(indices=rep.int(indices__, len__), irows=irows)))[["irows"]]
ans = .Call(CnqRecreateIndices, xo, len__, indices__, max(indices__))
f__ = ans[[1L]]; len__ = ans[[2L]]
allLen1 = FALSE # TODO; should this always be FALSE?
irows = NULL # important to reset
if (any_na(as_list(xo))) xo = xo[!is.na(xo)]
}
} else {
# turning on mult = "first"/"last" for non-equi joins again to test..
# if (nqmaxgrp>1L) stop("Non-equi joins aren't yet functional with mult='first' and mult='last'.")
# mult="first"/"last" logic moved to bmerge.c, also handles non-equi cases, #1452
if (!byjoin) { #1287 and #1271
irows = f__ # len__ is set to 1 as well, no need for 'pmin' logic
if (identical(nomatch,0L)) irows = irows[len__>0L] # 0s are len 0, so this removes -1 irows
}
# TODO: when nomatch=NA, len__ need not be allocated / set at all for mult="first"/"last"?
# TODO: how about when nomatch=0L, can we avoid allocating then as well?
}
if (length(xo) && length(irows)) {
irows = xo[irows] # TO DO: fsort here?
if (mult=="all" && !allGrp1) { # following #1991 fix, !allGrp1 will always be TRUE. TODO: revisit.
if (verbose) {last.started.at=proc.time();cat("Reorder irows for 'mult==\"all\" && !allGrp1' ... ");flush.console()}
irows = setorder(setDT(list(indices=rep.int(indices__, len__), irows=irows)))[["irows"]]
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
}
}
if (optimizedSubset){
## special treatment for calls like DT[x == 3] that are transformed into DT[J(x=3), on = "x==x"]
if(!.Call(CisOrderedSubset, irows, nrow(x))){
## restore original order. This is a very expensive operation.
## benchmarks have shown that starting with 1e6 irows, a tweak can significantly reduce time
## (see #2366)
if (verbose) {last.started.at=proc.time()[3];cat("Reordering", length(irows), "rows after bmerge done in ... ");flush.console()}
if(length(irows) < 1e6){
irows = fsort(irows, internal=TRUE) ## internally, fsort on integer falls back to forderv
} else {
irows = as.integer(fsort(as.numeric(irows))) ## nocov; parallelized for numeric, but overhead of type conversion
}
if (verbose) {cat(round(proc.time()[3]-last.started.at,3),"secs\n");flush.console()}
}
## make sure, all columns are taken from x and not from i.
## This is done by simply telling data.table to continue as if there was a simple subset
leftcols = integer(0L)
rightcols = integer(0L)
i <- irows ## important to make i not a data.table because otherwise Gforce doesn't kick in
}
}
else {
if (!missing(on)) {
stop("logical error. i is not a data.table, but 'on' argument is provided.")
}
# TO DO: TODO: Incorporate which_ here on DT[!i] where i is logical. Should avoid i = !i (above) - inefficient.
# i is not a data.table
if (!is.logical(i) && !is.numeric(i)) stop("i has not evaluated to logical, integer or double")
if (is.logical(i)) {
if (length(i)==1L # to avoid unname copy when length(i)==nrow (normal case we don't want to slow down)
&& isTRUE(unname(i))) { irows=i=NULL } # unname() for #2152 - length 1 named logical vector.
# NULL is efficient signal to avoid creating 1:nrow(x) but still return all rows, fixes #1249
else if (length(i)<=1L) { irows=i=integer(0L) }
# FALSE, NA and empty. All should return empty data.table. The NA here will be result of expression,
# where for consistency of edge case #1252 all NA to be removed. If NA is a single NA symbol, it
# was auto converted to NA_integer_ higher up for ease of use and convenience. We definitely
# don't want base R behaviour where DF[NA,] returns an entire copy filled with NA everywhere.
else if (length(i)==nrow(x)) { irows=i=which(i) }
# The which() here auto removes NA for convenience so user doesn't need to remember "!is.na() & ..."
# Also this which() is for consistenty of DT[colA>3,which=TRUE] and which(DT[,colA>3])
# Assigning to 'i' here as well to save memory, #926.
else stop("i evaluates to a logical vector length ", length(i), " but there are ", nrow(x), " rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle.")
} else {
irows = as.integer(i) # e.g. DT[c(1,3)] and DT[c(-1,-3)] ok but not DT[c(1,-3)] (caught as error)
irows = .Call(CconvertNegAndZeroIdx, irows, nrow(x), is.null(jsub) || root!=":=") # last argument is allowOverMax (NA when selecting, error when assigning)
# simplifies logic from here on: can assume positive subscripts (no zeros)
# maintains Arun's fix for #2697 (test 1042)
# efficient in C with more detailed helpful messages when user mixes positives and negatives
# falls through quickly (no R level allocs) if all items are within range [1,max] with no zeros or negatives
# minor TO DO: can we merge this with check_idx in fcast.c/subset ?
}
}
if (notjoin) {
if (byjoin || !is.integer(irows) || is.na(nomatch)) stop("Internal error: notjoin but byjoin or !integer or nomatch==NA") # nocov
irows = irows[irows!=0L]
if (verbose) {last.started.at=proc.time()[3];cat("Inverting irows for notjoin done in ... ");flush.console()}
i = irows = if (length(irows)) seq_len(nrow(x))[-irows] else NULL # NULL meaning all rows i.e. seq_len(nrow(x))
if (verbose) cat(round(proc.time()[3]-last.started.at, 3), "sec\n")
leftcols = integer() # proceed as if row subset from now on, length(leftcols) is switched on later
rightcols = integer()
# Doing this once here, helps speed later when repeatedly subsetting each column. R's [irows] would do this for each
# column when irows contains negatives.
}
if (which) return( if (is.null(irows)) seq_len(nrow(x)) else irows )
} else { # missing(i)
i = NULL
}
byval = NULL
xnrow = nrow(x)
xcols = xcolsAns = icols = icolsAns = integer()
xdotcols = FALSE
othervars = character(0L)
if (missing(j)) {
# missingby was already checked above before dealing with i
if (!length(x)) return(null.data.table())
if (!length(leftcols)) {
# basic x[i] subset, #2951
if (is.null(irows)) return(shallow(x)) # e.g. DT[TRUE] (#3214); otherwise CsubsetDT would materialize a deep copy
else return(.Call(CsubsetDT, x, irows, seq_along(x)) )
} else {
jisvars = names(i)[-leftcols]
tt = jisvars %chin% names(x)
if (length(tt)) jisvars[tt] = paste0("i.",jisvars[tt])
if (length(duprightcols <- rightcols[duplicated(rightcols)])) {
nx = c(names(x), names(x)[duprightcols])
rightcols = chmatchdup(names(x)[rightcols], nx)
nx = make.unique(nx)
} else nx = names(x)
ansvars = make.unique(c(nx, jisvars))
icols = c(leftcols, seq_along(i)[-leftcols])
icolsAns = c(rightcols, seq.int(length(nx)+1L, length.out=ncol(i)-length(unique(leftcols))))
xcols = xcolsAns = seq_along(x)[-rightcols]
}
ansvals = chmatch(ansvars, nx)
}
else {
if (is.data.table(i)) {
idotprefix = paste0("i.", names(i))
xdotprefix = paste0("x.", names(x))
} else idotprefix = xdotprefix = character(0L)
# j was substituted before dealing with i so that := can set allow.cartesian=FALSE (#800) (used above in i logic)
if (is.null(jsub)) return(NULL)
if (!with && is.call(jsub) && jsub[[1L]]==":=") {
# TODO: make these both errors (or single long error in both cases) in next release.
# i.e. using with=FALSE together with := at all will become an error. Eventually with will be removed.
if (is.null(names(jsub)) && is.name(jsub[[2L]])) {
warning("with=FALSE together with := was deprecated in v1.9.4 released Oct 2014. Please wrap the LHS of := with parentheses; e.g., DT[,(myVar):=sum(b),by=a] to assign to column name(s) held in variable myVar. See ?':=' for other examples. As warned in 2014, this is now a warning.")
jsub[[2L]] = eval(jsub[[2L]], parent.frame(), parent.frame())
} else {
warning("with=FALSE ignored, it isn't needed when using :=. See ?':=' for examples.")
}
with = TRUE
}
if (!with) {
# missingby was already checked above before dealing with i
if (is.call(jsub) && deparse(jsub[[1L]], 500L, backtick=FALSE) %chin% c("!", "-")) { # TODO is deparse avoidable here?
notj = TRUE
jsub = jsub[[2L]]
} else notj = FALSE
# fix for #1216, make sure the paranthesis are peeled from expr of the form (((1:4)))
while (is.call(jsub) && jsub[[1L]] == "(") jsub = as.list(jsub)[[-1L]]
if (is.call(jsub) && length(jsub) == 3L && jsub[[1L]] == ":") {
j = eval(jsub, setattr(as.list(seq_along(x)), 'names', names(x)), parent.frame()) # else j will be evaluated for the first time on next line
} else {
names(..syms) = ..syms
j = eval(jsub, lapply(substring(..syms,3L), get, pos=parent.frame()), parent.frame())
}
if (is.logical(j)) j <- which(j)
if (!length(j)) return( null.data.table() )
if (is.factor(j)) j = as.character(j) # fix for FR: #4867
if (is.character(j)) {
if (notj) {
w = chmatch(j, names(x))
if (anyNA(w)) warning("column(s) not removed because not found: ",paste(j[is.na(w)],collapse=","))
# all duplicates of the name in names(x) must be removed; e.g. data.table(x=1, y=2, x=3)[, !"x"] should just output 'y'.
w = !names(x) %chin% j
ansvars = names(x)[w]
ansvals = which(w)
} else {
# if DT[, c("x","x")] and "x" is duplicated in names(DT), we still subset only the first. Because dups are unusual and
# it's more common to select the same column a few times. A syntax would be needed to distinguish these intents.
ansvars = j # x. and i. prefixes may be in here, they'll result in NA and will be dealt with further below if length(leftcols)
ansvals = chmatch(ansvars, names(x)) # not chmatchdup()
}
if (!length(ansvals)) return(null.data.table())
if (!length(leftcols)) {
if (!anyNA(ansvals)) return(.Call(CsubsetDT, x, irows, ansvals))
else stop("column(s) not found: ", paste(ansvars[is.na(ansvals)],collapse=", "))
}
# else the NA in ansvals are for join inherited scope (test 1973), and NA could be in irows from join and data in i should be returned (test 1977)
# in both cases leave to the R-level subsetting of i and x together further below
} else if (is.numeric(j)) {
j = as.integer(j)
if (any(w<-(j>ncol(x)))) stop("Item ",which.first(w)," of j is ",j[which.first(w)]," which is outside the column number range [1,ncol=", ncol(x),"]")
j = j[j!=0L]
if (any(j<0L)) {
if (any(j>0L)) stop("j mixes positives and negatives")
j = seq_along(x)[j] # all j are <0 here
}
if (notj && length(j)) j = seq_along(x)[-j]
if (!length(j)) return(null.data.table())
return(.Call(CsubsetDT, x, irows, j))
} else {
stop("When with=FALSE, j-argument should be of type logical/character/integer indicating the columns to select.") # fix for #1440.
}
} else { # with=TRUE and byjoin could be TRUE
bynames = NULL
allbyvars = NULL
if (byjoin) {
bynames = names(x)[rightcols]
} else if (!missingby) {
# deal with by before j because we need byvars when j contains .SD
# may evaluate to NULL | character() | "" | list(), likely a result of a user expression where no-grouping is one case being loop'd through
bysubl = as.list.default(bysub)
bysuborig = bysub
if (is.name(bysub) && !(as.character(bysub) %chin% names(x))) { # TO DO: names(x),names(i),and i. and x. prefixes
bysub = eval(bysub, parent.frame(), parent.frame())
# fix for # 5106 - http://stackoverflow.com/questions/19983423/why-by-on-a-vector-not-from-a-data-table-column-is-very-slow
# case where by=y where y is not a column name, and not a call/symbol/expression, but an atomic vector outside of DT.
# note that if y is a list, this'll return an error (not sure if it should).
if (is.atomic(bysub)) bysubl = list(bysuborig) else bysubl = as.list.default(bysub)
}
if (length(bysubl) && identical(bysubl[[1L]],quote(eval))) { # TO DO: or by=..()
bysub = eval(bysubl[[2L]], parent.frame(), parent.frame())
bysub = replace_dot_alias(bysub) # fix for #1298
if (is.expression(bysub)) bysub=bysub[[1L]]
bysubl = as.list.default(bysub)
} else if (is.call(bysub) && as.character(bysub[[1L]]) %chin% c("c","key","names", "intersect", "setdiff")) {
# catch common cases, so we don't have to copy x[irows] for all columns
# *** TO DO ***: try() this eval first (as long as not list() or .()) and see if it evaluates to column names
# to avoid the explicit c,key,names which already misses paste("V",1:10) for example
# tried before but since not wrapped in try() it failed on some tests
# or look for column names used in this by (since if none it wouldn't find column names anyway
# when evaled within full x[irows]). Trouble is that colA%%2L is a call and should be within frame.
tt = eval(bysub, parent.frame(), parent.frame())
if (!is.character(tt)) stop("by=c(...), key(...) or names(...) must evaluate to 'character'")
bysub=tt
} else if (is.call(bysub) && !as.character(bysub[[1L]]) %chin% c("list", "as.list", "{", ".", ":")) {
# potential use of function, ex: by=month(date). catch it and wrap with "(", because we need to set "bysameorder" to FALSE as we don't know if the function will return ordered results just because "date" is ordered. Fixes #2670.
bysub = as.call(c(as.name('('), list(bysub)))
bysubl = as.list.default(bysub)
} else if (is.call(bysub) && bysub[[1L]] == ".") bysub[[1L]] = quote(list)
if (mode(bysub) == "character") {
if (length(grep(",", bysub, fixed = TRUE))) {
if (length(bysub)>1L) stop("'by' is a character vector length ",length(bysub)," but one or more items include a comma. Either pass a vector of column names (which can contain spaces, but no commas), or pass a vector length 1 containing comma separated column names. See ?data.table for other possibilities.")
bysub = strsplit(bysub,split=",")[[1L]]
}
backtick_idx = grep("^[^`]+$",bysub)
if (length(backtick_idx)) bysub[backtick_idx] = paste0("`",bysub[backtick_idx],"`")
backslash_idx = grep("\\", bysub, fixed = TRUE)
if (length(backslash_idx)) bysub[backslash_idx] = gsub('\\', '\\\\', bysub[backslash_idx], fixed = TRUE)
bysub = parse(text=paste0("list(",paste(bysub,collapse=","),")"))[[1L]]
bysubl = as.list.default(bysub)
}
allbyvars = intersect(all.vars(bysub),names(x))
orderedirows = .Call(CisOrderedSubset, irows, nrow(x)) # TRUE when irows is NULL (i.e. no i clause). Similar but better than is.sorted(f__)
bysameorder = byindex = FALSE
if (all(vapply_1b(bysubl, is.name))) {
bysameorder = orderedirows && haskey(x) && length(allbyvars) && identical(allbyvars,head(key(x),length(allbyvars)))
# either bysameorder or byindex can be true but not both. TODO: better name for bysameorder might be bykeyx
if (!bysameorder && keyby && !length(irows) && isTRUE(getOption("datatable.use.index"))) {
# TODO: could be allowed if length(irows)>1 but then the index would need to be squashed for use by uniqlist, #3062
# find if allbyvars is leading subset of any of the indices; add a trailing "__" to fix #3498 where a longer column name starts with a shorter column name
tt = paste0(c(allbyvars,""), collapse="__")
w = which.first(substring(paste0(indices(x),"__"),1L,nchar(tt)) == tt)
if (!is.na(w)) {
byindex = indices(x)[w]
if (!length(getindex(x, byindex))) {
if (verbose) cat("by index '", byindex, "' but that index has 0 length. Ignoring.\n", sep="")
byindex=FALSE
}
}
}
}
if (is.null(irows)) {
if (is.call(bysub) && length(bysub) == 3L && bysub[[1L]] == ":" && is.name(bysub[[2L]]) && is.name(bysub[[3L]])) {
byval = eval(bysub, setattr(as.list(seq_along(x)), 'names', names(x)), parent.frame())
byval = as.list(x)[byval]
} else byval = eval(bysub, x, parent.frame())
} else {
# length 0 when i returns no rows
if (!is.integer(irows)) stop("Internal error: irows isn't integer") # nocov
# Passing irows as i to x[] below has been troublesome in a rare edge case.
# irows may contain NA, 0, negatives and >nrow(x) here. That's all ok.
# But we may need i join column values to be retained (where those rows have no match), hence we tried eval(isub)
# in 1.8.3, but this failed test 876.
# TO DO: Add a test like X[i,sum(v),by=i.x2], or where by includes a join column (both where some i don't match).
# TO DO: Make xss directly, rather than recursive call.
if (!is.na(nomatch)) irows = irows[irows!=0L] # TO DO: can be removed now we have CisSortedSubset
if (length(allbyvars)) { ############### TO DO TO DO TO DO ###############
if (verbose) cat("i clause present and columns used in by detected, only these subset:",paste(allbyvars,collapse=","),"\n")
xss = x[irows,allbyvars,with=FALSE,nomatch=nomatch,mult=mult,roll=roll,rollends=rollends]
} else {
if (verbose) cat("i clause present but columns used in by not detected. Having to subset all columns before evaluating 'by': '",deparse(by),"'\n",sep="")
xss = x[irows,nomatch=nomatch,mult=mult,roll=roll,rollends=rollends]
}
if (is.call(bysub) && length(bysub) == 3L && bysub[[1L]] == ":") {
byval = eval(bysub, setattr(as.list(seq_along(xss)), 'names', names(xss)), parent.frame())
byval = as.list(xss)[byval]
} else byval = eval(bysub, xss, parent.frame())
xnrow = nrow(xss)
# TO DO: pass xss (x subset) through into dogroups. Still need irows there (for :=), but more condense
# and contiguous to use xss to form .SD in dogroups than going via irows
}
if (!length(byval) && xnrow>0L) {
# see missingby up above for comments
# by could be NULL or character(0L) for example (e.g. passed in as argument in a loop of different bys)
bysameorder = FALSE # 1st and only group is the entire table, so could be TRUE, but FALSE to avoid
# a key of empty character()
byval = list()
bynames = allbyvars = NULL
# the rest now fall through
} else bynames = names(byval)
if (is.atomic(byval)) {
if (is.character(byval) && length(byval)<=ncol(x) && !(is.name(bysub) && as.character(bysub)%chin%names(x)) ) {
stop("'by' appears to evaluate to column names but isn't c() or key(). Use by=list(...) if you can. Otherwise, by=eval",deparse(bysub)," should work. This is for efficiency so data.table can detect which columns are needed.")
} else {
# by may be a single unquoted column name but it must evaluate to list so this is a convenience to users. Could also be a single expression here such as DT[,sum(v),by=colA%%2]
byval = list(byval)
bysubl = c(as.name("list"),bysuborig) # for guessing the column name below
if (is.name(bysuborig))
bynames = as.character(bysuborig)
else
bynames = names(byval)
}
}
if (!is.list(byval)) stop("'by' or 'keyby' must evaluate to a vector or a list of vectors (where 'list' includes data.table and data.frame which are lists, too)")
if (length(byval)==1L && is.null(byval[[1L]])) bynull=TRUE #3530 when by=(function()NULL)()
if (!bynull) for (jj in seq_len(length(byval))) {
if (!typeof(byval[[jj]]) %chin% c("integer","logical","character","double")) stop("column or expression ",jj," of 'by' or 'keyby' is type ",typeof(byval[[jj]]),". Do not quote column names. Usage: DT[,sum(colC),by=list(colA,month(colB))]")
}
tt = vapply_1i(byval,length)
if (any(tt!=xnrow)) stop("The items in the 'by' or 'keyby' list are length (",paste(tt,collapse=","),"). Each must be length ", xnrow, "; the same length as there are rows in x (after subsetting if i is provided).")
if (is.null(bynames)) bynames = rep.int("",length(byval))
if (any(bynames=="") && !bynull) {
for (jj in seq_along(bynames)) {
if (bynames[jj]=="") {
# Best guess. Use "month" in the case of by=month(date), use "a" in the case of by=a%%2
byvars = all.vars(bysubl[[jj+1L]], functions = TRUE)
if (length(byvars) == 1L) tt = byvars
else {
tt = grep("^eval|^[^[:alpha:]. ]",byvars,invert=TRUE,value=TRUE)
if (length(tt)) tt = tt[1L] else all.vars(bysubl[[jj+1L]])[1L]
}
# fix for #497
if (length(byvars) > 1L && tt %chin% all.vars(jsub, FALSE)) {
bynames[jj] = deparse(bysubl[[jj+1L]])
if (verbose)
cat("by-expression '", bynames[jj], "' is not named, and the auto-generated name '", tt,
"' clashed with variable(s) in j. Therefore assigning the entire by-expression as name.\n", sep="")
}
else bynames[jj] = tt
# if user doesn't like this inferred name, user has to use by=list() to name the column
}
}
# Fix for #1334
if (any(duplicated(bynames))) {
bynames = make.unique(bynames)
}
}
setattr(byval, "names", bynames) # byval is just a list not a data.table hence setattr not setnames
}
jvnames = NULL
if (is.name(jsub)) {
# j is a single unquoted column name
if (jsub!=".SD") {
jvnames = gsub("^[.](N|I|GRP|BY)$","\\1",as.character(jsub))
# jsub is list()ed after it's eval'd inside dogroups.
}
} else if (is.call(jsub) && as.character(jsub[[1L]])[[1L]] %chin% c("list",".")) {
jsub[[1L]] = quote(list)
jsubl = as.list.default(jsub) # TO DO: names(jsub) and names(jsub)="" seem to work so make use of that
if (length(jsubl)>1L) {
jvnames = names(jsubl)[-1L] # check list(a=sum(v),v)
if (is.null(jvnames)) jvnames = rep.int("", length(jsubl)-1L)
for (jj in seq.int(2L,length(jsubl))) {
if (jvnames[jj-1L] == "" && mode(jsubl[[jj]])=="name") {
if (jsubl[[jj]]=="") stop("Item ", jj-1L, " of the .() or list() passed to j is missing") #3507
jvnames[jj-1L] = gsub("^[.](N|I|GRP|BY)$", "\\1", deparse(jsubl[[jj]]))
}
# TO DO: if call to a[1] for example, then call it 'a' too
}
setattr(jsubl, "names", NULL) # drops the names from the list so it's faster to eval the j for each group. We'll put them back aftwards on the result.
jsub = as.call(jsubl)
} # else empty list is needed for test 468: adding an empty list column
} # else maybe a call to transform or something which returns a list.
av = all.vars(jsub,TRUE) # TRUE fixes bug #1294 which didn't see b in j=fns[[b]](c)
use.I = ".I" %chin% av
# browser()
if (any(c(".SD","eval","get","mget") %chin% av)) {
if (missing(.SDcols)) {
# here we need to use 'dupdiff' instead of 'setdiff'. Ex: setdiff(c("x", "x"), NULL) will give 'x'.
ansvars = dupdiff(names(x),union(bynames,allbyvars)) # TO DO: allbyvars here for vars used by 'by'. Document.
# just using .SD in j triggers all non-by columns in the subset even if some of
# those columns are not used. It would be tricky to detect whether the j expression
# really does use all of the .SD columns or not, hence .SDcols for grouping
# over a subset of columns
# all duplicate columns must be matched, because nothing is provided
ansvals = chmatchdup(ansvars, names(x))
} else {
# FR #4979 - negative numeric and character indices for SDcols
colsub = substitute(.SDcols)
# fix for #5190. colsub[[1L]] gave error when it's a symbol.
if (is.call(colsub) && deparse(colsub[[1L]], 500L, backtick=FALSE) %chin% c("!", "-")) {
colm = TRUE
colsub = colsub[[2L]]
} else colm = FALSE
# fix for #1216, make sure the paranthesis are peeled from expr of the form (((1:4)))
while(is.call(colsub) && colsub[[1L]] == "(") colsub = as.list(colsub)[[-1L]]
if (is.call(colsub) && length(colsub) == 3L && colsub[[1L]] == ":") {
# .SDcols is of the format a:b
.SDcols = eval(colsub, setattr(as.list(seq_along(x)), 'names', names(x)), parent.frame())
} else {
if (is.call(colsub) && colsub[[1L]] == "patterns") {
# each pattern gives a new filter condition, intersect the end result
.SDcols = Reduce(intersect, do_patterns(colsub, names(x)))
} else {
.SDcols = eval(colsub, parent.frame(), parent.frame())
}
}
if (anyNA(.SDcols))
stop(".SDcols missing at the following indices: ", brackify(which(is.na(.SDcols))))
if (is.logical(.SDcols)) {
ansvals = which_(rep(.SDcols, length.out=length(x)), !colm)
ansvars = names(x)[ansvals]
} else if (is.numeric(.SDcols)) {
# if .SDcols is numeric, use 'dupdiff' instead of 'setdiff'
if (length(unique(sign(.SDcols))) > 1L) stop(".SDcols is numeric but has both +ve and -ve indices")
if (any(idx <- abs(.SDcols)>ncol(x) | abs(.SDcols)<1L))
stop(".SDcols is numeric but out of bounds [1, ", ncol(x), "] at: ", brackify(which(idx)))
if (colm) ansvars = dupdiff(names(x)[-.SDcols], bynames) else ansvars = names(x)[.SDcols]
ansvals = if (colm) setdiff(seq_along(names(x)), c(as.integer(.SDcols), which(names(x) %chin% bynames))) else as.integer(.SDcols)
} else {
if (!is.character(.SDcols)) stop(".SDcols should be column numbers or names")
if (!all(idx <- .SDcols %chin% names(x)))
stop("Some items of .SDcols are not column names: ", brackify(.SDcols[!idx]))
if (colm) ansvars = setdiff(setdiff(names(x), .SDcols), bynames) else ansvars = .SDcols
# dups = FALSE here. DT[, .SD, .SDcols=c("x", "x")] again doesn't really help with which 'x' to keep (and if '-' which x to remove)
ansvals = chmatch(ansvars, names(x))
}
}
# fix for long standing FR/bug, #495 and #484
allcols = c(names(x), xdotprefix, names(i), idotprefix)
if ( length(othervars <- setdiff(intersect(av, allcols), c(bynames, ansvars))) ) {
# we've a situation like DT[, c(sum(V1), lapply(.SD, mean)), by=., .SDcols=...] or
# DT[, lapply(.SD, function(x) x *v1), by=, .SDcols=...] etc.,
ansvars = union(ansvars, othervars)
ansvals = chmatch(ansvars, names(x))
}
# .SDcols might include grouping columns if users wants that, but normally we expect user not to include them in .SDcols
} else {
if (!missing(.SDcols)) warning("This j doesn't use .SD but .SDcols has been supplied. Ignoring .SDcols. See ?data.table.")
allcols = c(names(x), xdotprefix, names(i), idotprefix)
ansvars = setdiff(intersect(av,allcols), bynames)
if (verbose) cat("Detected that j uses these columns:",if (!length(ansvars)) "<none>" else paste(ansvars,collapse=","),"\n")
# using a few named columns will be faster
# Consider: DT[,max(diff(date)),by=list(month=month(date))]
# and: DT[,lapply(.SD,sum),by=month(date)]
# We don't want date in .SD in the latter, but we do in the former; hence the union() above.
ansvals = chmatch(ansvars, names(x))
}
# if (!length(ansvars)) Leave ansvars empty. Important for test 607.
# TODO remove as (m)get is now folded in above.
# added 'mget' - fix for #994
if (any(c("get", "mget") %chin% av)) {
if (verbose) {
cat("'(m)get' found in j. ansvars being set to all columns. Use .SDcols or a single j=eval(macro) instead. Both will detect the columns used which is important for efficiency.\nOld:", paste(ansvars,collapse=","),"\n")
# get('varname') is too difficult to detect which columns are used in general
# eval(macro) column names are detected via the if jsub[[1]]==eval switch earlier above.
}
# Do not include z in .SD when dt[, z := {.SD; get("x")}, .SDcols = "y"] (#2326, #2338)
if (is.call(jsub) && length(jsub[[1L]]) == 1L && jsub[[1L]] == ":=" && is.symbol(jsub[[2L]])) {
jsub_lhs_symbol <- as.character(jsub[[2L]])
if (jsub_lhs_symbol %chin% othervars) {
ansvars <- setdiff(ansvars, jsub_lhs_symbol)
}
}
if (length(ansvars)) othervars = ansvars # #1744 fix
allcols = c(names(x), xdotprefix, names(i), idotprefix)
ansvars = setdiff(allcols,bynames) # fix for bug #5443
ansvals = chmatch(ansvars, names(x))
if (length(othervars)) othervars = setdiff(ansvars, othervars) # #1744 fix
if (verbose) cat("New:",paste(ansvars,collapse=","),"\n")
}
lhs = NULL
newnames = NULL
suppPrint = identity
if (length(av) && av[1L] == ":=") {
if (identical(attr(x,".data.table.locked"),TRUE)) stop(".SD is locked. Using := in .SD's j is reserved for possible future use; a tortuously flexible way to modify by group. Use := in j directly to modify by group by reference.")
suppPrint <- function(x) { .global$print=address(x); x }
# Suppress print when returns ok not on error, bug #2376. Thanks to: http://stackoverflow.com/a/13606880/403310
# All appropriate returns following this point are wrapped; i.e. return(suppPrint(x)).
if (is.null(names(jsub))) {
# regular LHS:=RHS usage, or `:=`(...) with no named arguments (an error)
# `:=`(LHS,RHS) is valid though, but more because can't see how to detect that, than desire
if (length(jsub)!=3L) stop("In `:=`(col1=val1, col2=val2, ...) form, all arguments must be named.")
lhs = jsub[[2L]]
jsub = jsub[[3L]]
if (is.name(lhs)) {
lhs = as.character(lhs)
} else {
# e.g. (MyVar):= or get("MyVar"):=
lhs = eval(lhs, parent.frame(), parent.frame())
}
} else {
# `:=`(c2=1L,c3=2L,...)
lhs = names(jsub)[-1L]
if (any(lhs=="")) stop("In `:=`(col1=val1, col2=val2, ...) form, all arguments must be named.")
names(jsub)=""
jsub[[1L]]=as.name("list")
}
av = all.vars(jsub,TRUE)
if (!is.atomic(lhs)) stop("LHS of := must be a symbol, or an atomic vector (column names or positions).")
if (is.character(lhs)) {
m = chmatch(lhs,names(x))
} else if (is.numeric(lhs)) {
m = as.integer(lhs)
if (any(m<1L | ncol(x)<m)) stop("LHS of := appears to be column positions but are outside [1,ncol] range. New columns can only be added by name.")
lhs = names(x)[m]
} else
stop("LHS of := isn't column names ('character') or positions ('integer' or 'numeric')")
if (all(!is.na(m))) {
# updates by reference to existing columns
cols = as.integer(m)
newnames=NULL
if (identical(irows, integer())) {
# Empty integer() means no rows e.g. logical i with only FALSE and NA
# got converted to empty integer() by the which() above
# Short circuit and do-nothing since columns already exist. If some don't
# exist then for consistency with cases where irows is non-empty, we need to create
# them of the right type and populate with NA. Which will happen via the regular
# alternative branches below, to cover #759.
# We need this short circuit at all just for convenience. Otherwise users may need to
# fix errors in their RHS when called on empty edge cases, even when the result won't be
# used anyway (so it would be annoying to have to fix it.)
if (verbose) {
cat("No rows match i. No new columns to add so not evaluating RHS of :=\n")
cat("Assigning to 0 row subset of",nrow(x),"rows\n")
}
.Call(Cassign, x, irows, NULL, NULL, NULL, FALSE) # only purpose is to write 0 to .Last.updated
.global$print = address(x)
return(invisible(x))
}
} else {
# Adding new column(s). TO DO: move after the first eval in case the jsub has an error.
newnames=setdiff(lhs,names(x))
m[is.na(m)] = ncol(x)+seq_len(length(newnames))
cols = as.integer(m)
# don't pass verbose to selfrefok here -- only activated when
# ok=-1 which will trigger alloc.col with verbose in the next
# branch, which again calls _selfrefok and returns the message then
if ((ok<-selfrefok(x, verbose=FALSE))==0L) # ok==0 so no warning when loaded from disk (-1) [-1 considered TRUE by R]
warning("Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.")
if ((ok<1L) || (truelength(x) < ncol(x)+length(newnames))) {
DT = x # in case getOption contains "ncol(DT)" as it used to. TODO: warn and then remove
n = length(newnames) + eval(getOption("datatable.alloccol")) # TODO: warn about expressions and then drop the eval()
# i.e. reallocate at the size as if the new columns were added followed by alloc.col().
name = substitute(x)
if (is.name(name) && ok && verbose) { # && NAMED(x)>0 (TO DO) # ok here includes -1 (loaded from disk)
cat("Growing vector of column pointers from truelength ", truelength(x), " to ", n, ". A shallow copy has been taken, see ?alloc.col. Only a potential issue if two variables point to the same data (we can't yet detect that well) and if not you can safely ignore this. To avoid this message you could alloc.col() first, deep copy first using copy(), wrap with suppressWarnings() or increase the 'datatable.alloccol' option.\n")
# #1729 -- copying to the wrong environment here can cause some confusion
if (ok == -1L) cat("Note that the shallow copy will assign to the environment from which := was called. That means for example that if := was called within a function, the original table may be unaffected.\n")
# Verbosity should not issue warnings, so cat rather than warning.
# TO DO: Add option 'datatable.pedantic' to turn on warnings like this.
# TO DO ... comments moved up from C ...
# Note that the NAMED(dt)>1 doesn't work because .Call
# always sets to 2 (see R-ints), it seems. Work around
# may be possible but not yet working. When the NAMED test works, we can drop allocwarn argument too
# because that's just passed in as FALSE from [<- where we know `*tmp*` isn't really NAMED=2.
# Note also that this growing will happen for missing columns assigned NULL, too. But so rare, we
# don't mind.
}
alloc.col(x, n, verbose=verbose) # always assigns to calling scope; i.e. this scope
if (is.name(name)) {
assign(as.character(name),x,parent.frame(),inherits=TRUE)
} else if (is.call(name) && (name[[1L]] == "$" || name[[1L]] == "[[") && is.name(name[[2L]])) {
k = eval(name[[2L]], parent.frame(), parent.frame())
if (is.list(k)) {
origj = j = if (name[[1L]] == "$") as.character(name[[3L]]) else eval(name[[3L]], parent.frame(), parent.frame())
if (is.character(j)) {
if (length(j)!=1L) stop("L[[i]][,:=] syntax only valid when i is length 1, but it's length %d",length(j))
j = match(j, names(k))
if (is.na(j)) stop("Item '",origj,"' not found in names of list")
}
.Call(Csetlistelt,k,as.integer(j), x)
} else if (is.environment(k) && exists(as.character(name[[3L]]), k)) {
assign(as.character(name[[3L]]), x, k, inherits=FALSE)
}
} # TO DO: else if env$<- or list$<-
}
}
}
}
if (length(ansvars)) {
w = ansvals
if (length(rightcols) && missingby) {
w[ w %in% rightcols ] = NA
}
# patch for #1615. Allow 'x.' syntax. Only useful during join op when x's join col needs to be used.
# Note that I specifically have not implemented x[y, aa, on=c(aa="bb")] to refer to x's join column
# as well because x[i, col] == x[i][, col] will not be TRUE anymore..
if ( any(xdotprefixvals <- ansvars %chin% xdotprefix)) {
w[xdotprefixvals] = chmatch(ansvars[xdotprefixvals], xdotprefix)
xdotcols = TRUE
}
if (!any(wna <- is.na(w))) {
xcols = w
xcolsAns = seq_along(ansvars)
icols = icolsAns = integer()
} else {
if (!length(leftcols)) stop("column(s) not found: ", paste(ansvars[wna],collapse=", "))
xcols = w[!wna]
xcolsAns = which(!wna)
ivars = names(i)
ivars[leftcols] = names(x)[rightcols]
w2 = chmatch(ansvars[wna], ivars)
if (any(w2na <- is.na(w2))) {
ivars = paste0("i.",ivars)
ivars[leftcols] = names(i)[leftcols]
w2[w2na] = chmatch(ansvars[wna][w2na], ivars)
if (any(w2na <- is.na(w2))) {
ivars[leftcols] = paste0("i.",ivars[leftcols])
w2[w2na] = chmatch(ansvars[wna][w2na], ivars)
if (any(w2na <- is.na(w2))) stop("column(s) not found: ", paste(ansvars[wna][w2na],sep=", "))
}
}
icols = w2
icolsAns = which(wna)
}
}
} # end of if !missing(j)
SDenv = new.env(parent=parent.frame())
# taking care of warnings for posixlt type, #646
SDenv$strptime <- function(x, ...) {
warning("POSIXlt column type detected and converted to POSIXct. We do not recommend use of POSIXlt at all because it uses 40 bytes to store one date. Use as.POSIXct to avoid this warning.")
as.POSIXct(base::strptime(x, ...))
}
syms = all.vars(jsub)
syms = syms[ substring(syms,1L,2L)==".." ]
syms = syms[ substring(syms,3L,3L)!="." ] # exclude ellipsis
for (sym in syms) {
if (sym %chin% names(x)) {
# if "..x" exists as column name, use column, for backwards compatibility; e.g. package socialmixr in rev dep checks #2779
next
# TODO in future, as warned in NEWS item for v1.11.0 :
# warning(sym," in j is looking for ",getName," in calling scope, but a column '", sym, "' exists. Column names should not start with ..")
}
getName = substring(sym, 3L)
if (!exists(getName, parent.frame())) {
if (exists(sym, parent.frame())) next # user did 'manual' prefix; i.e. variable in calling scope has .. prefix
stop("Variable '",getName,"' is not found in calling scope. Looking in calling scope because this symbol was prefixed with .. in the j= parameter.")
}
assign(sym, get(getName, parent.frame()), SDenv)
}
# hash=TRUE (the default) does seem better as expected using e.g. test 645. TO DO experiment with 'size' argument
if (missingby || bynull || (!byjoin && !length(byval))) {
# No grouping: 'by' = missing | NULL | character() | "" | list()
# Considered passing a one-group to dogroups but it doesn't do the recycling of i within group, that's done here
if (length(ansvars)) {
if (!(length(i) && length(icols))) {
# new in v1.12.0 to redirect to CsubsetDT in this case
if (!identical(xcolsAns, seq_along(xcolsAns)) || length(xcols)!=length(xcolsAns) || length(ansvars)!=length(xcolsAns)) {
stop("Internal error: xcolAns does not pass checks: ", length(xcolsAns), length(ansvars), length(xcols), paste(xcolsAns,collapse=",")) # nocov
}
# Retained from old R way below (test 1542.01 checks shallow at this point)
# ' Temp fix for #921 - skip COPY until after evaluating 'jval' (scroll down).
# ' Unless 'with=FALSE' - can not be expressions but just column names.
ans = if (with && is.null(irows)) shallow(x, xcols) else .Call(CsubsetDT, x, irows, xcols)
setattr(ans, "names", ansvars)
} else {
# length(i) && length(icols)
if (is.null(irows)) {
stop("Internal error: irows is NULL when making join result at R level. Should no longer happen now we use CsubsetDT earlier.") # nocov
# TODO: Make subsetDT do a shallow copy when irows is NULL (it currently copies). Then copy only when user uses := or set* on the result
# by using NAMED/REFCNT on columns, with warning if they copy. Since then, even foo = DT$b would cause the next set or := to copy that
# column (so the warning is needed). To tackle that, we could have our own DT.NAMED attribute, perhaps.
# Or keep the rule that [.data.table always returns new memory, and create view() or view= as well, maybe cleaner.
}
ans = vector("list", length(ansvars))
ii = rep.int(indices__, len__) # following #1991 fix
# TODO: if (allLen1 && allGrp1 && (is.na(nomatch) || !any(f__==0L))) then ii will be 1:nrow(i) [nomatch=0 should drop rows in i that have no match]
# But rather than that complex logic here at R level to catch that and do a shallow copy for efficiency, just do the check inside CsubsetDT
# to see if it passed 1:nrow(x) and then CsubsetDT should do the shallow copy safely and centrally.
# That R level branch was taken out in PR #3213
# TO DO: use CsubsetDT twice here and then remove this entire R level branch
for (s in seq_along(icols)) {
target = icolsAns[s]
source = icols[s]
ans[[target]] = .Call(CsubsetVector,i[[source]],ii) # i.e. i[[source]][ii]
}
for (s in seq_along(xcols)) {
target = xcolsAns[s]
source = xcols[s]
ans[[target]] = .Call(CsubsetVector,x[[source]],irows) # i.e. x[[source]][irows], but guaranteed new memory even for singleton logicals from R 3.1.0
}
setattr(ans, "names", ansvars)
if (haskey(x)) {
keylen = which.first(!key(x) %chin% ansvars)-1L
if (is.na(keylen)) keylen = length(key(x))
len = length(rightcols)
# fix for #1268, #1704, #1766 and #1823
chk = if (len && !missing(on)) !identical(head(key(x), len), names(on)) else FALSE
if ( (keylen>len || chk) && !.Call(CisOrderedSubset, irows, nrow(x))) {
keylen = if (!chk) len else 0L # fix for #1268
}
## check key on i as well!
ichk = is.data.table(i) && haskey(i) &&
identical(head(key(i), length(leftcols)), names(i)[leftcols]) # i has the correct key, #3061
if (keylen && (ichk || is.logical(i) || (.Call(CisOrderedSubset, irows, nrow(x)) && ((roll == FALSE) || length(irows) == 1L)))) # see #1010. don't set key when i has no key, but irows is ordered and roll != FALSE
setattr(ans,"sorted",head(key(x),keylen))
}
setattr(ans, "class", class(x)) # fix for #5296
setattr(ans, "row.names", .set_row_names(nrow(ans)))
alloc.col(ans)
}
if (!with || missing(j)) return(ans)
SDenv$.SDall = ans
SDenv$.SD = if (!length(othervars)) SDenv$.SDall else shallow(SDenv$.SDall, setdiff(ansvars, othervars))
SDenv$.N = nrow(SDenv$.SD)
} else {
SDenv$.SDall = SDenv$.SD = null.data.table() # no columns used by j so .SD can be empty. Only needs to exist so that we can rely on it being there when locking it below for example. If .SD were used by j, of course then xvars would be the columns and we wouldn't be in this leaf.
SDenv$.N = if (is.null(irows)) nrow(x) else length(irows) * !identical(suppressWarnings(max(irows)), 0L)
# Fix for #963.
# When irows is integer(0L), length(irows) = 0 will result in 0 (as expected).
# Binary search can return all 0 irows when none of the input matches. Instead of doing all(irows==0L) (previous method), which has to allocate a logical vector the size of irows, we can make use of 'max'. If max is 0, we return 0. The condition where only some irows > 0 won't occur.
}
# Temp fix for #921. Allocate `.I` only if j-expression uses it.
SDenv$.I = if (!missing(j) && use.I) seq_len(SDenv$.N) else 0L
SDenv$.GRP = 1L
setattr(SDenv$.SD,".data.table.locked",TRUE) # used to stop := modifying .SD via j=f(.SD), bug#1727. The more common case of j=.SD[,subcol:=1] was already caught when jsub is inspected for :=.
setattr(SDenv$.SDall,".data.table.locked",TRUE)
lockBinding(".SD",SDenv)
lockBinding(".SDall",SDenv)
lockBinding(".N",SDenv)
lockBinding(".I",SDenv)
lockBinding(".GRP",SDenv)
for (ii in ansvars) assign(ii, SDenv$.SDall[[ii]], SDenv)
# Since .SD is inside SDenv, alongside its columns as variables, R finds .SD symbol more quickly, if used.
# There isn't a copy of the columns here, the xvar symbols point to the SD columns (copy-on-write).
if (is.name(jsub) && is.null(lhs) && !exists(jsubChar<-as.character(jsub), SDenv, inherits=FALSE)) {
stop("j (the 2nd argument inside [...]) is a single symbol but column name '",jsubChar,"' is not found. Perhaps you intended DT[, ..",jsubChar,"]. This difference to data.frame is deliberate and explained in FAQ 1.1.")
}
jval = eval(jsub, SDenv, parent.frame())
# copy 'jval' when required
# More speedup - only check + copy if irows is NULL
# Temp fix for #921 - check address and copy *after* evaluating 'jval'
if (is.null(irows)) {
if (!is.list(jval)) { # performance improvement when i-arg is S4, but not list, #1438, Thanks @DCEmilberg.
jcpy = address(jval) %in% vapply_1c(SDenv$.SD, address) # %chin% errors when RHS is list()
if (jcpy) jval = copy(jval)
} else if (address(jval) == address(SDenv$.SD)) {
jval = copy(jval)
} else if ( length(jcpy <- which(vapply_1c(jval, address) %in% vapply_1c(SDenv, address))) ) {
for (jidx in jcpy) jval[[jidx]] = copy(jval[[jidx]])
} else if (is.call(jsub) && jsub[[1L]] == "get" && is.list(jval)) {
jval = copy(jval) # fix for #1212
}
} else {
if (is.data.table(jval)) {
setattr(jval, '.data.table.locked', NULL) # fix for #1341
if (!truelength(jval)) alloc.col(jval)
}
}
if (!is.null(lhs)) {
# TODO?: use set() here now that it can add new columns. Then remove newnames and alloc logic above.
.Call(Cassign,x,irows,cols,newnames,jval,verbose)
return(suppPrint(x))
}
if ((is.call(jsub) && is.list(jval) && jsub[[1L]] != "get" && !is.object(jval)) || !missingby) {
# is.call: selecting from a list column should return list
# is.object: for test 168 and 168.1 (S4 object result from ggplot2::qplot). Just plain list results should result in data.table
# Fix for #813 and #758. Ex: DT[c(FALSE, FALSE), list(integer(0L), y)]
# where DT = data.table(x=1:2, y=3:4) should return an empty data.table!!
if (!is.null(irows) && `||`(
identical(irows, integer(0L)) && !bynull,
length(irows) && !anyNA(irows) && all(irows==0L) ## anyNA() because all() returns NA (not FALSE) when irows is all-NA. TODO: any way to not check all 'irows' values?
))
if (is.atomic(jval)) jval = jval[0L] else jval = lapply(jval, `[`, 0L)
if (is.atomic(jval)) {
setattr(jval,"names",NULL)
jval = data.table(jval) # TO DO: should this be setDT(list(jval)) instead?
} else {
if (is.null(jvnames)) jvnames=names(jval)
# avoid copy if all vectors are already of same lengths, use setDT
lenjval = vapply(jval, length, 0L)
if (any(lenjval != lenjval[1L])) {
jval = as.data.table.list(jval) # does the vector expansion to create equal length vectors
jvnames = jvnames[lenjval != 0L] # fix for #1477
} else setDT(jval)
}
if (is.null(jvnames)) jvnames = character(length(jval)-length(bynames))
ww = which(jvnames=="")
if (any(ww)) jvnames[ww] = paste0("V",ww)
setnames(jval, jvnames)
}
# fix for bug #5114 from GSee's - .data.table.locked=TRUE. # TO DO: more efficient way e.g. address==address (identical will do that but then proceed to deep compare if !=, wheras we want just to stop?)
# Commented as it's taken care of above, along with #921 fix. Kept here for the bug fix info and TO DO.
# if (identical(jval, SDenv$.SD)) return(copy(jval))
if (is.data.table(jval)) {
setattr(jval, 'class', class(x)) # fix for #5296
if (haskey(x) && all(key(x) %chin% names(jval)) && suppressWarnings(is.sorted(jval, by=key(x)))) # TO DO: perhaps this usage of is.sorted should be allowed internally then (tidy up and make efficient)
setattr(jval, 'sorted', key(x))
# postponed to v1.12.4 because package eplusr creates a NULL column and then runs setcolorder on the result which fails if there are fewer columns
# w = sapply(jval, is.null)
# if (any(w)) jval = jval[,!w,with=FALSE] # no !..w due to 'Undefined global functions or variables' note from R CMD check
}
return(jval)
}
###########################################################################
# Grouping ...
###########################################################################
o__ = integer()
if (".N" %chin% ansvars) stop("The column '.N' can't be grouped because it conflicts with the special .N variable. Try setnames(DT,'.N','N') first.")
if (".I" %chin% ansvars) stop("The column '.I' can't be grouped because it conflicts with the special .I variable. Try setnames(DT,'.I','I') first.")
SDenv$.iSD = NULL # null.data.table()
SDenv$.xSD = NULL # null.data.table() - introducing for FR #2693 and Gabor's post on fixing for FAQ 2.8
assign("print", function(x,...){base::print(x,...);NULL}, SDenv)
# Now ggplot2 returns data from print, we need a way to throw it away otherwise j accumulates the result
SDenv$.SDall = SDenv$.SD = null.data.table() # e.g. test 607. Grouping still proceeds even though no .SD e.g. grouping key only tables, or where j consists of .N only
SDenv$.N = vector("integer", 1L) # explicit new vector (not 0L or as.integer() which might return R's internal small-integer global)
SDenv$.GRP = vector("integer", 1L) # because written to by reference at C level (one write per group). TODO: move this alloc to C level
if (byjoin) {
# The groupings come instead from each row of the i data.table.
# Much faster for a few known groups vs a 'by' for all followed by a subset
if (!is.data.table(i)) stop("logical error. i is not data.table, but mult='all' and 'by'=.EACHI")
byval = i
bynames = if (missing(on)) head(key(x),length(leftcols)) else names(on)
allbyvars = NULL
bysameorder = haskey(i) || (is.sorted(f__) && ((roll == FALSE) || length(f__) == 1L)) # Fix for #1010
## 'av' correct here ?? *** TO DO ***
xjisvars = intersect(av, names(x)[rightcols]) # no "x." for xvars.
# if 'get' is in 'av' use all cols in 'i', fix for bug #5443
# added 'mget' - fix for #994
jisvars = if (any(c("get", "mget") %chin% av)) names(i) else intersect(gsub("^i[.]","", setdiff(av, xjisvars)), names(i))
# JIS (non join cols) but includes join columns too (as there are named in i)
if (length(jisvars)) {
tt = min(nrow(i),1L)
SDenv$.iSD = i[tt,jisvars,with=FALSE]
for (ii in jisvars) {
assign(ii, SDenv$.iSD[[ii]], SDenv)
assign(paste0("i.",ii), SDenv$.iSD[[ii]], SDenv)
}
}
} else {
# Find the groups, using 'byval' ...
if (missingby) stop("Internal error: by= is missing") # nocov
if (length(byval) && length(byval[[1L]])) {
if (!bysameorder && isFALSE(byindex)) {
if (verbose) {last.started.at=proc.time();cat("Finding groups using forderv ... ");flush.console()}
o__ = forderv(byval, sort=keyby, retGrp=TRUE)
# The sort= argument is called sortGroups at C level. It's primarily for saving the sort of unique strings at
# C level for efficiency when by= not keyby=. Other types also retain appearance order, but at byte level to
# minimize data movement and benefit from skipping subgroups which happen to be grouped but not sorted. This byte
# appearance order is not the same as the order of group values within by= columns, so the 2nd forder below is
# still needed to get the group appearance order. Always passing sort=TRUE above won't change any result at all
# (tested and confirmed), it'll just make by= slower. It must be TRUE when keyby= though since the key is just
# marked afterwards.
# forderv() returns empty integer() if already ordered to save allocating 1:xnrow
bysameorder = orderedirows && !length(o__)
if (verbose) {
cat(timetaken(last.started.at),"\n")
last.started.at=proc.time()
cat("Finding group sizes from the positions (can be avoided to save RAM) ... ")
flush.console() # for windows
}
f__ = attr(o__, "starts")
len__ = uniqlengths(f__, xnrow)
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
if (!bysameorder && !keyby) {
# TO DO: lower this into forder.c
if (verbose) {last.started.at=proc.time();cat("Getting back original order ... ");flush.console()}
firstofeachgroup = o__[f__]
if (length(origorder <- forderv(firstofeachgroup))) {
f__ = f__[origorder]
len__ = len__[origorder]
}
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
}
if (!orderedirows && !length(o__)) o__ = seq_len(xnrow) # temp fix. TODO: revist orderedirows
} else {
if (verbose) last.started.at=proc.time();
if (bysameorder) {
if (verbose) {cat("Finding groups using uniqlist on key ... ");flush.console()}
f__ = uniqlist(byval)
} else {
if (!is.character(byindex) || length(byindex)!=1L) stop("Internal error: byindex not the index name") # nocov
if (verbose) {cat("Finding groups using uniqlist on index '", byindex, "' ... ", sep="");flush.console()}
o__ = getindex(x, byindex)
if (is.null(o__)) stop("Internal error: byindex not found") # nocov
f__ = uniqlist(byval, order=o__)
}
if (verbose) {
cat(timetaken(last.started.at),"\n")
last.started.at=proc.time()
cat("Finding group sizes from the positions (can be avoided to save RAM) ... ")
flush.console() # for windows
}
len__ = uniqlengths(f__, xnrow)
# TO DO: combine uniqlist and uniquelengths into one call. Or, just set len__ to NULL when dogroups infers that.
if (verbose) { cat(timetaken(last.started.at),"\n"); flush.console() }
}
} else {
f__=NULL
len__=0L
bysameorder=TRUE # for test 724
}
# TO DO: allow secondary keys to be stored, then we see if our by matches one, if so use it, and no need to sort again. TO DO: document multiple keys.
}
if (length(xcols)) {
# TODO add: if (max(len__)==nrow) stop("There is no need to deep copy x in this case")
# TODO move down to dogroup.c, too.
SDenv$.SDall = .Call(CsubsetDT, x, if (length(len__)) seq_len(max(len__)) else 0L, xcols) # must be deep copy when largest group is a subset
if (xdotcols) setattr(SDenv$.SDall, 'names', ansvars[xcolsAns]) # now that we allow 'x.' prefix in 'j', #2313 bug fix - [xcolsAns]
SDenv$.SD = if (!length(othervars)) SDenv$.SDall else shallow(SDenv$.SDall, setdiff(ansvars, othervars))
}
if (nrow(SDenv$.SDall)==0L) {
setattr(SDenv$.SDall,"row.names",c(NA_integer_,0L))
setattr(SDenv$.SD,"row.names",c(NA_integer_,0L))
}
# .set_row_names() basically other than not integer() for 0 length, otherwise dogroups has no [1] to modify to -.N
setattr(SDenv$.SD,".data.table.locked",TRUE) # used to stop := modifying .SD via j=f(.SD), bug#1727. The more common case of j=.SD[,subcol:=1] was already caught when jsub is inspected for :=.
setattr(SDenv$.SDall,".data.table.locked",TRUE)
lockBinding(".SD",SDenv)
lockBinding(".SDall",SDenv)
lockBinding(".N",SDenv)
lockBinding(".GRP",SDenv)
lockBinding(".iSD",SDenv)
GForce = FALSE
if ( getOption("datatable.optimize")>=1 && (is.call(jsub) || (is.name(jsub) && as.character(jsub)[[1L]] %chin% c(".SD",".N"))) ) { # Ability to turn off if problems or to benchmark the benefit
# Optimization to reduce overhead of calling lapply over and over for each group
ansvarsnew = setdiff(ansvars, othervars)
oldjsub = jsub
funi = 1L # Fix for #985
# convereted the lapply(.SD, ...) to a function and used below, easier to implement FR #2722 then.
.massageSD <- function(jsub) {
txt = as.list(jsub)[-1L]
if (length(names(txt))>1L) .Call(Csetcharvec, names(txt), 2L, "") # fixes bug #4839
fun = txt[[2L]]
if (is.call(fun) && fun[[1L]]=="function") {
# Fix for #2381: added SDenv$.SD to 'eval' to take care of cases like: lapply(.SD, function(x) weighted.mean(x, bla)) where "bla" is a column in DT
# http://stackoverflow.com/questions/13441868/data-table-and-stratified-means
# adding this does not compromise in speed (that is, not any lesser than without SDenv$.SD)
# replaced SDenv$.SD to SDenv to deal with Bug #5007 reported by Ricardo (Nice catch!)
thisfun = paste0("..FUN", funi) # Fix for #985
assign(thisfun,eval(fun, SDenv, SDenv), SDenv) # to avoid creating function() for each column of .SD
lockBinding(thisfun,SDenv)
txt[[1L]] = as.name(thisfun)
} else {
if (is.character(fun)) fun = as.name(fun)
txt[[1L]] = fun
}
ans = vector("list",length(ansvarsnew)+1L)
ans[[1L]] = as.name("list")
for (ii in seq_along(ansvarsnew)) {
txt[[2L]] = as.name(ansvarsnew[ii])
ans[[ii+1L]] = as.call(txt)
}
jsub = as.call(ans) # important no names here
jvnames = ansvarsnew # but here instead
list(jsub, jvnames)
# It may seem inefficient to constuct a potentially long expression. But, consider calling
# lapply 100000 times. The C code inside lapply does the LCONS stuff anyway, every time it
# is called, involving small memory allocations.
# The R level lapply calls as.list which needs a shallow copy.
# lapply also does a setAttib of names (duplicating the same names over and over again
# for each group) which is terrible for our needs. We replace all that with a
# (ok, long, but not huge in memory terms) list() which is primitive (so avoids symbol
# lookup), and the eval() inside dogroups hardly has to do anything. All this results in
# overhead minimised. We don't need to worry about the env passed to the eval in a possible
# lapply replacement, or how to pass ... efficiently to it.
# Plus we optimize lapply first, so that mean() can be optimized too as well, next.
}
if (is.name(jsub)) {
if (jsub == ".SD") {
jsub = as.call(c(quote(list), lapply(ansvarsnew, as.name)))
jvnames = ansvarsnew
}
} else if (length(as.character(jsub[[1L]])) == 1L) { # Else expect problems with <jsub[[1L]] == >
subopt = length(jsub) == 3L && jsub[[1L]] == "[" && (is.numeric(jsub[[3L]]) || jsub[[3L]] == ".N")
headopt = jsub[[1L]] == "head" || jsub[[1L]] == "tail"
firstopt = jsub[[1L]] == "first" || jsub[[1L]] == "last" # fix for #2030
if ((length(jsub) >= 2L && jsub[[2L]] == ".SD") &&
(subopt || headopt || firstopt)) {
if (headopt && length(jsub)==2L) jsub[["n"]] = 6L # head-tail n=6 when missing #3462
# optimise .SD[1] or .SD[2L]. Not sure how to test .SD[a] as to whether a is numeric/integer or a data.table, yet.
jsub = as.call(c(quote(list), lapply(ansvarsnew, function(x) { jsub[[2L]] = as.name(x); jsub })))
jvnames = ansvarsnew
} else if (jsub[[1L]]=="lapply" && jsub[[2L]]==".SD" && length(xcols)) {
deparse_ans = .massageSD(jsub)
jsub = deparse_ans[[1L]]
jvnames = deparse_ans[[2L]]
} else if (jsub[[1L]] == "c" && length(jsub) > 1L) {
# TODO, TO DO: raise the checks for 'jvnames' earlier (where jvnames is set by checking 'jsub') and set 'jvnames' already.
# FR #2722 is just about optimisation of j=c(.N, lapply(.SD, .)) that is taken care of here.
# FR #735 tries to optimise j-expressions of the form c(...) as long as ... contains
# 1) lapply(.SD, ...), 2) simply .SD or .SD[..], 3) .N, 4) list(...) and 5) functions that normally return a single value*
# On 5)* the IMPORTANT point to note is that things that are not wrapped within "list(...)" should *always*
# return length 1 output for us to optimise. Else, there's no equivalent to optimising c(...) to list(...) AFAICT.
# One issue could be that these functions (e.g., mean) can be "re-defined" by the OP to produce a length > 1 output
# Of course this is worrying too much though. If the issue comes up, we'll just remove the relevant optimisations.
# For now, we optimise all functions mentioned in 'optfuns' below.
optfuns = c("max", "min", "mean", "length", "sum", "median", "sd", "var")
is_valid = TRUE
any_SD = FALSE
jsubl = as.list.default(jsub)
oldjvnames = jvnames
jvnames = NULL # TODO: not let jvnames grow, maybe use (number of lapply(.SD, .))*lenght(ansvarsnew) + other jvars ?? not straightforward.
# Fix for #744. Don't use 'i' in for-loops. It masks the 'i' from the input!!
for (i_ in 2L:length(jsubl)) {
this = jsub[[i_]]
if (is.name(this)) { # no need to check length(this)==1L; is.name() returns single TRUE or FALSE (documented); can't have a vector of names
if (this == ".SD") { # optimise '.SD' alone
any_SD = TRUE
jsubl[[i_]] = lapply(ansvarsnew, as.name)
jvnames = c(jvnames, ansvarsnew)
} else if (this == ".N") {
# don't optimise .I in c(.SD, .I), it's length can be > 1
# only c(.SD, list(.I)) should be optimised!! .N is always length 1.
jvnames = c(jvnames, gsub("^[.]([N])$", "\\1", this))
} else {
# jvnames = c(jvnames, if (is.null(names(jsubl))) "" else names(jsubl)[i_])
is_valid=FALSE
break
}
} else if (is.call(this)) {
if (this[[1L]] == "lapply" && this[[2L]] == ".SD" && length(xcols)) {
any_SD = TRUE
deparse_ans = .massageSD(this)
funi = funi + 1L # Fix for #985
jsubl[[i_]] = as.list(deparse_ans[[1L]][-1L]) # just keep the '.' from list(.)
jvnames = c(jvnames, deparse_ans[[2L]])
} else if (this[[1L]] == "list") {
# also handle c(lapply(.SD, sum), list()) - silly, yes, but can happen
if (length(this) > 1L) {
jl__ = as.list(jsubl[[i_]])[-1L] # just keep the '.' from list(.)
jn__ = if (is.null(names(jl__))) rep("", length(jl__)) else names(jl__)
idx = unlist(lapply(jl__, function(x) is.name(x) && x == ".I"))
if (any(idx)) jn__[idx & (jn__ == "")] = "I"
jvnames = c(jvnames, jn__)
jsubl[[i_]] = jl__
}
} else if (is.call(this) && length(this) > 1L && as.character(this[[1L]]) %chin% optfuns) {
jvnames = c(jvnames, if (is.null(names(jsubl))) "" else names(jsubl)[i_])
} else if ( length(this) == 3L && (this[[1L]] == "[" || this[[1L]] == "head") &&
this[[2L]] == ".SD" && (is.numeric(this[[3L]]) || this[[3L]] == ".N") ) {
# optimise .SD[1] or .SD[2L]. Not sure how to test .SD[a] as to whether a is numeric/integer or a data.table, yet.
any_SD = TRUE
jsubl[[i_]] = lapply(ansvarsnew, function(x) { this[[2L]] = as.name(x); this })
jvnames = c(jvnames, ansvarsnew)
} else if (any(all.vars(this) == ".SD")) {
# TODO, TO DO: revisit complex cases (as illustrated below)
# complex cases like DT[, c(.SD[x>1], .SD[J(.)], c(.SD), a + .SD, lapply(.SD, sum)), by=grp]
# hard to optimise such cases (+ difficulty in counting exact columns and therefore names). revert back to no optimisation.
is_valid=FALSE
break
} else { # just to be sure that any other case (I've overlooked) runs smoothly, without optimisation
# TO DO, TODO: maybe a message/warning here so that we can catch the overlooked cases, if any?
is_valid=FALSE
break
}
} else {
is_valid = FALSE
break
}
}
if (!is_valid || !any_SD) { # restore if c(...) doesn't contain lapply(.SD, ..) or if it's just invalid
jvnames = oldjvnames # reset jvnames
jsub = oldjsub # reset jsub
jsubl = as.list.default(jsubl) # reset jsubl
} else {
setattr(jsubl, 'names', NULL)
jsub = as.call(unlist(jsubl, use.names=FALSE))
jsub[[1L]] = quote(list)
}
}
}
if (verbose) {
if (!identical(oldjsub, jsub))
cat("lapply optimization changed j from '",deparse(oldjsub),"' to '",deparse(jsub,width.cutoff=200L),"'\n",sep="")
else
cat("lapply optimization is on, j unchanged as '",deparse(jsub,width.cutoff=200L),"'\n",sep="")
}
dotN <- function(x) is.name(x) && x == ".N" # For #5760
# FR #971, GForce kicks in on all subsets, no joins yet. Although joins could work with
# nomatch=0L even now.. but not switching it on yet, will deal it separately.
if (getOption("datatable.optimize")>=2 && !is.data.table(i) && !byjoin && length(f__) && !length(lhs)) {
if (!length(ansvars) && !use.I) {
GForce = FALSE
if ( (is.name(jsub) && jsub == ".N") || (is.call(jsub) && length(jsub)==2L && length(as.character(jsub[[1L]])) && as.character(jsub[[1L]])[1L] == "list" && length(as.character(jsub[[2L]])) && as.character(jsub[[2L]])[1L] == ".N") ) {
GForce = TRUE
if (verbose) cat("GForce optimized j to '",deparse(jsub,width.cutoff=200L),"'\n",sep="")
}
} else {
# Apply GForce
gfuns = c("sum", "prod", "mean", "median", "var", "sd", ".N", "min", "max", "head", "last", "first", "tail", "[") # added .N for #5760
.ok <- function(q) {
if (dotN(q)) return(TRUE) # For #5760
# run GForce for simple f(x) calls and f(x, na.rm = TRUE)-like calls where x is a column of .SD
# is.symbol() is for #1369, #1974 and #2949
if (!(is.call(q) && is.symbol(q[[1L]]) && is.symbol(q[[2L]]) && (q1c <- as.character(q[[1L]])) %chin% gfuns)) return(FALSE)
if (!(q2c<-as.character(q[[2L]])) %chin% names(SDenv$.SDall) && q2c!=".I") return(FALSE) # 875
if ((length(q)==2L || identical("na",substring(names(q)[3L], 1L, 2L))) && (!q1c %chin% c("head","tail"))) return(TRUE)
# ... head-tail uses default value n=6 which as of now should not go gforce ^^
# otherwise there must be three arguments, and only in two cases:
# 1) head/tail(x, 1) or 2) x[n], n>0
length(q)==3L && length(q3 <- q[[3L]])==1L && is.numeric(q3) &&
( (q1c %chin% c("head", "tail") && q3==1L) || (q1c == "[" && q3>0L) )
}
if (jsub[[1L]]=="list") {
GForce = TRUE
for (ii in seq_along(jsub)[-1L]) if (!.ok(jsub[[ii]])) GForce = FALSE
} else GForce = .ok(jsub)
if (GForce) {
if (jsub[[1L]]=="list")
for (ii in seq_along(jsub)[-1L]) {
if (dotN(jsub[[ii]])) next; # For #5760
jsub[[ii]][[1L]] = as.name(paste0("g", jsub[[ii]][[1L]]))
if (length(jsub[[ii]])==3L) jsub[[ii]][[3L]] = eval(jsub[[ii]][[3L]], parent.frame()) # tests 1187.2 & 1187.4
}
else {
jsub[[1L]] = as.name(paste0("g", jsub[[1L]]))
if (length(jsub)==3L) jsub[[3L]] = eval(jsub[[3L]], parent.frame()) # tests 1187.3 & 1187.5
}
if (verbose) cat("GForce optimized j to '",deparse(jsub,width.cutoff=200L),"'\n",sep="")
} else if (verbose) cat("GForce is on, left j unchanged\n");
}
}
if (!GForce && !is.name(jsub)) {
# Still do the old speedup for mean, for now
nomeanopt=FALSE # to be set by .optmean() using <<- inside it
oldjsub = jsub
if (jsub[[1L]]=="list") {
for (ii in seq_along(jsub)[-1L]) {
this_jsub = jsub[[ii]]
if (dotN(this_jsub)) next; # For #5760
# Addressing #1369, #2949 and #1974. Added is.symbol() check to handle cases where expanded function definition is used insead of function names. #1369 results in (function(x) sum(x)) as jsub[[.]] from dcast.data.table.
if (is.call(this_jsub) && is.symbol(this_jsub[[1L]]) && this_jsub[[1L]]=="mean")
jsub[[ii]] = .optmean(this_jsub)
}
} else if (jsub[[1L]]=="mean") {
jsub = .optmean(jsub)
}
if (nomeanopt) {
warning("Unable to optimize call to mean() and could be very slow. You must name 'na.rm' like that otherwise if you do mean(x,TRUE) the TRUE is taken to mean 'trim' which is the 2nd argument of mean. 'trim' is not yet optimized.",immediate.=TRUE)
}
if (verbose) {
if (!identical(oldjsub, jsub))
cat("Old mean optimization changed j from '",deparse(oldjsub),"' to '",deparse(jsub,width.cutoff=200),"'\n",sep="")
else
cat("Old mean optimization is on, left j unchanged.\n")
}
assign("Cfastmean", Cfastmean, SDenv)
# Old comments still here for now ...
# Here in case nomeanopt=TRUE or some calls to mean weren't detected somehow. Better but still slow.
# Maybe change to :
# assign("mean", fastmean, SDenv) # neater than the hard work above, but slower
# when fastmean can do trim.
}
} else if (verbose) {
if (getOption("datatable.optimize")<1) cat("All optimizations are turned off\n")
else cat("Optimization is on but left j unchanged (single plain symbol): '",deparse(jsub,width.cutoff=200),"'\n",sep="")
}
if (byjoin) {
groups = i
grpcols = leftcols # 'leftcols' are the columns in i involved in the join (either head of key(i) or head along i)
jiscols = chmatch(jisvars,names(i)) # integer() if there are no jisvars (usually there aren't, advanced feature)
xjiscols = chmatch(xjisvars, names(x))
SDenv$.xSD = x[min(nrow(i), 1L), xjisvars, with=FALSE]
if (!missing(on)) o__ = xo else o__ = integer(0L)
} else {
groups = byval
grpcols = seq_along(byval)
jiscols = NULL # NULL rather than integer() is used in C to know when using by
xjiscols = NULL
}
lockBinding(".xSD", SDenv)
grporder = o__
# for #971, added !GForce. if (GForce) we do it much more (memory) efficiently than subset of order vector below.
if (length(irows) && !isTRUE(irows) && !GForce) {
# any zeros in irows were removed by convertNegAndZeroIdx earlier above; no need to check for zeros again. Test 1058-1061 check case #2758.
if (length(o__) && length(irows)!=length(o__)) stop("Internal error: length(irows)!=length(o__)") # nocov
o__ = if (length(o__)) irows[o__] # better do this once up front (even though another alloc) than deep repeated branch in dogroups.c
else irows
} # else grporder is left bound to same o__ memory (no cost of copy)
if (is.null(lhs)) cols=NULL
if (!length(f__)) {
# for consistency of empty case in test 184
f__=len__=0L
}
if (verbose) {last.started.at=proc.time();cat("Making each group and running j (GForce ",GForce,") ... ",sep="");flush.console()}
if (GForce) {
thisEnv = new.env() # not parent=parent.frame() so that gsum is found
for (ii in ansvars) assign(ii, x[[ii]], thisEnv)
assign(".N", len__, thisEnv) # For #5760
#fix for #1683
if (use.I) assign(".I", seq_len(nrow(x)), thisEnv)
ans = gforce(thisEnv, jsub, o__, f__, len__, irows) # irows needed for #971.
gi = if (length(o__)) o__[f__] else f__
g = lapply(grpcols, function(i) groups[[i]][gi])
ans = c(g, ans)
} else {
ans = .Call(Cdogroups, x, xcols, groups, grpcols, jiscols, xjiscols, grporder, o__, f__, len__, jsub, SDenv, cols, newnames, !missing(on), verbose)
}
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
# TO DO: xrows would be a better name for irows: irows means the rows of x that i joins to
# Grouping by i: icols the joins columns (might not need), isdcols (the non join i and used by j), all __ are length x
# Grouping by by: i is by val, icols NULL, o__ may be subset of x, f__ points to o__ (or x if !length o__)
# TO DO: setkey could mark the key whether it is unique or not.
if (!is.null(lhs)) {
if (any(names(x)[cols] %chin% key(x)))
setkey(x,NULL)
# fixes #1479. Take care of secondary indices, TODO: cleaner way of doing this
attrs = attr(x, 'index')
skeys = names(attributes(attrs))
if (!is.null(skeys)) {
hits = unlist(lapply(paste0("__", names(x)[cols]), function(x) grep(x, skeys, fixed = TRUE)))
hits = skeys[unique(hits)]
for (i in seq_along(hits)) setattr(attrs, hits[i], NULL) # does by reference
}
if (keyby) {
cnames = as.character(bysubl)[-1L]
cnames = gsub('^`|`$', '', cnames) # the wrapping backticks that were added above can be removed now, #3378
if (all(cnames %chin% names(x))) {
if (verbose) {last.started.at=proc.time();cat("setkey() after the := with keyby= ... ");flush.console()}
setkeyv(x,cnames) # TO DO: setkey before grouping to get memcpy benefit.
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
}
else warning(":= keyby not straightforward character column names or list() of column names, treating as a by:",paste(cnames,collapse=","),"\n")
}
return(suppPrint(x))
}
if (is.null(ans)) {
ans = as.data.table.list(lapply(groups,"[",0L)) # side-effects only such as test 168
setnames(ans,seq_along(bynames),bynames) # TO DO: why doesn't groups have bynames in the first place?
return(ans)
}
setattr(ans,"row.names",.set_row_names(length(ans[[1L]])))
setattr(ans,"class",class(x)) # fix for #5296
if (is.null(names(ans))) {
# Efficiency gain of dropping names has been successful. Ordinarily this will run.
if (is.null(jvnames)) jvnames = character(length(ans)-length(bynames))
if (length(bynames)+length(jvnames)!=length(ans))
stop("Internal error: jvnames is length ",length(jvnames), " but ans is ",length(ans)," and bynames is ", length(bynames)) # nocov
ww = which(jvnames=="")
if (any(ww)) jvnames[ww] = paste0("V",ww)
setattr(ans, "names", c(bynames, jvnames))
} else {
setnames(ans,seq_along(bynames),bynames) # TO DO: reinvestigate bynames flowing from dogroups here and simplify
}
if (byjoin && keyby && !bysameorder) {
if (verbose) {last.started.at=proc.time();cat("setkey() afterwards for keyby=.EACHI ... ");flush.console()}
setkeyv(ans,names(ans)[seq_along(byval)])
if (verbose) {cat(timetaken(last.started.at),"\n"); flush.console()}
} else if (keyby || (haskey(x) && bysameorder && (byjoin || (length(allbyvars) && identical(allbyvars,head(key(x),length(allbyvars))))))) {
setattr(ans,"sorted",names(ans)[seq_along(grpcols)])
}
alloc.col(ans) # TODO: overallocate in dogroups in the first place and remove this line
}
.optmean <- function(expr) { # called by optimization of j inside [.data.table only. Outside for a small speed advantage.
if (length(expr)==2L) # no parameters passed to mean, so defaults of trim=0 and na.rm=FALSE
return(call(".External",quote(Cfastmean),expr[[2L]], FALSE))
# return(call(".Internal",expr)) # slightly faster than .External, but R now blocks .Internal in coerce.c from apx Sep 2012
if (length(expr)==3L && identical("na",substring(names(expr)[3L], 1L, 2L))) # one parameter passed to mean()
return(call(".External",quote(Cfastmean),expr[[2L]], expr[[3L]])) # faster than .Call
assign("nomeanopt",TRUE,parent.frame())
expr # e.g. trim is not optimized, just na.rm
}
# [[.data.frame is now dispatched due to inheritance.
# The code below tried to avoid that but made things
# very slow (462 times faster down to 1 in the timings test).
# TO DO. Reintroduce velow but dispatch straight to
# .C("do_subset2") or better. Tests 604-608 test
# that this doesn't regress.
#"[[.data.table" <- function(x,...) {
# if (!cedta()) return(`[[.data.frame`(x,...))
# .subset2(x,...)
# #class(x)=NULL # awful, copy
# #x[[...]]
#}
#"[[<-.data.table" <- function(x,i,j,value) {
# if (!cedta()) return(`[[<-.data.frame`(x,i,j,value))
# if (!missing(j)) stop("[[i,j]] assignment not available in data.table, put assignment(s) in [i,{...}] instead, more powerful")
# cl = oldClass(x) # [[<-.data.frame uses oldClass rather than class, don't know why but we'll follow suit
# class(x) = NULL
# x[[i]] = value
# class(x) = cl
# x
#}
as.matrix.data.table <- function(x, rownames=NULL, rownames.value=NULL, ...) {
# rownames = the rownames column (most common usage)
if (!is.null(rownames)) {
if (!is.null(rownames.value)) stop("rownames and rownames.value cannot both be used at the same time")
if (length(rownames)>1L) {
# TODO in future as warned in NEWS for 1.11.6:
# warning("length(rownames)>1 is deprecated. Please use rownames.value= instead")
if (length(rownames)!=nrow(x))
stop("length(rownames)==", length(rownames), " but nrow(DT)==", nrow(x),
". The rownames argument specifies a single column name or number. Consider rownames.value= instead.")
rownames.value = rownames
rownames = NULL
} else if (length(rownames)==0L) {
stop("length(rownames)==0 but should be a single column name or number, or NULL")
} else {
if (isTRUE(rownames)) {
if (length(key(x))>1L) {
warning("rownames is TRUE but key has multiple columns ",
brackify(key(x)), "; taking first column x[,1] as rownames")
}
rownames = if (length(key(x))==1L) chmatch(key(x),names(x)) else 1L
}
else if (is.logical(rownames) || is.na(rownames)) {
# FALSE, NA, NA_character_ all mean the same as NULL
rownames = NULL
}
else if (is.character(rownames)) {
w = chmatch(rownames, names(x))
if (is.na(w)) stop("'", rownames, "' is not a column of x")
rownames = w
}
else { # rownames is a column number already
rownames <- as.integer(rownames)
if (is.na(rownames) || rownames<1L || rownames>ncol(x))
stop("as.integer(rownames)==", rownames,
" which is outside the column number range [1,ncol=", ncol(x), "].")
}
}
} else if (!is.null(rownames.value)) {
if (length(rownames.value)!=nrow(x))
stop("length(rownames.value)==", length(rownames.value),
" but should be nrow(x)==", nrow(x))
}
if (!is.null(rownames)) {
# extract that column and drop it.
rownames.value <- x[[rownames]]
dm <- dim(x) - c(0, 1)
cn <- names(x)[-rownames]
X <- x[, .SD, .SDcols = cn]
} else {
dm <- dim(x)
cn <- names(x)
X <- x
}
if (any(dm == 0L))
return(array(NA, dim = dm, dimnames = list(rownames.value, cn)))
p <- dm[2L]
n <- dm[1L]
collabs <- as.list(cn)
class(X) <- NULL
non.numeric <- non.atomic <- FALSE
all.logical <- TRUE
for (j in seq_len(p)) {
if (is.ff(X[[j]])) X[[j]] <- X[[j]][] # to bring the ff into memory, since we need to create a matrix in memory
xj <- X[[j]]
if (length(dj <- dim(xj)) == 2L && dj[2L] > 1L) {
if (inherits(xj, "data.table"))
xj <- X[[j]] <- as.matrix(X[[j]])
dnj <- dimnames(xj)[[2L]]
collabs[[j]] <- paste(collabs[[j]], if (length(dnj) >
0L)
dnj
else seq_len(dj[2L]), sep = ".")
}
if (!is.logical(xj))
all.logical <- FALSE
if (length(levels(xj)) > 0L || !(is.numeric(xj) || is.complex(xj) || is.logical(xj)) ||
(!is.null(cl <- attr(xj, "class")) && any(cl %chin%
c("Date", "POSIXct", "POSIXlt"))))
non.numeric <- TRUE
if (!is.atomic(xj))
non.atomic <- TRUE
}
if (non.atomic) {
for (j in seq_len(p)) {
xj <- X[[j]]
if (is.recursive(xj)) { }
else X[[j]] <- as.list(as.vector(xj))
}
}
else if (all.logical) { }
else if (non.numeric) {
for (j in seq_len(p)) {
if (is.character(X[[j]])) next
xj <- X[[j]]
miss <- is.na(xj)
xj <- if (length(levels(xj))) as.vector(xj) else format(xj)
is.na(xj) <- miss
X[[j]] <- xj
}
}
X <- unlist(X, recursive = FALSE, use.names = FALSE)
dim(X) <- c(n, length(X)/n)
dimnames(X) <- list(rownames.value, unlist(collabs, use.names = FALSE))
X
}
# bug #2375. fixed. same as head.data.frame and tail.data.frame to deal with negative indices
head.data.table <- function(x, n=6L, ...) {
if (!cedta()) return(NextMethod())
stopifnot(length(n) == 1L)
i = seq_len(if (n<0L) max(nrow(x)+n, 0L) else min(n,nrow(x)))
x[i, , ]
}
tail.data.table <- function(x, n=6L, ...) {
if (!cedta()) return(NextMethod())
stopifnot(length(n) == 1L)
n <- if (n<0L) max(nrow(x) + n, 0L) else min(n, nrow(x))
i = seq.int(to=nrow(x), length.out=n)
x[i]
}
"[<-.data.table" <- function (x, i, j, value) {
# [<- is provided for consistency, but := is preferred as it allows by group and by reference to subsets of columns
# with no copy of the (very large, say 10GB) columns at all. := is like an UPDATE in SQL and we like and want two symbols to change.
if (!cedta()) {
x = if (nargs()<4L) `[<-.data.frame`(x, i, value=value)
else `[<-.data.frame`(x, i, j, value)
return(alloc.col(x)) # over-allocate (again). Avoid all this by using :=.
}
# TO DO: warning("Please use DT[i,j:=value] syntax instead of DT[i,j]<-value, for efficiency. See ?':='")
if (!missing(i)) {
isub=substitute(i)
i = eval(.massagei(isub), x, parent.frame())
if (is.matrix(i)) {
if (!missing(j)) stop("When i is a matrix in DT[i]<-value syntax, it doesn't make sense to provide j")
x = `[<-.data.frame`(x, i, value=value)
return(alloc.col(x))
}
i = x[i, which=TRUE]
# Tried adding ... after value above, and passing ... in here (e.g. for mult="first") but R CMD check
# then gives "The argument of a replacement function which corresponds to the right hand side must be
# named 'value'". So, users have to use := for that.
} else i = NULL # meaning (to C code) all rows, without allocating 1L:nrow(x) vector
if (missing(j)) j=names(x)
if (!is.atomic(j)) stop("j must be an atomic vector, see ?is.atomic")
if (anyNA(j)) stop("NA in j")
if (is.character(j)) {
newnames = setdiff(j,names(x))
cols = as.integer(chmatch(j, c(names(x),newnames)))
# We can now mix existing columns and new columns
} else {
if (!is.numeric(j)) stop("j must be vector of column name or positions")
if (any(j>ncol(x))) stop("Attempt to assign to column position greater than ncol(x). Create the column by name, instead. This logic intends to catch (most likely) user errors.")
cols = as.integer(j) # for convenience e.g. to convert 1 to 1L
newnames = NULL
}
reinstatekey=NULL
if (haskey(x) && identical(key(x),key(value)) &&
identical(names(x),names(value)) &&
is.sorted(i) &&
identical(substitute(x),quote(`*tmp*`))) {
# DT["a",]$y <- 1.1 winds up creating `*tmp*` subset of rows and assigning _all_ the columns into x and
# over-writing the key columns with the same value (not just the single 'y' column).
# That isn't good for speed; it's an R thing. Solution is to use := instead to avoid all this, but user
# expects key to be retained in this case because _he_ didn't assign to a key column (the internal base R
# code did).
reinstatekey=key(x)
}
if (!selfrefok(x) || truelength(x) < ncol(x)+length(newnames)) {
x = alloc.col(x,length(x)+length(newnames)) # because [<- copies via *tmp* and main/duplicate.c copies at length but copies truelength over too
# search for one other .Call to assign in [.data.table to see how it differs
}
verbose=getOption("datatable.verbose")
x = .Call(Cassign,copy(x),i,cols,newnames,value,verbose) # From 3.1.0, DF[2,"b"] = 7 no longer copies DF$a (so in this [<-.data.table method we need to copy)
alloc.col(x) # can maybe avoid this realloc, but this is (slow) [<- anyway, so just be safe.
if (length(reinstatekey)) setkeyv(x,reinstatekey)
invisible(x)
# no copy at all if user calls directly; i.e. `[<-.data.table`(x,i,j,value)
# or uses data.table := syntax; i.e. DT[i,j:=value]
# but, there is one copy by R in [<- dispatch to `*tmp*`; i.e. DT[i,j]<-value. *Update: not from R > 3.0.2, yay*
# That copy is via main/duplicate.c which preserves truelength but copies length amount. Hence alloc.col(x,length(x)).
# No warn passed to assign here because we know it'll be copied via *tmp*.
# := allows subassign to a column with no copy of the column at all, and by group, etc.
}
"$<-.data.table" <- function(x, name, value) {
if (!cedta()) {
ans = `$<-.data.frame`(x, name, value)
return(alloc.col(ans)) # over-allocate (again)
}
x = copy(x)
`[<-.data.table`(x,j=name,value=value) # important i is missing here
}
as.data.frame.data.table <- function(x, ...)
{
ans = copy(x)
setattr(ans,"row.names",.set_row_names(nrow(x))) # since R 2.4.0, data.frames can have non-character row names
setattr(ans,"class","data.frame")
setattr(ans,"sorted",NULL) # remove so if you convert to df, do something, and convert back, it is not sorted
setattr(ans,".internal.selfref",NULL)
# leave tl intact, no harm,
ans
}
as.list.data.table <- function(x, ...) {
# Similar to as.list.data.frame in base. Although a data.table/frame is a list, too, it may be
# being coerced to raw list type (by calling code) so that "[" and "[[" work in their raw list form,
# such as lapply does for data.frame. So we do have to remove the class attributes (and thus shallow
# copy is almost instant way to achieve that, without risking compatibility).
#if (sys.call(-2L)[[1L]]=="lapply")
# return(x)
ans = shallow(x)
setattr(ans, "class", NULL)
setattr(ans, "row.names", NULL)
setattr(ans, "sorted", NULL)
setattr(ans,".internal.selfref", NULL) # needed to pass S4 tests for example
ans
}
dimnames.data.table <- function(x) {
if (!cedta()) {
if (!inherits(x, "data.frame"))
stop("data.table inherits from data.frame (from v1.5), but this data.table does not. Has it been created manually (e.g. by using 'structure' rather than 'data.table') or saved to disk using a prior version of data.table?")
return(`dimnames.data.frame`(x))
}
list(NULL, names(x))
}
"dimnames<-.data.table" = function (x, value) # so that can do colnames(dt)=<..> as well as names(dt)=<..>
{
if (!cedta()) return(`dimnames<-.data.frame`(x,value)) # nocov ; will drop key but names<-.data.table (below) is more common usage and does retain the key
if (!is.list(value) || length(value) != 2L) stop("attempting to assign invalid object to dimnames of a data.table")
if (!is.null(value[[1L]])) stop("data.tables do not have rownames")
if (ncol(x) != length(value[[2L]])) stop("Can't assign ", length(value[[2L]]), " colnames to a ", ncol(x), "-column data.table")
setnames(x,as.character(value[[2L]]))
x # this returned value is now shallow copied by R 3.1.0 via *tmp*. A very welcome change.
}
"names<-.data.table" <- function(x,value)
{
# When non data.table aware packages change names, we'd like to maintain the key.
# If call is names(DT)[2]="newname", R will call this names<-.data.table function (notice no i) with 'value' already prepared to be same length as ncol
x = shallow(x) # `names<-` should not modify by reference. Related to #1015, #476 and #825. Needed for R v3.1.0+. TO DO: revisit
if (is.null(value))
setattr(x,"names",NULL) # e.g. plyr::melt() calls base::unname()
else
setnames(x,value)
x # this returned value is now shallow copied by R 3.1.0 via *tmp*. A very welcome change.
}
within.data.table <- function (data, expr, ...)
# basically within.list but retains key (if any)
# will be slower than using := or a regular query (see ?within for further info).
{
if (!cedta()) return(NextMethod())
parent <- parent.frame()
e <- evalq(environment(), data, parent)
eval(substitute(expr), e) # might (and it's known that some user code does) contain rm()
l <- as.list(e)
l <- l[!vapply_1b(l, is.null)]
nD <- length(del <- setdiff(names(data), (nl <- names(l))))
ans = copy(data)
if (length(nl)) ans[,nl] <- l
if (nD) ans[,del] <- NULL
if (haskey(data) && all(key(data) %chin% names(ans))) {
x = TRUE
for (i in key(data)) {
x = identical(data[[i]],ans[[i]])
if (!x) break
}
if (x) setattr(ans,"sorted",key(data))
}
ans
}
transform.data.table <- function (`_data`, ...)
# basically transform.data.frame with data.table instead of data.frame, and retains key
{
if (!cedta()) return(NextMethod())
e <- eval(substitute(list(...)), `_data`, parent.frame())
tags <- names(e)
inx <- chmatch(tags, names(`_data`))
matched <- !is.na(inx)
if (any(matched)) {
if (isTRUE(attr(`_data`, ".data.table.locked", TRUE))) setattr(`_data`, ".data.table.locked", NULL) # fix for #1641
`_data`[,inx[matched]] <- e[matched]
`_data` <- data.table(`_data`)
}
if (!all(matched)) {
ans <- do.call("data.table", c(list(`_data`), e[!matched]))
} else {
ans <- `_data`
}
key.cols <- key(`_data`)
if (!any(tags %chin% key.cols)) {
setattr(ans, "sorted", key.cols)
}
ans
}
subset.data.table <- function (x, subset, select, ...)
{
key.cols <- key(x)
if (missing(subset)) {
r <- TRUE
} else {
e <- substitute(subset)
r <- eval(e, x, parent.frame())
if (!is.logical(r))
stop("'subset' must evaluate to logical")
r <- r & !is.na(r)
}
if (missing(select)) {
vars <- seq_len(ncol(x))
} else {
nl <- as.list(seq_len(ncol(x)))
setattr(nl,"names",names(x))
vars <- eval(substitute(select), nl, parent.frame()) # e.g. select=colF:colP
# #891 fix - don't convert numeric vars to column names - will break when there are duplicate columns
key.cols <- intersect(key.cols, names(x)[vars]) ## Only keep key.columns found in the select clause
}
ans <- x[r, vars, with = FALSE]
if (nrow(ans) > 0L) {
if (!missing(select) && length(key.cols)) {
## Set the key on the returned data.table as long as the key
## columns that "remain" are the same as the original, or a
## prefix of it.
is.prefix <- all(key(x)[seq_len(length(key.cols))] == key.cols)
if (is.prefix) {
setattr(ans, "sorted", key.cols)
}
}
} else {
setkey(ans,NULL)
}
ans
}
# Equivalent of 'rowSums(is.na(dt) > 0L)' but much faster and memory efficient.
# Also called "complete.cases" in base. Unfortunately it's not a S3 generic.
# Also handles bit64::integer64. TODO: export this?
# For internal use only. 'by' requires integer input. No argument checks here yet.
is_na <- function(x, by=seq_along(x)) .Call(Cdt_na, x, by)
any_na <- function(x, by=seq_along(x)) .Call(CanyNA, x, by)
na.omit.data.table <- function (object, cols = seq_along(object), invert = FALSE, ...) {
# compare to stats:::na.omit.data.frame
if (!cedta()) return(NextMethod())
if ( !missing(invert) && is.na(as.logical(invert)) )
stop("Argument 'invert' must be logical TRUE/FALSE")
if (is.character(cols)) {
old = cols
cols = chmatch(cols, names(object), nomatch=0L)
if (any(idx <- cols==0L))
stop("Column", if (sum(idx)>1L) "s " else " ", brackify(old[idx]), if (sum(idx)>1L) " don't" else " doesn't", " exist in the input data.table")
}
cols = as.integer(cols)
ix = .Call(Cdt_na, object, cols)
# forgot about invert with no NA case, #2660
if (invert) {
if (all(ix))
object
else
.Call(CsubsetDT, object, which_(ix, bool = TRUE), seq_along(object))
} else {
if (any(ix))
.Call(CsubsetDT, object, which_(ix, bool = FALSE), seq_along(object))
else
object
}
}
which_ <- function(x, bool = TRUE) {
# fix for #1467, quotes result in "not resolved in current namespace" error
.Call(Cwhichwrapper, x, bool)
}
is.na.data.table <- function (x) {
if (!cedta()) return(`is.na.data.frame`(x))
do.call("cbind", lapply(x, "is.na"))
}
# not longer needed as inherits ...
# t.data.table <- t.data.frame
# Math.data.table <- Math.data.frame
# summary.data.table <- summary.data.frame
Ops.data.table <- function(e1, e2 = NULL)
{
ans = NextMethod()
if (cedta() && is.data.frame(ans))
ans = as.data.table(ans)
ans
}
split.data.table <- function(x, f, drop = FALSE, by, sorted = FALSE, keep.by = TRUE, flatten = TRUE, ..., verbose = getOption("datatable.verbose")) {
if (!is.data.table(x)) stop("x argument must be a data.table")
stopifnot(is.logical(drop), is.logical(sorted), is.logical(keep.by), is.logical(flatten))
# split data.frame way, using `f` and not `by` argument
if (!missing(f)) {
if (!length(f) && nrow(x))
stop("group length is 0 but data nrow > 0")
if (!missing(by))
stop("passing 'f' argument together with 'by' is not allowed, use 'by' when split by column in data.table and 'f' when split by external factor")
# same as split.data.frame - handling all exceptions, factor orders etc, in a single stream of processing was a nightmare in factor and drop consistency
return(lapply(split(x = seq_len(nrow(x)), f = f, drop = drop, ...), function(ind) x[ind]))
}
if (missing(by)) stop("Either 'by' or 'f' argument must be supplied")
# check reserved column names during processing
if (".ll.tech.split" %chin% names(x)) stop("Column '.ll.tech.split' is reserved for split.data.table processing")
if (".nm.tech.split" %chin% by) stop("Column '.nm.tech.split' is reserved for split.data.table processing")
if (!all(by %chin% names(x))) stop("Argument 'by' must refer to column names in x")
if (!all(by.atomic <- vapply_1b(by, function(.by) is.atomic(x[[.by]])))) stop("Argument 'by' must refer only to atomic-type columns, but the following columns are non-atomic: ", brackify(by[!by.atomic]))
# list of data.tables (flatten) or list of lists of ... data.tables
make.levels = function(x, cols, sorted) {
by.order = if (!sorted) x[, funique(.SD), .SDcols=cols] # remember order of data, only when not sorted=FALSE
ul = lapply(setNames(cols, nm=cols), function(col) {
if (!is.factor(x[[col]])) unique(x[[col]]) else {
.x_lev = levels(x[[col]])
#need to keep as a factor or order will be lost, #2082
factor(.x_lev, levels = .x_lev)
}
})
r = do.call("CJ", c(ul, sorted=sorted, unique=TRUE))
if (!sorted && nrow(by.order)) {
ii = r[by.order, on=cols, which=TRUE]
r = rbindlist(list(
r[ii], # original order from data
r[-ii] # empty levels at the end
))
}
r
}
.by = by[1L]
# this builds data.table call - is much more cleaner than handling each case one by one
dtq = as.list(call("[", as.name("x")))
join = FALSE
flatten_any = flatten && any(vapply_1b(by, function(col) is.factor(x[[col]])))
nested_current = !flatten && is.factor(x[[.by]])
if (!drop && (flatten_any || nested_current)) {
# create 'levs' here to avoid lexical scoping glitches, see #3151
levs = make.levels(x=x, cols=if (flatten) by else .by, sorted=sorted)
dtq[["i"]] = quote(levs)
join = TRUE
}
dtq[["j"]] = substitute(
list(.ll.tech.split=list(.expr)),
list(.expr = if (join) quote(if(.N == 0L) .SD[0L] else .SD) else as.name(".SD")) # simplify when `nomatch` accept NULL #857 ?
)
by.or.keyby = if (join) "by" else c("by"[!sorted], "keyby"[sorted])[1L]
dtq[[by.or.keyby]] = substitute( # retain order, for `join` and `sorted` it will use order of `i` data.table instead of `keyby`.
.expr,
list(.expr = if(join) {as.name(".EACHI")} else if (flatten) by else .by)
)
dtq[[".SDcols"]] = if (keep.by) names(x) else setdiff(names(x), if (flatten) by else .by)
if (join) dtq[["on"]] = if (flatten) by else .by
dtq = as.call(dtq)
if (isTRUE(verbose)) cat("Processing split.data.table with: ", deparse(dtq, width.cutoff=500L), "\n", sep="")
tmp = eval(dtq)
# add names on list
setattr(ll <- tmp$.ll.tech.split,
"names",
as.character(
if (!flatten) tmp[[.by]] else tmp[, list(.nm.tech.split=paste(unlist(lapply(.SD, as.character)), collapse = ".")), by=by, .SDcols=by]$.nm.tech.split
))
# handle nested split
if (flatten || length(by) == 1L) {
lapply(lapply(ll, setattr, '.data.table.locked', NULL), setDT)
# alloc.col could handle DT in list as done in: c9c4ff80bdd4c600b0c4eff23b207d53677176bd
} else if (length(by) > 1L) {
lapply(ll, split.data.table, drop=drop, by=by[-1L], sorted=sorted, keep.by=keep.by, flatten=flatten)
}
}
# TO DO, add more warnings e.g. for by.data.table(), telling user what the data.table syntax is but letting them dispatch to data.frame if they want
copy <- function(x) {
newx = .Call(Ccopy,x) # copies at length but R's duplicate() also copies truelength over.
# TO DO: inside Ccopy it could reset tl to 0 or length, but no matter as selfrefok detects it
# TO DO: revisit duplicate.c in R 3.0.3 and see where it's at
if (!is.data.table(x)) {
# fix for #1476. TODO: find if a cleaner fix is possible..
if (is.list(x)) {
anydt = vapply(x, is.data.table, TRUE, USE.NAMES=FALSE)
if (sum(anydt)) {
newx[anydt] = lapply(newx[anydt], function(x) {
setattr(x, ".data.table.locked", NULL)
alloc.col(x)
})
}
}
return(newx) # e.g. in as.data.table.list() the list is copied before changing to data.table
}
setattr(newx,".data.table.locked",NULL)
alloc.col(newx)
}
point <- function(to, to_idx, from, from_idx) {
.Call(CpointWrapper, to, to_idx, from, from_idx)
}
.shallow <- function(x, cols = NULL, retain.key = FALSE, unlock = FALSE) {
isnull = is.null(cols)
if (!isnull) cols = validate(cols, x) # NULL is default = all columns
ans = .Call(Cshallowwrapper, x, cols) # copies VECSXP only
if(retain.key){
if (isnull) return(ans) # handle most frequent case first
## get correct key if cols are present
cols = names(x)[cols]
keylength <- which.first(!key(ans) %chin% cols) - 1L
if (is.na(keylength)) keylength <- length(key(ans))
if (!keylength) {
setattr(ans, "sorted", NULL) ## no key remaining
} else {
setattr(ans, "sorted", head(key(ans), keylength)) ## keep what can be kept
}
## take care of attributes.
indices <- names(attributes(attr(ans, "index")))
for(index in indices) {
indexcols <- strsplit(index, split = "__")[[1L]][-1L]
indexlength <- which.first(!indexcols %chin% cols) - 1L
if (is.na(indexlength)) next ## all columns are present, nothing to be done
reducedindex <- paste0("__", indexcols[seq_len(indexlength)], collapse="") ## the columns until the first missing from the new index
if (reducedindex %chin% indices || !indexlength) {
## Either reduced index already present or no columns of the original index remain.
## Drop the original index completely
setattr(attr(ans, "index", exact = TRUE), index, NULL)
} else if(length(attr(attr(ans, "index"), index))) {
## index is not length 0. Drop it since shortening could lead to spurious reordering in discarded columns (#2336)
setattr(attr(ans, "index", exact = TRUE), index, NULL)
} else {
## rename index to reducedindex
names(attributes(attr(ans, "index")))[names(attributes(attr(ans, "index"))) == index] <- reducedindex
}
}
} else { # retain.key == FALSE
setattr(ans, "sorted", NULL)
setattr(ans, "index", NULL)
}
if (unlock) setattr(ans, '.data.table.locked', NULL)
ans
}
shallow <- function(x, cols=NULL) {
if (!is.data.table(x))
stop("x is not a data.table. Shallow copy is a copy of the vector of column pointers (only), so is only meaningful for data.table")
ans = .shallow(x, cols=cols, retain.key = TRUE)
ans
}
alloc.col <- function(DT, n=getOption("datatable.alloccol"), verbose=getOption("datatable.verbose"))
{
name = substitute(DT)
if (identical(name,quote(`*tmp*`))) stop("alloc.col attempting to modify `*tmp*`")
ans = .Call(Calloccolwrapper, DT, eval(n), verbose)
if (is.name(name)) {
name = as.character(name)
assign(name,ans,parent.frame(),inherits=TRUE)
}
.Call(Csetmutable,ans)
}
selfrefok <- function(DT,verbose=getOption("datatable.verbose")) {
.Call(Cselfrefokwrapper,DT,verbose)
}
truelength <- function(x) .Call(Ctruelength,x)
# deliberately no "truelength<-" method. alloc.col is the mechanism for that.
# settruelength() no longer need (and so removed) now that data.table depends on R 2.14.0
# which initializes tl to zero rather than leaving uninitialized.
setattr <- function(x,name,value) {
# Wrapper for setAttrib internal R function
# Sets attribute by reference (no copy)
# Named setattr (rather than setattrib) at R level to more closely resemble attr<-
# And as from 1.7.8 is made exported in NAMESPACE for use in user attributes.
# User can also call `attr<-` function directly, but that copies (maybe just when NAMED>0, which is always for data.frame, I think). See "Confused by NAMED" thread on r-devel 24 Nov 2011.
# We tend to use setattr() internally in data.table.R because often we construct a data.table and it hasn't
# got names yet. setnames() is the user interface which checks integrity and doesn't let you drop names for example.
if (name=="names" && is.data.table(x) && length(attr(x,"names")) && !is.null(value))
setnames(x,value)
# Using setnames here so that truelength of names can be retained, to carry out integrity checks such as not
# creating names longer than the number of columns of x, and to change the key, too
# For convenience so that setattr(DT,"names",allnames) works as expected without requiring a switch to setnames.
else {
ans = .Call(Csetattrib, x, name, value)
# If name=="names" and this is the first time names are assigned (e.g. in data.table()), this will be grown by alloc.col very shortly afterwards in the caller.
if (!is.null(ans)) {
warning("Input is a length=1 logical that points to the same address as R's global value. Therefore the attribute has not been set by reference, rather on a copy. You will need to assign the result back to a variable. See issue #1281.")
x = ans
}
}
# fix for #1142 - duplicated levels for factors
if (name == "levels" && is.factor(x) && anyDuplicated(value))
.Call(Csetlevels, x, (value <- as.character(value)), unique(value))
invisible(x)
}
setnames <- function(x,old,new,skip_absent=FALSE) {
# Sets by reference, maintains truelength, no copy of table at all.
# But also more convenient than names(DT)[i]="newname" because we can also do setnames(DT,"oldname","newname")
# without an onerous match() ourselves. old can be positions, too, but we encourage by name for robustness.
if (!is.data.frame(x)) stop("x is not a data.table or data.frame")
if (length(names(x)) != length(x)) stop("x is length ",length(x)," but its names are length ",length(names(x)))
stopifnot(isTRUEorFALSE(skip_absent))
if (missing(new)) {
# for setnames(DT,new); e.g., setnames(DT,c("A","B")) where ncol(DT)==2
if (!is.character(old)) stop("Passed a vector of type '",typeof(old),"'. Needs to be type 'character'.")
if (length(old) != ncol(x)) stop("Can't assign ",length(old)," names to a ",ncol(x)," column data.table")
nx <- names(x)
# note that duplicate names are permitted to be created in this usage only
if (anyNA(nx)) {
# if x somehow has some NA names, which() needs help to return them, #2475
w = which((nx != old) | (is.na(nx) & !is.na(old)))
} else {
w = which(nx != old)
}
if (!length(w)) return(invisible(x)) # no changes
new = old[w]
i = w
} else {
if (missing(old)) stop("When 'new' is provided, 'old' must be provided too")
if (!is.character(new)) stop("'new' is not a character vector")
if (is.numeric(old)) {
if (length(sgn <- unique(sign(old))) != 1L)
stop("Items of 'old' is numeric but has both +ve and -ve indices.")
tt = abs(old)<1L | abs(old)>length(x) | is.na(old)
if (any(tt)) stop("Items of 'old' either NA or outside range [1,",length(x),"]: ",paste(old[tt],collapse=","))
i = if (sgn == 1L) as.integer(old) else seq_along(x)[as.integer(old)]
if (any(duplicated(i))) stop("Some duplicates exist in 'old': ",paste(i[duplicated(i)],collapse=","))
} else {
if (!is.character(old)) stop("'old' is type ",typeof(old)," but should be integer, double or character")
if (any(duplicated(old))) stop("Some duplicates exist in 'old': ", paste(old[duplicated(old)],collapse=","))
i = chmatch(old,names(x))
if (anyNA(i)) {
if (isTRUE(skip_absent)) {
w <- old %chin% names(x)
old = old[w]
new = new[w]
i = i[w]
} else {
stop("Items of 'old' not found in column names: ",paste(old[is.na(i)],collapse=","), ". Consider skip_absent=TRUE.")
}
}
if (any(tt<-!is.na(chmatch(old,names(x)[-i])))) stop("Some items of 'old' are duplicated (ambiguous) in column names: ",paste(old[tt],collapse=","))
}
if (length(new)!=length(i)) stop("'old' is length ",length(i)," but 'new' is length ",length(new))
}
# update the key if the column name being change is in the key
m = chmatch(names(x)[i], key(x))
w = which(!is.na(m))
if (length(w))
.Call(Csetcharvec, attr(x,"sorted"), m[w], new[w])
# update secondary keys
idx = attr(x,"index")
for (k in names(attributes(idx))) {
tt = strsplit(k,split="__")[[1L]][-1L]
m = chmatch(names(x)[i], tt)
w = which(!is.na(m))
if (length(w)) {
tt[m[w]] = new[w]
newk = paste0("__",tt,collapse="")
setattr(idx, newk, attr(idx, k))
setattr(idx, k, NULL)
}
}
.Call(Csetcharvec, attr(x,"names"), as.integer(i), new)
invisible(x)
}
setcolorder <- function(x, neworder=key(x))
{
if (anyDuplicated(neworder)) stop("neworder contains duplicates")
# if (!is.data.table(x)) stop("x is not a data.table")
if (length(neworder) != length(x)) {
if (length(neworder) > length(x))
stop("neworder is length ", length(neworder),
" but x has only ", length(x), " columns.")
#if shorter than length(x), pad by the missing
# elements (checks below will catch other mistakes)
neworder = c(neworder, setdiff(if (is.character(neworder)) names(x)
else seq_along(x), neworder))
}
if (is.character(neworder)) {
if (any(duplicated(names(x)))) stop("x has some duplicated column name(s): ", paste(names(x)[duplicated(names(x))], collapse=","), ". Please remove or rename the duplicate(s) and try again.")
o = as.integer(chmatch(neworder, names(x)))
if (anyNA(o)) stop("Names in neworder not found in x: ", paste(neworder[is.na(o)], collapse=","))
} else {
if (!is.numeric(neworder)) stop("neworder is not a character or numeric vector")
o = as.integer(neworder)
m = !(o %in% seq_len(length(x)))
if (any(m)) stop("Column numbers in neworder out of bounds: ", paste(o[m], collapse=","))
}
.Call(Csetcolorder, x, o)
invisible(x)
}
set <- function(x,i=NULL,j,value) # low overhead, loopable
{
if (is.atomic(value)) {
# protect NAMED of atomic value from .Call's NAMED=2 by wrapping with list()
l = vector("list", 1L)
.Call(Csetlistelt,l,1L,value) # to avoid the copy by list() in R < 3.1.0
value = l
}
.Call(Cassign,x,i,j,NULL,value,FALSE) # verbose=FALSE for speed to avoid getOption() TO DO: somehow read getOption("datatable.verbose") from C level
invisible(x)
}
chmatch <- function(x, table, nomatch=NA_integer_)
.Call(Cchmatch, x, table, as.integer(nomatch[1L])) # [1L] to fix #1672
# chmatchdup() behaves like 'pmatch' but only the 'exact' matching part; i.e. a value in
# 'x' is matched to 'table' only once. No index will be present more than once. For example:
# chmatchdup(c("a", "a"), c("a", "a")) # 1,2 - the second 'a' in 'x' has a 2nd match in 'table'
# chmatchdup(c("a", "a"), c("a", "b")) # 1,NA - the second one doesn't 'see' the first 'a'
# chmatchdup(c("a", "a"), c("a", "a.1")) # 1,NA - this is where it differs from pmatch - we don't need the partial match.
chmatchdup <- function(x, table, nomatch=NA_integer_)
.Call(Cchmatchdup, x, table, as.integer(nomatch[1L]))
"%chin%" <- function(x, table)
.Call(Cchin, x, table) # TO DO if table has 'ul' then match to that
chorder <- function(x) {
o = forderv(x, sort=TRUE, retGrp=FALSE)
if (length(o)) o else seq_along(x)
}
chgroup <- function(x) {
# TO DO: deprecate and remove this. It's exported but doubt anyone uses it. Think the plan was to use it internally, but forderv superceded.
o = forderv(x, sort=FALSE, retGrp=TRUE)
if (length(o)) as.vector(o) else seq_along(x) # as.vector removes the attributes
}
.rbind.data.table <- function(..., use.names=TRUE, fill=FALSE, idcol=NULL) {
# See FAQ 2.23
# Called from base::rbind.data.frame
# fix for #1626.. because some packages (like psych) bind an input
# data.frame/data.table with a matrix..
l = lapply(list(...), function(x) if (is.list(x)) x else as.data.table(x))
rbindlist(l, use.names, fill, idcol)
}
rbindlist <- function(l, use.names="check", fill=FALSE, idcol=NULL) {
if (isFALSE(idcol)) { idcol = NULL }
else if (!is.null(idcol)) {
if (isTRUE(idcol)) idcol = ".id"
if (!is.character(idcol)) stop("idcol must be a logical or character vector of length 1. If logical TRUE the id column will named '.id'.")
idcol = idcol[1L]
}
miss = missing(use.names)
# more checking of use.names happens at C level; this is just minimal to massage 'check' to NA
if (identical(use.names, NA)) stop("use.names=NA invalid") # otherwise use.names=NA could creep in an usage equivalent to use.names='check'
if (identical(use.names,"check")) {
if (!miss) stop("use.names='check' cannot be used explicitly because the value 'check' is new in v1.12.2 and subject to change. It is just meant to convey default behavior. See ?rbindlist.")
use.names = NA
}
ans = .Call(Crbindlist, l, use.names, fill, idcol)
if (!length(ans)) return(null.data.table())
setDT(ans)[]
}
vecseq <- function(x,y,clamp) .Call(Cvecseq,x,y,clamp)
# .Call(Caddress, x) increments NAM() when x is vector with NAM(1). Referring object within non-primitive function is enough to increment reference.
address <- function(x) .Call(Caddress, eval(substitute(x), parent.frame()))
":=" <- function(...) stop('Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").')
setDF <- function(x, rownames=NULL) {
if (!is.list(x)) stop("setDF only accepts data.table, data.frame or list of equal length as input")
if (anyDuplicated(rownames)) stop("rownames contains duplicates")
if (is.data.table(x)) {
# copied from as.data.frame.data.table
if (is.null(rownames)) {
rn <- .set_row_names(nrow(x))
} else {
if (length(rownames) != nrow(x))
stop("rownames incorrect length; expected ", nrow(x), " names, got ", length(rownames))
rn <- rownames
}
setattr(x, "row.names", rn)
setattr(x, "class", "data.frame")
setattr(x, "sorted", NULL)
setattr(x, ".internal.selfref", NULL)
} else if (is.data.frame(x)) {
if (!is.null(rownames)) {
if (length(rownames) != nrow(x))
stop("rownames incorrect length; expected ", nrow(x), " names, got ", length(rownames))
setattr(x, "row.names", rownames)
}
x
} else {
n = vapply(x, length, 0L)
mn = max(n)
if (any(n<mn))
stop("All elements in argument 'x' to 'setDF' must be of same length")
xn = names(x)
if (is.null(xn)) {
setattr(x, "names", paste0("V",seq_len(length(x))))
} else {
idx = xn %chin% ""
if (any(idx)) {
xn[idx] = paste0("V", seq_along(which(idx)))
setattr(x, "names", xn)
}
}
if (is.null(rownames)) {
rn <- .set_row_names(mn)
} else {
if (length(rownames) != mn)
stop("rownames incorrect length; expected ", mn, " names, got ", length(rownames))
rn <- rownames
}
setattr(x,"row.names", rn)
setattr(x,"class","data.frame")
}
invisible(x)
}
setDT <- function(x, keep.rownames=FALSE, key=NULL, check.names=FALSE) {
name = substitute(x)
if (is.name(name)) {
home <- function(x, env) {
if (identical(env, emptyenv()))
stop("Cannot find symbol ", cname, call. = FALSE)
else if (exists(x, env, inherits=FALSE)) env
else home(x, parent.env(env))
}
cname = as.character(name)
envir = home(cname, parent.frame())
if (bindingIsLocked(cname, envir)) {
stop("Can not convert '", cname, "' to data.table by reference because binding is locked. It is very likely that '", cname, "' resides within a package (or an environment) that is locked to prevent modifying its variable bindings. Try copying the object to your current environment, ex: var <- copy(var) and then using setDT again.")
}
}
if (is.data.table(x)) {
# fix for #1078 and #1128, see .resetclass() for explanation.
setattr(x, 'class', .resetclass(x, 'data.table'))
if (!missing(key)) setkeyv(x, key) # fix for #1169
if (check.names) setattr(x, "names", make.names(names(x), unique=TRUE))
if (selfrefok(x) > 0) return(invisible(x)) else alloc.col(x)
} else if (is.data.frame(x)) {
rn = if (!identical(keep.rownames, FALSE)) rownames(x) else NULL
setattr(x, "row.names", .set_row_names(nrow(x)))
if (check.names) setattr(x, "names", make.names(names(x), unique=TRUE))
# fix for #1078 and #1128, see .resetclass() for explanation.
setattr(x, "class", .resetclass(x, 'data.frame'))
alloc.col(x)
if (!is.null(rn)) {
nm = c(if (is.character(keep.rownames)) keep.rownames[1L] else "rn", names(x))
x[, (nm[1L]) := rn]
setcolorder(x, nm)
}
} else if (is.null(x) || (is.list(x) && !length(x))) {
x = null.data.table()
} else if (is.list(x)) {
# copied from as.data.table.list - except removed the copy
for (i in seq_along(x)) {
if (inherits(x[[i]], "POSIXlt"))
stop("Column ", i, " is of POSIXlt type. Please convert it to POSIXct using as.POSIXct and run setDT again. We do not recommend use of POSIXlt at all because it uses 40 bytes to store one date.")
}
n = vapply(x, length, 0L)
n_range = range(n)
if (n_range[1L] != n_range[2L]) {
tbl = sort(table(n))
stop("All elements in argument 'x' to 'setDT' must be of same length, ",
"but the profile of input lengths (length:frequency) is: ",
brackify(sprintf('%s:%d', names(tbl), tbl)),
"\nThe first entry with fewer than ", n_range[2L],
" entries is ", which.max(n<n_range[2L]))
}
xn = names(x)
if (is.null(xn)) {
setattr(x, "names", paste0("V",seq_len(length(x))))
} else {
idx = xn %chin% "" # names can be NA - test 1006 caught that!
if (any(idx)) {
xn[idx] = paste0("V", seq_along(which(idx)))
setattr(x, "names", xn)
}
if (check.names) setattr(x, "names", make.names(xn, unique=TRUE))
}
setattr(x,"row.names",.set_row_names(n_range[2L]))
setattr(x,"class",c("data.table","data.frame"))
alloc.col(x)
} else {
stop("Argument 'x' to 'setDT' should be a 'list', 'data.frame' or 'data.table'")
}
if (!is.null(key)) setkeyv(x, key)
if (is.name(name)) {
name = as.character(name)
assign(name, x, parent.frame(), inherits=TRUE)
} else if (is.call(name) && (name[[1L]] == "$" || name[[1L]] == "[[") && is.name(name[[2L]])) {
# common case is call from 'lapply()'
k = eval(name[[2L]], parent.frame(), parent.frame())
if (is.list(k)) {
origj = j = if (name[[1L]] == "$") as.character(name[[3L]]) else eval(name[[3L]], parent.frame(), parent.frame())
if (length(j) == 1L) {
if (is.character(j)) {
j = match(j, names(k))
if (is.na(j))
stop("Item '", origj, "' not found in names of input list")
}
}
.Call(Csetlistelt,k,as.integer(j), x)
} else if (is.environment(k) && exists(as.character(name[[3L]]), k)) {
assign(as.character(name[[3L]]), x, k, inherits=FALSE)
}
}
.Call(CexpandAltRep, x) # issue#2866 and PR#2882
invisible(x)
}
as_list <- function(x) {
lx = vector("list", 1L)
.Call(Csetlistelt, lx, 1L, x)
lx
}
# FR #1353
rowid <- function(..., prefix=NULL) {
rowidv(list(...), prefix=prefix)
}
rowidv <- function(x, cols=seq_along(x), prefix=NULL) {
if (!is.null(prefix) && (!is.character(prefix) || length(prefix) != 1L))
stop("prefix must be NULL or a character vector of length=1.")
if (is.atomic(x)) {
if (!missing(cols) && !is.null(cols))
stop("x is a single vector, non-NULL 'cols' doesn't make sense.")
cols = 1L
x = as_list(x)
} else {
if (!length(cols))
stop("x is a list, 'cols' can not be on 0-length.")
if (is.character(cols))
cols = chmatch(cols, names(x))
cols = as.integer(cols)
}
xorder = forderv(x, by=cols, sort=FALSE, retGrp=TRUE) # speedup on char with sort=FALSE
xstart = attr(xorder, 'start')
if (!length(xorder)) xorder = seq_along(x[[1L]])
ids = .Call(Cfrank, xorder, xstart, uniqlengths(xstart, length(xorder)), "sequence")
if (!is.null(prefix))
ids = paste0(prefix, ids)
ids
}
# FR #686
rleid <- function(..., prefix=NULL) {
rleidv(list(...), prefix=prefix)
}
rleidv <- function(x, cols=seq_along(x), prefix=NULL) {
if (!is.null(prefix) && (!is.character(prefix) || length(prefix) != 1L))
stop("prefix must be NULL or a character vector of length=1.")
if (is.atomic(x)) {
if (!missing(cols) && !is.null(cols))
stop("x is a single vector, non-NULL 'cols' doesn't make sense.")
cols = 1L
x = as_list(x)
} else {
if (!length(cols))
stop("x is a list, 'cols' can not be 0-length.")
if (is.character(cols))
cols = chmatch(cols, names(x))
cols = as.integer(cols)
}
ids = .Call(Crleid, x, cols)
if (!is.null(prefix)) ids = paste0(prefix, ids)
ids
}
# GForce functions
`g[` <- function(x, n) .Call(Cgnthvalue, x, as.integer(n)) # n is of length=1 here.
ghead <- function(x, n) .Call(Cghead, x, as.integer(n)) # n is not used at the moment
gtail <- function(x, n) .Call(Cgtail, x, as.integer(n)) # n is not used at the moment
gfirst <- function(x) .Call(Cgfirst, x)
glast <- function(x) .Call(Cglast, x)
gsum <- function(x, na.rm=FALSE) .Call(Cgsum, x, na.rm)
gmean <- function(x, na.rm=FALSE) .Call(Cgmean, x, na.rm)
gprod <- function(x, na.rm=FALSE) .Call(Cgprod, x, na.rm)
gmedian <- function(x, na.rm=FALSE) .Call(Cgmedian, x, na.rm)
gmin <- function(x, na.rm=FALSE) .Call(Cgmin, x, na.rm)
gmax <- function(x, na.rm=FALSE) .Call(Cgmax, x, na.rm)
gvar <- function(x, na.rm=FALSE) .Call(Cgvar, x, na.rm)
gsd <- function(x, na.rm=FALSE) .Call(Cgsd, x, na.rm)
gforce <- function(env, jsub, o, f, l, rows) .Call(Cgforce, env, jsub, o, f, l, rows)
isReallyReal <- function(x) {
.Call(CisReallyReal, x)
}
.prepareFastSubset <- function(isub, x, enclos, notjoin, verbose = FALSE){
## helper that decides, whether a fast binary search can be performed, if i is a call
## For details on the supported queries, see \code{\link{datatable-optimize}}
## Additional restrictions are imposed if x is .SD, or if options indicate that no optimization
## is to be performed
#' @param isub the substituted i
#' @param x the data.table
#' @param enclos The environment where to evaluate when RHS is not a column of x
#' @param notjoin boolean that is set before, indicating whether i started with '!'.
#' @param verbose TRUE for detailed output
#' @return If i is not fast subsettable, NULL. Else, a list with entries:
#' out$i: a data.table that will be used as i with proper column names and key.
#' out$on: the correct 'on' statement that will be used for x[i, on =...]
#' out$notjoin Bool. In some cases, notjoin is updated within the function.
#' ATTENTION: If nothing else helps, an auto-index is created on x unless options prevent this.
if(getOption("datatable.optimize") < 3L) return(NULL) ## at least level three optimization required.
if (!is.call(isub)) return(NULL)
if (!is.null(attr(x, '.data.table.locked'))) return(NULL) # fix for #958, don't create auto index on '.SD'.
## a list of all possible operators with their translations into the 'on' clause
validOps <- list(op = c("==", "%in%", "%chin%"),
on = c("==", "==", "=="))
## Determine, whether the nature of isub in general supports fast binary search
remainingIsub <- isub
i <- list()
on <- character(0)
nonEqui = FALSE
while(length(remainingIsub)){
if(is.call(remainingIsub)){
if (length(remainingIsub[[1L]]) != 1L) return(NULL) ## only single symbol, either '&' or one of validOps allowed.
if (remainingIsub[[1L]] != "&"){ ## only a single expression present or a different connection.
stub <- remainingIsub
remainingIsub <- NULL ## there is no remainder to be evaluated after stub.
} else {
## multiple expressions with & connection.
if (notjoin) return(NULL) ## expressions of type DT[!(a==1 & b==2)] currently not supported
stub <- remainingIsub[[3L]] ## the single column expression like col == 4
remainingIsub <- remainingIsub[[2L]] ## the potentially longer expression with potential additional '&'
}
} else { ## single symbol present
stub <- remainingIsub
remainingIsub <- NULL
}
## check the stub if it is fastSubsettable
if(is.symbol(stub)){
## something like DT[x & y]. If x and y are logical columns, we can optimize.
col <- as.character(stub)
if(!col %chin% names(x)) return(NULL)
if(!is.logical(x[[col]])) return(NULL)
## redirect to normal DT[x == TRUE]
stub <- call("==", as.symbol(col), TRUE)
}
if (length(stub[[1L]]) != 1) return(NULL) ## Whatever it is, definitely not one of the valid operators
operator <- as.character(stub[[1L]])
if (!operator %chin% validOps$op) return(NULL) ## operator not supported
if (!is.name(stub[[2L]])) return(NULL)
col <- as.character(stub[[2L]])
if (!col %chin% names(x)) return(NULL) ## any non-column name prevents fast subsetting
if(col %chin% names(i)) return(NULL) ## repeated appearance of the same column not suported (e.g. DT[x < 3 & x < 5])
## now check the RHS of stub
RHS = eval(stub[[3L]], x, enclos)
if (is.list(RHS)) RHS = as.character(RHS) # fix for #961
if (length(RHS) != 1L && !operator %chin% c("%in%", "%chin%")){
if (length(RHS) != nrow(x)) stop("RHS of ", operator, " is length ",length(RHS)," which is not 1 or nrow (",nrow(x),"). For robustness, no recycling is allowed (other than of length 1 RHS). Consider %in% instead.")
return(NULL) # DT[colA == colB] regular element-wise vector scan
}
if ( mode(x[[col]]) != mode(RHS) || # mode() so that doubleLHS/integerRHS and integerLHS/doubleRHS!isReallyReal are optimized (both sides mode 'numeric')
is.factor(x[[col]])+is.factor(RHS) == 1L || # but factor is also mode 'numeric' so treat that separately
is.integer(x[[col]]) && isReallyReal(RHS) ) { # and if RHS contains fractions then don't optimize that as bmerge truncates the fractions to match to the target integer type
# re-direct non-matching type cases to base R, as data.table's binary
# search based join is strict in types. #957, #961 and #1361
# the mode() checks also deals with NULL since mode(NULL)=="NULL" and causes this return, as one CRAN package (eplusr 0.9.1) relies on
return(NULL)
}
if(is.character(x[[col]]) && !operator %chin% c("==", "%in%", "%chin%")) return(NULL) ## base R allows for non-equi operators on character columns, but these can't be optimized.
if (!operator %chin% c("%in%", "%chin%")) {
# addional requirements for notjoin and NA values. Behaviour is different for %in%, %chin% compared to other operators
# RHS is of length=1 or n
if (any_na(as_list(RHS))) {
## dt[x == NA] or dt[x <= NA] will always return empty
notjoin = FALSE
RHS = RHS[0L]
} else if (notjoin) {
## dt[!x == 3] must not return rows where x is NA
RHS = c(RHS, if (is.double(RHS)) c(NA, NaN) else NA)
}
}
## if it passed until here, fast subset can be done for this stub
i <- c(i, setNames(list(RHS), col))
on <- c(on, setNames(paste0(col, validOps$on[validOps$op == operator], col), col))
## loop continues with remainingIsub
}
if (length(i) == 0L) stop("Internal error in .isFastSubsettable. Please report to data.table developers") # nocov
## convert i to data.table with all combinations in rows.
if(length(i) > 1L && prod(vapply(i, length, integer(1L))) > 1e4){
## CJ would result in more than 1e4 rows. This would be inefficient, especially memory-wise #2635
if (verbose) {cat("Subsetting optimization disabled because the cross-product of RHS values exceeds 1e4, causing memory problems.\n");flush.console()}
return(NULL)
}
## Care is needed with names as we construct i
## with 'CJ' and 'do.call' and this would cause problems if colNames were 'sorted' or 'unique'
## as these two would be interpreted as args for CJ
colNames <- names(i)
names(i) <- NULL
i$sorted <- FALSE
i$unique <- TRUE
i <- do.call(CJ, i)
setnames(i, colNames)
idx <- NULL
if(is.null(idx)){
## check whether key fits the columns in i.
## order of key columns makes no difference, as long as they are all upfront in the key, I believe.
if (all(names(i) %chin% head(key(x), length(i)))){
if (verbose) {cat("Optimized subsetting with key '", paste0( head(key(x), length(i)), collapse = ", "),"'\n",sep="");flush.console()}
idx <- integer(0L) ## integer(0L) not NULL! Indicates that x is ordered correctly.
idxCols <- head(key(x), length(i)) ## in correct order!
}
}
if (is.null(idx)){
if (!getOption("datatable.use.index")) return(NULL) # #1422
## check whether an exising index can be used
## An index can be used if it corresponds exactly to the columns in i (similar to the key above)
candidates <- indices(x, vectors = TRUE)
idx <- NULL
for (cand in candidates){
if (all(names(i) %chin% cand) && length(cand) == length(i)){
idx <- attr(attr(x, "index"), paste0("__", cand, collapse = ""))
idxCols <- cand
break
}
}
if (!is.null(idx)){
if (verbose) {cat("Optimized subsetting with index '", paste0( idxCols, collapse = "__"),"'\n",sep="");flush.console()}
}
}
if (is.null(idx)){
## if nothing else helped, auto create a new index that can be used
if (!getOption("datatable.auto.index")) return(NULL)
if (verbose) {cat("Creating new index '", paste0(names(i), collapse = "__"),"'\n",sep="");flush.console()}
if (verbose) {last.started.at=proc.time();cat("Creating index", paste0(names(i), collapse = "__"), "done in ... ");flush.console()}
setindexv(x, names(i))
if (verbose) {cat(timetaken(last.started.at),"\n");flush.console()}
if (verbose) {cat("Optimized subsetting with index '", paste0(names(i), collapse = "__"),"'\n",sep="");flush.console()}
idx <- attr(attr(x, "index"), paste0("__", names(i), collapse = ""))
idxCols <- names(i)
}
if(!is.null(idxCols)){
setkeyv(i, idxCols)
on <- on[idxCols] ## make sure 'on' is in the correct order. Otherwise the logic won't recognise that a key / index already exists.
}
return(list(i = i,
on = on,
notjoin = notjoin
)
)
}
.parse_on <- function(onsub, isnull_inames) {
## helper that takes the 'on' string(s) and extracts comparison operators and column names from it.
#' @param onsub the substituted on
#' @param isnull_inames bool; TRUE if i has no names.
#' @return List with two entries:
#' 'on' : character vector providing the column names for the join.
#' Names correspond to columns in x, entries correspond to columns in i
#' 'ops': integer vector. Gives the indices of the operators that connect the columns in x and i.
ops = c("==", "<=", "<", ">=", ">", "!=")
pat = paste0("(", ops, ")", collapse="|")
if (is.call(onsub) && onsub[[1L]] == "eval") {
onsub = eval(onsub[[2L]], parent.frame(2L), parent.frame(2L))
if (is.call(onsub) && onsub[[1L]] == "eval") { onsub = onsub[[2L]] }
}
if (is.call(onsub) && as.character(onsub[[1L]]) %chin% c("list", ".")) {
spat = paste0("[ ]+(", pat, ")[ ]+")
onsub = lapply(as.list(onsub)[-1L], function(x) gsub(spat, "\\1", deparse(x, width.cutoff=500L)))
onsub = as.call(c(quote(c), onsub))
}
on = eval(onsub, parent.frame(2L), parent.frame(2L))
if (!is.character(on))
stop("'on' argument should be a named atomic vector of column names indicating which columns in 'i' should be joined with which columns in 'x'.")
## extract the operators and potential variable names from 'on'.
## split at backticks to take care about variable names like `col1<=`.
pieces <- strsplit(on, "(?=[`])", perl = TRUE)
xCols <- character(length(on))
## if 'on' is named, the names are the xCols for sure
if(!is.null(names(on))){
xCols <- names(on)
}
iCols <- character(length(on))
operators <- character(length(on))
## loop over the elements and extract operators and column names.
for(i in seq_along(pieces)){
thisCols <- character(0)
thisOperators <- character(0)
j <- 1
while(j <= length(pieces[[i]])){
if(pieces[[i]][j] == "`"){
## start of a variable name with backtick.
thisCols <- c(thisCols, pieces[[i]][j+1])
j <- j+3 # +1 is the column name, +2 is delimiting "`", +3 is next relevant entry.`
} else {
## no backtick
## search for operators
thisOperators <- c(thisOperators,
unlist(regmatches(pieces[[i]][j], gregexpr(pat, pieces[[i]][j])),
use.names = FALSE))
## search for column names
thisCols <- c(thisCols, trimws(strsplit(pieces[[i]][j], pat)[[1]]))
## there can be empty string column names because of trimws, remove them
thisCols <- thisCols[thisCols != ""]
j <- j+1
}
}
if (length(thisOperators) == 0) {
## if no operator is given, it must be ==
operators[i] <- "=="
} else if (length(thisOperators) == 1) {
operators[i] <- thisOperators
} else {
## multiple operators found in one 'on' part. Something is wrong.
stop("Found more than one operator in one 'on' statement: ", on[i], ". Please specify a single operator.")
}
if (length(thisCols) == 2){
## two column names found, first is xCol, second is iCol for sure
xCols[i] <- thisCols[1]
iCols[i] <- thisCols[2]
} else if (length(thisCols) == 1){
## a single column name found. Can mean different things
if(xCols[i] != ""){
## xCol is given by names(on). thisCols must be iCol
iCols[i] <- thisCols[1]
} else if (isnull_inames){
## i has no names. It will be given the names V1, V2, ... automatically.
## The single column name is the x column. It will match to the ith column in i.
xCols[i] <- thisCols[1]
iCols[i] <- paste0("V", i)
} else {
## i has names and one single column name is given by on.
## This means that xCol and iCol have the same name.
xCols[i] <- thisCols[1]
iCols[i] <- thisCols[1]
}
} else if (length(thisCols) == 0){
stop("'on' contains no column name: ", on[i], ". Each 'on' clause must contain one or two column names.")
} else {
stop("'on' contains more than 2 column names: ", on[i], ". Each 'on' clause must contain one or two column names.")
}
}
idx_op = match(operators, ops, nomatch=0L)
if (any(idx_op %in% c(0L, 6L)))
stop("Invalid operators ", paste(operators[idx_op %in% c(0L, 6L)], collapse=","), ". Only allowed operators are ", paste(ops[1:5], collapse=""), ".")
## the final on will contain the xCol as name, the iCol as value
on <- iCols
names(on) <- xCols
return(list(on = on, ops = idx_op))
}
|
library(maptools)
library(maps)
library(ggplot2)
library(plyr)
library(dplyr)
setwd("~/Desktop/puzzles-starting-2015/puzzle-16-vt-crashes/BoundaryOther_BNDHASH")
## read in VT town shape files
vt <- readShapeSpatial('Boundary_BNDHASH_region_towns.shp')
#plot(vt)
## read in VT population info
pop <- read.csv('../2012pop.csv')
vt@data <- merge(vt@data, pop, by.x = "TOWNNAME", by.y = "NAME", all.x=TRUE)
#vt@data <- arrange(vt@data, TOWNS_)
#plot(vt, col=rgb(256-(256*vt@data$X2012.population/42282),256,256, maxColorValue = 256))
## import crash data
crashes <- read.csv('../Vermont_Crash_Data_2012.csv')
crash_table <- table(crashes$Town)
crash_df <- data.frame(crash_table)
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Buel's Gore", "Buels Gore", as.character(Var1)))
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Isle Lamotte", "Isle La Motte", as.character(Var1)))
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Mt. Holly", "Mount Holly", as.character(Var1)))
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Mt. Tabor", "Mount Tabor", as.character(Var1)))
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Rutland Town", "Rutland", as.character(Var1)))
## merge crash data with
vt@data <- merge(vt@data, crash_df, by.x = "TOWNNAMEMC", by.y = "Var1", all.x=TRUE, all.y=TRUE)
vt@data <- arrange(vt@data, TOWNS_)
vt@data <- vt@data[1:255,]
vt@data$Freq[is.na(vt@data$Freq)] <- 0
vt@data <- mutate(vt@data, acc_per_cap = Freq/X2012.population)
vt@data$acc_per_cap[is.nan(vt@data$acc_per_cap)] <- 0
vt@data <- mutate(vt@data, log_acc = log10(acc_per_cap))
vt@data$log_acc[is.infinite(vt@data$log_acc)] <- -4
vt@data <- mutate(vt@data, log_acc_mod = (log_acc + 4)/3.6)
png('question_log_map.png', height=1200, width=700)
plot(vt, col=rgb(196 + (60*vt@data$log_acc_mod), 196 - (196*vt@data$log_acc_mod), 196 - (196*vt@data$log_acc_mod), maxColorValue = 256))
dev.off()
vt@data <- mutate(vt@data, bacc_per_cap = ifelse(X2012.population > 1000, acc_per_cap, 0))
png('question_log_map.png', height=1200, width=700)
plot(vt, col=rgb(196 + (60*vt@data$log_acc_mod), 196 - (196*vt@data$log_acc_mod), 196 - (196*vt@data$log_acc_mod), maxColorValue = 256))
dev.off()
png('question_lin_map.png', height=1200, width=700)
plot(vt, col=rgb(196 + (60*vt@data$acc_per_cap/.375), 196 - (196*vt@data$acc_per_cap/.375), 196 - (196*vt@data$acc_per_cap/.375), maxColorValue = 256))
dev.off()
png('answer_lin_map.png', height=1200, width=700)
plot(vt, col=rgb(196 - (196*vt@data$bacc_per_cap/.0468), 196 - (196*vt@data$bacc_per_cap/.0468), 196 + (60*vt@data$bacc_per_cap/.0468), maxColorValue = 256))
dev.off() | /puzzle-16-vt-crashes/crashes-vt.R | no_license | mcfink/puzzle-scripts | R | false | false | 2,628 | r | library(maptools)
library(maps)
library(ggplot2)
library(plyr)
library(dplyr)
setwd("~/Desktop/puzzles-starting-2015/puzzle-16-vt-crashes/BoundaryOther_BNDHASH")
## read in VT town shape files
vt <- readShapeSpatial('Boundary_BNDHASH_region_towns.shp')
#plot(vt)
## read in VT population info
pop <- read.csv('../2012pop.csv')
vt@data <- merge(vt@data, pop, by.x = "TOWNNAME", by.y = "NAME", all.x=TRUE)
#vt@data <- arrange(vt@data, TOWNS_)
#plot(vt, col=rgb(256-(256*vt@data$X2012.population/42282),256,256, maxColorValue = 256))
## import crash data
crashes <- read.csv('../Vermont_Crash_Data_2012.csv')
crash_table <- table(crashes$Town)
crash_df <- data.frame(crash_table)
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Buel's Gore", "Buels Gore", as.character(Var1)))
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Isle Lamotte", "Isle La Motte", as.character(Var1)))
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Mt. Holly", "Mount Holly", as.character(Var1)))
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Mt. Tabor", "Mount Tabor", as.character(Var1)))
crash_df <- mutate(crash_df, Var1 = ifelse(Var1 == "Rutland Town", "Rutland", as.character(Var1)))
## merge crash data with
vt@data <- merge(vt@data, crash_df, by.x = "TOWNNAMEMC", by.y = "Var1", all.x=TRUE, all.y=TRUE)
vt@data <- arrange(vt@data, TOWNS_)
vt@data <- vt@data[1:255,]
vt@data$Freq[is.na(vt@data$Freq)] <- 0
vt@data <- mutate(vt@data, acc_per_cap = Freq/X2012.population)
vt@data$acc_per_cap[is.nan(vt@data$acc_per_cap)] <- 0
vt@data <- mutate(vt@data, log_acc = log10(acc_per_cap))
vt@data$log_acc[is.infinite(vt@data$log_acc)] <- -4
vt@data <- mutate(vt@data, log_acc_mod = (log_acc + 4)/3.6)
png('question_log_map.png', height=1200, width=700)
plot(vt, col=rgb(196 + (60*vt@data$log_acc_mod), 196 - (196*vt@data$log_acc_mod), 196 - (196*vt@data$log_acc_mod), maxColorValue = 256))
dev.off()
vt@data <- mutate(vt@data, bacc_per_cap = ifelse(X2012.population > 1000, acc_per_cap, 0))
png('question_log_map.png', height=1200, width=700)
plot(vt, col=rgb(196 + (60*vt@data$log_acc_mod), 196 - (196*vt@data$log_acc_mod), 196 - (196*vt@data$log_acc_mod), maxColorValue = 256))
dev.off()
png('question_lin_map.png', height=1200, width=700)
plot(vt, col=rgb(196 + (60*vt@data$acc_per_cap/.375), 196 - (196*vt@data$acc_per_cap/.375), 196 - (196*vt@data$acc_per_cap/.375), maxColorValue = 256))
dev.off()
png('answer_lin_map.png', height=1200, width=700)
plot(vt, col=rgb(196 - (196*vt@data$bacc_per_cap/.0468), 196 - (196*vt@data$bacc_per_cap/.0468), 196 + (60*vt@data$bacc_per_cap/.0468), maxColorValue = 256))
dev.off() |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/piecewise.R
\name{piecewise}
\alias{piecewise}
\title{Piecewise regression}
\usage{
piecewise(x, xk, coef)
}
\arguments{
\item{x}{Number}
\item{xk}{Number}
\item{coef}{Numeric Vector}
}
\value{
Numeric
}
\description{
takes the x value and plots a line until it hits the change point defined by xk,
then plots a different line to make a piecewise regression graph.
}
\examples{
curve(myf(x, xk, coef), add = TRUE, lwd = 2, col = "Blue")
}
| /man/piecewise.Rd | no_license | Nathanv97/vand6485 | R | false | true | 520 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/piecewise.R
\name{piecewise}
\alias{piecewise}
\title{Piecewise regression}
\usage{
piecewise(x, xk, coef)
}
\arguments{
\item{x}{Number}
\item{xk}{Number}
\item{coef}{Numeric Vector}
}
\value{
Numeric
}
\description{
takes the x value and plots a line until it hits the change point defined by xk,
then plots a different line to make a piecewise regression graph.
}
\examples{
curve(myf(x, xk, coef), add = TRUE, lwd = 2, col = "Blue")
}
|
varSelection <- function(data, miss_thr=2/3, gamma_thr=0.7, beta_thr=c(-3,3), m=10, crit_thr=0.95,
Theta_range=c(-15, 15), qsel=0.25, ...) {
#data: dataset (dichotomous variable must be 0/1 coded)
#miss_thr = threshold for missing values (default 2/3)
#gamma_thr = threshold for item discrimination (default 0.7)
#beta_thr = threshold for beta parameters (default [-3,3])
#m = max no. of categories for discrete variables, otherwise it is considered as continuous
#crit_thr = threshold for "critical items": obs. response rate concentrated in a certain category (def. 0.95)
#Theta_range = latent trait range (standard normal distributed) for evaluating the item/test information (def. [-15,15])
#qsek = quantile for the selection based on item information proportion on the whole test information (def. 0.25 = 1st quartile)
#... = argument for 'mirt' function within IRT selection
library(mirt)
nvar <- ncol(data) #no. of variables
n <- nrow(data) #no. of statistical units (households)
out <- data.frame(ID=1:nvar, name=names(data), stringsAsFactors=FALSE)
miss <- apply(data, 2, function(x) sum(1*is.na(x)))
miss_prop <- round(miss/n, 6)
ncat <- apply(data, 2, function(x) length(unique(na.omit(x))))
mmin <- apply(data, 2, min, na.rm=TRUE)
mmax <- apply(data, 2, max, na.rm=TRUE)
mmean <- apply(data, 2, mean, na.rm=TRUE)
out <- data.frame(out, miss_prop, ncat, min=mmin, max=mmax, mean=mmean)
rownames(out) <- NULL
# browser()
# check for dichotomous data
flag <- (ncat == 2 & (mmin != 0 | mmax != 1))
if (any(flag)) stop("Check dichotomous data: they must be 0/1 coded")
# preliminary selection: missing values and continuous variables
cat("*****************Preliminary selection*****************\n")
cat("- Missing proportion threshold", miss_thr, "\n")
cat("- Variables with number of response categories greater than", m, "are removed\n")
cat("......\n")
cont <- ifelse(out$ncat > m | out$max > m, 1, 0)
z <- which(out$miss_prop <= miss_thr & cont != 1)
out$cont <- cont
out$miss <- 1*(out$miss_prop >= miss_thr)
out2 <- out[z, ]
# critical items
data_sub1 <- subset(data, select=out2$ID)
tab <- apply(data_sub1, 2, function(x) prop.table(table(x, useNA="always")))
crit_item <- sapply(tab, function(x) 1*(max(x)>=crit_thr))
out2 <- data.frame(out2, crit_item)
nvar_prel <- nrow(out2)
cat("End preliminary selection\n")
cat("- ", nvar_prel, "variables out of", nvar, "are retained\n")
cat("- ", sum(crit_item), "are \"critical\" items\n")
# browser()
# model-based selection
cat("\n*****************IRT selection*****************\n")
modIRT <- mirt(data_sub1, model=1, itemtype="graded", ...)
params <- coef(modIRT, simplify=TRUE, IRTpars=TRUE)$items
out2$gamma <- params[, 1] #discrim parameters
beta <- params[, 2:ncol(params)] #"difficulty" parameter(s)
colnames(beta) <- paste("beta", 1:ncol(beta), sep="")
out2 <- data.frame(out2, beta)
#item information
Theta <- matrix(seq(Theta_range[1], Theta_range[2], by = .1))
item_info <- matrix(NA, nrow=length(Theta), ncol=nvar_prel)
for (j in 1:nvar_prel) {
extr <- extract.item(modIRT, item=j)
item_info[, j] <- iteminfo(extr, Theta)
}
item_infotot <- colSums(item_info)
# test information
test_info <- testinfo(modIRT, Theta)
test_infotot <- sum(test_info)
out2$prop_info <- item_infotot/test_infotot*100
# sel on gamma
out2$gamma_sel <- ifelse(out2$gamma >= gamma_thr, "keep", "drop")
# sel on betas
beta_med <- apply(beta, 1, median, na.rm=TRUE)
out2$beta_sel <- ifelse(beta_med >= beta_thr[1] & beta_med <= beta_thr[2], "keep", "drop")
# sel on information (prop >= 1/n.items)
out2$info_sel <- ifelse(out2$prop_info >= (1/nvar_prel)*100, "keep", "drop")
# sel on information (prop >= quantile)
q <- quantile(out2$prop_info, qsel)
out2$info_selQ <- ifelse(out2$prop_info >= q, "keep", "drop")
# Final proposal: at least 2 criteria out of 4
sel <- subset(out2, select=c("gamma_sel", "beta_sel", "info_sel", "info_selQ"))
nkeep <- apply(sel, 1, function(x) sum(1*(x == "keep")))
final_sel <- rep(NA, nvar_prel)
final_sel <- ifelse(nkeep < 2, "drop", final_sel)
final_sel <- ifelse(nkeep > 2, "keep", final_sel)
final_sel <- ifelse(nkeep == 2 & out2$crit_item == 1, "drop", final_sel)
final_sel <- ifelse(nkeep == 2 & out2$crit_item == 0, "keep", final_sel)
out2$final_sel <- final_sel
cat("End IRT selection\n")
return(list(prel=out, final=out2))
}
| /R/IRT/varSelection.R | permissive | unhcr-americas/vulnerability-scoring | R | false | false | 4,560 | r | varSelection <- function(data, miss_thr=2/3, gamma_thr=0.7, beta_thr=c(-3,3), m=10, crit_thr=0.95,
Theta_range=c(-15, 15), qsel=0.25, ...) {
#data: dataset (dichotomous variable must be 0/1 coded)
#miss_thr = threshold for missing values (default 2/3)
#gamma_thr = threshold for item discrimination (default 0.7)
#beta_thr = threshold for beta parameters (default [-3,3])
#m = max no. of categories for discrete variables, otherwise it is considered as continuous
#crit_thr = threshold for "critical items": obs. response rate concentrated in a certain category (def. 0.95)
#Theta_range = latent trait range (standard normal distributed) for evaluating the item/test information (def. [-15,15])
#qsek = quantile for the selection based on item information proportion on the whole test information (def. 0.25 = 1st quartile)
#... = argument for 'mirt' function within IRT selection
library(mirt)
nvar <- ncol(data) #no. of variables
n <- nrow(data) #no. of statistical units (households)
out <- data.frame(ID=1:nvar, name=names(data), stringsAsFactors=FALSE)
miss <- apply(data, 2, function(x) sum(1*is.na(x)))
miss_prop <- round(miss/n, 6)
ncat <- apply(data, 2, function(x) length(unique(na.omit(x))))
mmin <- apply(data, 2, min, na.rm=TRUE)
mmax <- apply(data, 2, max, na.rm=TRUE)
mmean <- apply(data, 2, mean, na.rm=TRUE)
out <- data.frame(out, miss_prop, ncat, min=mmin, max=mmax, mean=mmean)
rownames(out) <- NULL
# browser()
# check for dichotomous data
flag <- (ncat == 2 & (mmin != 0 | mmax != 1))
if (any(flag)) stop("Check dichotomous data: they must be 0/1 coded")
# preliminary selection: missing values and continuous variables
cat("*****************Preliminary selection*****************\n")
cat("- Missing proportion threshold", miss_thr, "\n")
cat("- Variables with number of response categories greater than", m, "are removed\n")
cat("......\n")
cont <- ifelse(out$ncat > m | out$max > m, 1, 0)
z <- which(out$miss_prop <= miss_thr & cont != 1)
out$cont <- cont
out$miss <- 1*(out$miss_prop >= miss_thr)
out2 <- out[z, ]
# critical items
data_sub1 <- subset(data, select=out2$ID)
tab <- apply(data_sub1, 2, function(x) prop.table(table(x, useNA="always")))
crit_item <- sapply(tab, function(x) 1*(max(x)>=crit_thr))
out2 <- data.frame(out2, crit_item)
nvar_prel <- nrow(out2)
cat("End preliminary selection\n")
cat("- ", nvar_prel, "variables out of", nvar, "are retained\n")
cat("- ", sum(crit_item), "are \"critical\" items\n")
# browser()
# model-based selection
cat("\n*****************IRT selection*****************\n")
modIRT <- mirt(data_sub1, model=1, itemtype="graded", ...)
params <- coef(modIRT, simplify=TRUE, IRTpars=TRUE)$items
out2$gamma <- params[, 1] #discrim parameters
beta <- params[, 2:ncol(params)] #"difficulty" parameter(s)
colnames(beta) <- paste("beta", 1:ncol(beta), sep="")
out2 <- data.frame(out2, beta)
#item information
Theta <- matrix(seq(Theta_range[1], Theta_range[2], by = .1))
item_info <- matrix(NA, nrow=length(Theta), ncol=nvar_prel)
for (j in 1:nvar_prel) {
extr <- extract.item(modIRT, item=j)
item_info[, j] <- iteminfo(extr, Theta)
}
item_infotot <- colSums(item_info)
# test information
test_info <- testinfo(modIRT, Theta)
test_infotot <- sum(test_info)
out2$prop_info <- item_infotot/test_infotot*100
# sel on gamma
out2$gamma_sel <- ifelse(out2$gamma >= gamma_thr, "keep", "drop")
# sel on betas
beta_med <- apply(beta, 1, median, na.rm=TRUE)
out2$beta_sel <- ifelse(beta_med >= beta_thr[1] & beta_med <= beta_thr[2], "keep", "drop")
# sel on information (prop >= 1/n.items)
out2$info_sel <- ifelse(out2$prop_info >= (1/nvar_prel)*100, "keep", "drop")
# sel on information (prop >= quantile)
q <- quantile(out2$prop_info, qsel)
out2$info_selQ <- ifelse(out2$prop_info >= q, "keep", "drop")
# Final proposal: at least 2 criteria out of 4
sel <- subset(out2, select=c("gamma_sel", "beta_sel", "info_sel", "info_selQ"))
nkeep <- apply(sel, 1, function(x) sum(1*(x == "keep")))
final_sel <- rep(NA, nvar_prel)
final_sel <- ifelse(nkeep < 2, "drop", final_sel)
final_sel <- ifelse(nkeep > 2, "keep", final_sel)
final_sel <- ifelse(nkeep == 2 & out2$crit_item == 1, "drop", final_sel)
final_sel <- ifelse(nkeep == 2 & out2$crit_item == 0, "keep", final_sel)
out2$final_sel <- final_sel
cat("End IRT selection\n")
return(list(prel=out, final=out2))
}
|
library(plyr)
library(ggplot2)
# Read the data file
NEI <- readRDS("data/summarySCC_PM25.rds")
SCC <- readRDS("data/Source_Classification_Code.rds")
# First extract all source codes corresponding to coal combustion
# The EI.Sector field looks like the most direct way to determine this
CoalCombustionSCC <- subset(SCC, EI.Sector %in% c("Fuel Comb - Comm/Institutional - Coal",
"Fuel Comb - Electric Generation - Coal",
"Fuel Comb - Industrial Boilers, ICEs - Coal"))
# This may omit some. For example, see 242
# Compare to Short.Name matching both Comb and Coal
CoalCombustionSCC1 <- subset(SCC, grepl("Comb", Short.Name) & grepl("Coal", Short.Name))
nrow(CoalCombustionSCC)
nrow(CoalCombustionSCC1)
d1 <- setdiff(CoalCombustionSCC, CoalCombustionSCC1)
d2 <- setdiff(CoalCombustionSCC1, CoalCombustionSCC)
length(d1)
length(d2)
# Above does not work correctly
d3 <- setdiff(CoalCombustionSCC$SCC, CoalCombustionSCC1$SCC)
d4 <- setdiff(CoalCombustionSCC1$SCC, CoalCombustionSCC$SCC)
length(d3)
length(d4)
# Given these differences I believe the best approach is to union the two sets
CoalCombustionSCCCodes <- union(CoalCombustionSCC$SCC, CoalCombustionSCC1$SCC)
length(CoalCombustionSCCCodes)
CoalCombustion <- subset(NEI, SCC %in% CoalCombustionSCCCodes)
coalCombustionPM25ByYear <- ddply(CoalCombustion, .(year, type), function(x) sum(x$Emissions))
colnames(coalCombustionPM25ByYear)[3] <- "Emissions"
png("plot4.png")
qplot(year, Emissions, data=coalCombustionPM25ByYear, color=type, geom="line") +
stat_summary(fun.y = "sum", fun.ymin = "sum", fun.ymax = "sum",
color = "black", aes(shape="total"), geom="line") +
geom_line(aes(size="total", shape = NA)) +
ggtitle(expression("Coal Combustion" ~ PM[2.5] ~ "Emissions by Source Type and Year")) +
xlab("Year") +
ylab(expression("Total" ~ PM[2.5] ~ "Emissions (tons)"))
dev.off()
| /plot4.R | no_license | madamovic/ExData_Plotting2 | R | false | false | 1,957 | r | library(plyr)
library(ggplot2)
# Read the data file
NEI <- readRDS("data/summarySCC_PM25.rds")
SCC <- readRDS("data/Source_Classification_Code.rds")
# First extract all source codes corresponding to coal combustion
# The EI.Sector field looks like the most direct way to determine this
CoalCombustionSCC <- subset(SCC, EI.Sector %in% c("Fuel Comb - Comm/Institutional - Coal",
"Fuel Comb - Electric Generation - Coal",
"Fuel Comb - Industrial Boilers, ICEs - Coal"))
# This may omit some. For example, see 242
# Compare to Short.Name matching both Comb and Coal
CoalCombustionSCC1 <- subset(SCC, grepl("Comb", Short.Name) & grepl("Coal", Short.Name))
nrow(CoalCombustionSCC)
nrow(CoalCombustionSCC1)
d1 <- setdiff(CoalCombustionSCC, CoalCombustionSCC1)
d2 <- setdiff(CoalCombustionSCC1, CoalCombustionSCC)
length(d1)
length(d2)
# Above does not work correctly
d3 <- setdiff(CoalCombustionSCC$SCC, CoalCombustionSCC1$SCC)
d4 <- setdiff(CoalCombustionSCC1$SCC, CoalCombustionSCC$SCC)
length(d3)
length(d4)
# Given these differences I believe the best approach is to union the two sets
CoalCombustionSCCCodes <- union(CoalCombustionSCC$SCC, CoalCombustionSCC1$SCC)
length(CoalCombustionSCCCodes)
CoalCombustion <- subset(NEI, SCC %in% CoalCombustionSCCCodes)
coalCombustionPM25ByYear <- ddply(CoalCombustion, .(year, type), function(x) sum(x$Emissions))
colnames(coalCombustionPM25ByYear)[3] <- "Emissions"
png("plot4.png")
qplot(year, Emissions, data=coalCombustionPM25ByYear, color=type, geom="line") +
stat_summary(fun.y = "sum", fun.ymin = "sum", fun.ymax = "sum",
color = "black", aes(shape="total"), geom="line") +
geom_line(aes(size="total", shape = NA)) +
ggtitle(expression("Coal Combustion" ~ PM[2.5] ~ "Emissions by Source Type and Year")) +
xlab("Year") +
ylab(expression("Total" ~ PM[2.5] ~ "Emissions (tons)"))
dev.off()
|
#' @rdname coxplsDR
#' @export
coxplsDR.formula <- function(Xplan,time,time2,event,type,origin,typeres="deviance", collapse, weighted, scaleX=TRUE, scaleY=TRUE, ncomp=min(7,ncol(Xplan)), modepls="regression", plot=FALSE, allres=FALSE,dataXplan=NULL,subset,weights,model_frame=FALSE, model_matrix=FALSE, contrasts.arg=NULL,...) {
if (missing(dataXplan))
dataXplan <- environment(Xplan)
mf0 <- match.call(expand.dots = FALSE)
m0 <- match(c("subset", "weights"), names(mf0), 0L)
mf0 <- mf0[c(1L, m0)]
mf0$data <- dataXplan
mf0$formula <- as.formula(paste(c(as.character(Xplan),"+0"),collapse=""))
mf0$drop.unused.levels <- TRUE
mf0[[1L]] <- as.name("model.frame")
mf0 <- eval(mf0, parent.frame())
if (model_frame)
return(mf0)
mt0 <- attr(mf0, "terms")
Y <- model.response(mf0, "any")
if (length(dim(Y)) == 1L) {
nm <- rownames(Y)
dim(Y) <- NULL
if (!is.null(nm))
names(Y) <- nm
}
Xplan <- if (!is.empty.model(mt0)) model.matrix(mt0, mf0, , contrasts.arg=contrasts.arg)
else matrix(, NROW(Y), 0L)
if (model_matrix)
return(Xplan)
weights <- as.vector(model.weights(mf0))
if (!is.null(weights) && !is.numeric(weights))
stop("'weights' must be a numeric vector")
if (!is.null(weights) && any(weights < 0))
stop("negative weights not allowed")
NextMethod("coxplsDR")
}
| /R/coxplsDR.formula.R | no_license | cran/plsRcox | R | false | false | 1,296 | r | #' @rdname coxplsDR
#' @export
coxplsDR.formula <- function(Xplan,time,time2,event,type,origin,typeres="deviance", collapse, weighted, scaleX=TRUE, scaleY=TRUE, ncomp=min(7,ncol(Xplan)), modepls="regression", plot=FALSE, allres=FALSE,dataXplan=NULL,subset,weights,model_frame=FALSE, model_matrix=FALSE, contrasts.arg=NULL,...) {
if (missing(dataXplan))
dataXplan <- environment(Xplan)
mf0 <- match.call(expand.dots = FALSE)
m0 <- match(c("subset", "weights"), names(mf0), 0L)
mf0 <- mf0[c(1L, m0)]
mf0$data <- dataXplan
mf0$formula <- as.formula(paste(c(as.character(Xplan),"+0"),collapse=""))
mf0$drop.unused.levels <- TRUE
mf0[[1L]] <- as.name("model.frame")
mf0 <- eval(mf0, parent.frame())
if (model_frame)
return(mf0)
mt0 <- attr(mf0, "terms")
Y <- model.response(mf0, "any")
if (length(dim(Y)) == 1L) {
nm <- rownames(Y)
dim(Y) <- NULL
if (!is.null(nm))
names(Y) <- nm
}
Xplan <- if (!is.empty.model(mt0)) model.matrix(mt0, mf0, , contrasts.arg=contrasts.arg)
else matrix(, NROW(Y), 0L)
if (model_matrix)
return(Xplan)
weights <- as.vector(model.weights(mf0))
if (!is.null(weights) && !is.numeric(weights))
stop("'weights' must be a numeric vector")
if (!is.null(weights) && any(weights < 0))
stop("negative weights not allowed")
NextMethod("coxplsDR")
}
|
#' plot a map of estimated abundance or related quantity on a grid.
#' @param N quantity to plot
#' @param Coords data.frame holding x and y coordinates of each prediction cell
#' @param highlight [optional] A vector of cells to highlight. Default = NULL
#' @param myPalette A prespecified palette from RColorBrewer (default is YlOrBr(9) )
#' @param leg.title Title of the legend
#' @return ggplot2 map of predictions on a grid
#' @export
#' @author Paul Conn \email{paul.conn@@noaa.gov}
plot.prediction.map<-function(N,Coords,highlight=NULL,myPalette=NULL,leg.title="Abundance"){
#require(rgeos)
#require(ggplot2)
#library(RColorBrewer)
if(is.null(myPalette))myPalette <- colorRampPalette(brewer.pal(9, "YlOrBr"))
if(is.null(highlight)==FALSE){
midpoints=Coords[highlight,]
colnames(midpoints)=c("Easting","Northing")
}
Abundance=N
Cur.df=cbind(Coords,Abundance)
new.colnames=colnames(Cur.df)
new.colnames[1:2]=c("Easting","Northing")
colnames(Cur.df)=new.colnames
Grid.theme=theme(axis.ticks = element_blank(), axis.text = element_blank())
p1=ggplot(Cur.df)+aes(Easting,Northing,fill=Abundance)+geom_raster()+Grid.theme+scale_fill_gradientn(colours=myPalette(100),name=leg.title)
if(is.null(highlight)==FALSE){
#p1=p1+geom_rect(data=midpoints,size=0.5,fill=NA,colour="yellow",aes(xmin=Easting-25067,xmax=Easting,ymin=Northing,ymax=Northing+25067))
p1=p1+geom_rect(data=midpoints,size=0.5,fill=NA,colour="yellow",aes(xmin=Easting-25067/2,xmax=Easting+25067/2,ymin=Northing-25067/2,ymax=Northing+25067/2))
}
p1
}
| /HierarchicalGOF/R/util_functions.R | no_license | sadanapr/HierarchicalGOF | R | false | false | 1,566 | r | #' plot a map of estimated abundance or related quantity on a grid.
#' @param N quantity to plot
#' @param Coords data.frame holding x and y coordinates of each prediction cell
#' @param highlight [optional] A vector of cells to highlight. Default = NULL
#' @param myPalette A prespecified palette from RColorBrewer (default is YlOrBr(9) )
#' @param leg.title Title of the legend
#' @return ggplot2 map of predictions on a grid
#' @export
#' @author Paul Conn \email{paul.conn@@noaa.gov}
plot.prediction.map<-function(N,Coords,highlight=NULL,myPalette=NULL,leg.title="Abundance"){
#require(rgeos)
#require(ggplot2)
#library(RColorBrewer)
if(is.null(myPalette))myPalette <- colorRampPalette(brewer.pal(9, "YlOrBr"))
if(is.null(highlight)==FALSE){
midpoints=Coords[highlight,]
colnames(midpoints)=c("Easting","Northing")
}
Abundance=N
Cur.df=cbind(Coords,Abundance)
new.colnames=colnames(Cur.df)
new.colnames[1:2]=c("Easting","Northing")
colnames(Cur.df)=new.colnames
Grid.theme=theme(axis.ticks = element_blank(), axis.text = element_blank())
p1=ggplot(Cur.df)+aes(Easting,Northing,fill=Abundance)+geom_raster()+Grid.theme+scale_fill_gradientn(colours=myPalette(100),name=leg.title)
if(is.null(highlight)==FALSE){
#p1=p1+geom_rect(data=midpoints,size=0.5,fill=NA,colour="yellow",aes(xmin=Easting-25067,xmax=Easting,ymin=Northing,ymax=Northing+25067))
p1=p1+geom_rect(data=midpoints,size=0.5,fill=NA,colour="yellow",aes(xmin=Easting-25067/2,xmax=Easting+25067/2,ymin=Northing-25067/2,ymax=Northing+25067/2))
}
p1
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tidal_height.R
\name{tidal_height}
\alias{tidal_height}
\title{internal funtion}
\usage{
tidal_height(H1, H2, T1, T2, t)
}
\arguments{
\item{H1}{height 1}
\item{H2}{height 2}
\item{T1}{time 1}
\item{T2}{time 2}
\item{t}{time point}
}
\value{
numeric value with tidal height
}
\description{
internal function
}
| /man/tidal_height.Rd | no_license | bmjesus/sentinel | R | false | true | 392 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tidal_height.R
\name{tidal_height}
\alias{tidal_height}
\title{internal funtion}
\usage{
tidal_height(H1, H2, T1, T2, t)
}
\arguments{
\item{H1}{height 1}
\item{H2}{height 2}
\item{T1}{time 1}
\item{T2}{time 2}
\item{t}{time point}
}
\value{
numeric value with tidal height
}
\description{
internal function
}
|
#' Calculate inflow/outflow
#'
#' @param df dataframe merged from pond sizes, in, out and storage dataframe
#'@import tidyverse
#' @return f.df dataframe with calculated inflow, out, and outflow
#' @export
#'
#' @examples \dontrun
wbcalc<-function(df){
#df$outflow = rowSums(cbind(df$sr,df$sgw,df$ssr,df$et))
df$outflow = as.numeric(df$sr+df$sgw+df$ssr+df$et)
df$out.rre=as.numeric(df$sr-df$rre)#Main outflow variable from a wetland is soil runoff ( ), but a portion of this returns back as redirected residual
#df$inflow = rowSums(cbind(df$mr, df$mi, df$rr, df$ri, df$condense,df$isd,df$isr, df$rre), na.rm = T)
df$inflow = as.numeric(df$mr+ df$mi+df$rr+ df$ri+df$condense+df$isd+df$isr+df$rre)
f.df<-df
return(f.df)
}
| /R/wbcalc.R | no_license | emilycavaliere/WQCRHM | R | false | false | 734 | r | #' Calculate inflow/outflow
#'
#' @param df dataframe merged from pond sizes, in, out and storage dataframe
#'@import tidyverse
#' @return f.df dataframe with calculated inflow, out, and outflow
#' @export
#'
#' @examples \dontrun
wbcalc<-function(df){
#df$outflow = rowSums(cbind(df$sr,df$sgw,df$ssr,df$et))
df$outflow = as.numeric(df$sr+df$sgw+df$ssr+df$et)
df$out.rre=as.numeric(df$sr-df$rre)#Main outflow variable from a wetland is soil runoff ( ), but a portion of this returns back as redirected residual
#df$inflow = rowSums(cbind(df$mr, df$mi, df$rr, df$ri, df$condense,df$isd,df$isr, df$rre), na.rm = T)
df$inflow = as.numeric(df$mr+ df$mi+df$rr+ df$ri+df$condense+df$isd+df$isr+df$rre)
f.df<-df
return(f.df)
}
|
data_canada <- read.csv("E:/Nilam/2nd Term/Advanced Database Topics/Projects/Project 1/refugges/1/UNdata_Export_20180512_213810165.csv")
retrival_data_canada <- subset(data_canada, Country=="Canada")
final_data_canada <-aggregate(Total.refugees.and.people.in.refugee.like.situations.sup.....sup.~Year+Country, data=retrival_data_canada, FUN=sum)
write.csv(final_data_canada,"E:/Nilam/2nd Term/Advanced Database Topics/Projects/Project 1/refugges/1/outputUNdata2.csv", row.names = FALSE)
# Get the max salary from data frame.
Max_refugees_canada <- max(final_data_canada$Total.refugees.and.people.in.refugee.like.situations.sup.....sup.)
Max_year_canada <- max(final_data_canada$Year)
png(file="1_Line_Canada.jpg")
par(mar=c(5,6,4,2)+0.1)
plot(final_data_canada$Year, col="red", final_data_canada$Total.refugees.and.people.in.refugee.like.situations.sup.....sup. , pch=20, type="o", ylim=c(0,Max_refugees_canada), xlim=c(1975,Max_year_canada), axes=FALSE, ann=FALSE)
axis(1, las=1, at=5*0:Max_year_canada)
axis(2, las=2, at=20000*0:Max_refugees_canada)
box()
title(main="Refugees In Canada", col.main="blue" , font.main=4, font.lab=4, cex.main=1.5)
title(xlab="Year")
title(ylab="")
mtext("Total No. Of Refugees",side=2,line=5)
dev.off() | /1_Canada_Year.R | no_license | khushbusutaria/Data-Analysis-using-R | R | false | false | 1,262 | r | data_canada <- read.csv("E:/Nilam/2nd Term/Advanced Database Topics/Projects/Project 1/refugges/1/UNdata_Export_20180512_213810165.csv")
retrival_data_canada <- subset(data_canada, Country=="Canada")
final_data_canada <-aggregate(Total.refugees.and.people.in.refugee.like.situations.sup.....sup.~Year+Country, data=retrival_data_canada, FUN=sum)
write.csv(final_data_canada,"E:/Nilam/2nd Term/Advanced Database Topics/Projects/Project 1/refugges/1/outputUNdata2.csv", row.names = FALSE)
# Get the max salary from data frame.
Max_refugees_canada <- max(final_data_canada$Total.refugees.and.people.in.refugee.like.situations.sup.....sup.)
Max_year_canada <- max(final_data_canada$Year)
png(file="1_Line_Canada.jpg")
par(mar=c(5,6,4,2)+0.1)
plot(final_data_canada$Year, col="red", final_data_canada$Total.refugees.and.people.in.refugee.like.situations.sup.....sup. , pch=20, type="o", ylim=c(0,Max_refugees_canada), xlim=c(1975,Max_year_canada), axes=FALSE, ann=FALSE)
axis(1, las=1, at=5*0:Max_year_canada)
axis(2, las=2, at=20000*0:Max_refugees_canada)
box()
title(main="Refugees In Canada", col.main="blue" , font.main=4, font.lab=4, cex.main=1.5)
title(xlab="Year")
title(ylab="")
mtext("Total No. Of Refugees",side=2,line=5)
dev.off() |
library(ggplot2)
args <- commandArgs(TRUE)
referenceFile <- args[1]
sampleFile <- args[2]
outputFile <- args[3]
title <- args[4]
xlabel <- args[5]
ylabel <- args[6]
ref <- read.table(referenceFile, header = TRUE, check.names = FALSE)
sample <- read.table(sampleFile, header = TRUE, check.names = FALSE)
plot <- ggplot() +
geom_point(data = ref, aes(x = PC1, y = PC2, colour = popID), shape = 1) +
geom_point(data = sample, aes(x = PC1, y = PC2), shape = 18, size = 4) +
scale_colour_discrete(name = "Population") +
theme_bw(12) +
ggtitle(title) +
labs(x = xlabel, y = ylabel)
ggsave(filename = outputFile, height = 10, width = 10)
| /tools/R/ancestry-plot.r | permissive | gkno/gkno_launcher | R | false | false | 639 | r | library(ggplot2)
args <- commandArgs(TRUE)
referenceFile <- args[1]
sampleFile <- args[2]
outputFile <- args[3]
title <- args[4]
xlabel <- args[5]
ylabel <- args[6]
ref <- read.table(referenceFile, header = TRUE, check.names = FALSE)
sample <- read.table(sampleFile, header = TRUE, check.names = FALSE)
plot <- ggplot() +
geom_point(data = ref, aes(x = PC1, y = PC2, colour = popID), shape = 1) +
geom_point(data = sample, aes(x = PC1, y = PC2), shape = 18, size = 4) +
scale_colour_discrete(name = "Population") +
theme_bw(12) +
ggtitle(title) +
labs(x = xlabel, y = ylabel)
ggsave(filename = outputFile, height = 10, width = 10)
|
###########################################################
# This script trains 1Q-ahead RR, SVR, KNN and RF models #
# Preliminaries: #
source("code/prem_v1.R") # Import data #
# Import libraries #
library(MASS) #
library(e1071) #
library(caret) #
library(randomForest) #
# Import functions #
source("code/rr.R") # RR function #
source("code/svr.R") # SVR function #
source("code/knn.R") # KNN function #
source("code/rf.R") # RF function #
###########################################################
### Warmup period
warm.end <- c(1965,4)
### Ridge regression
set.seed(123)
# 1q
rr.1q.4lag <- RidgeReg(warm.end=warm.end, lags = 4, lambdas = 2^seq.int(-5, 5, 0.5), forecast.ahead = 1,
val.size = 4)
rr.1q.3lag <- RidgeReg(warm.end=warm.end, lags = 3, lambdas = 2^seq.int(-5, 5, 0.5), forecast.ahead = 1,
val.size = 4)
rr.1q.2lag <- RidgeReg(warm.end=warm.end, lags = 2, lambdas = 2^seq.int(-5, 5, 0.5), forecast.ahead = 1,
val.size = 4)
rr.1q.1lag <- RidgeReg(warm.end=warm.end, lags = 1, lambdas = 2^seq.int(-5, 5, 0.5), forecast.ahead = 1,
val.size = 4)
### SVR: Linear
set.seed(123)
# 1q
svr.linear.1q.4lag <- SVR(warm.end=warm.end, lags = 4, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-7, 1, 0.5), kernel="linear")
svr.linear.1q.3lag <- SVR(warm.end=warm.end, lags = 3, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-7, 1, 0.5), kernel="linear")
svr.linear.1q.2lag <- SVR(warm.end=warm.end, lags = 2, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-7, 1, 0.5), kernel="linear")
svr.linear.1q.1lag <- SVR(warm.end=warm.end, lags = 1, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-7, 1, 0.5), kernel="linear")
### SVR: Radial
set.seed(123)
# 1q
svr.radial.1q.4lag <- SVR(warm.end=warm.end, lags = 4, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-3, 3, 0.5), gamma=2^seq.int(-5,1,0.5),
kernel="radial")
svr.radial.1q.3lag <- SVR(warm.end=warm.end, lags = 3, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-3, 3, 0.5), gamma=2^seq.int(-5,1,0.5),
kernel="radial")
svr.radial.1q.2lag <- SVR(warm.end=warm.end, lags = 2, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-3, 3, 0.5), gamma=2^seq.int(-5,1,0.5),
kernel="radial")
svr.radial.1q.1lag <- SVR(warm.end=warm.end, lags = 1, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-3, 3, 0.5), gamma=2^seq.int(-5,1,0.5),
kernel="radial")
### KNN
set.seed(123)
# 1q ahead
knn.1q.4lag <- KNNReg(warm.end=warm.end, lags = 4, forecast.ahead = 1, val.size = 4,
neighbours = 1:50)
knn.1q.3lag <- KNNReg(warm.end=warm.end, lags = 3, forecast.ahead = 1, val.size = 4,
neighbours = 1:50)
knn.1q.2lag <- KNNReg(warm.end=warm.end, lags = 2, forecast.ahead = 1, val.size = 4,
neighbours = 1:50)
knn.1q.1lag <- KNNReg(warm.end=warm.end, lags = 1, forecast.ahead = 1, val.size = 4,
neighbours = 1:50)
### RF
set.seed(123)
# 1q
rf.1q.4lag <- RF(warm.end=warm.end, lags = 4, forecast.ahead = 1, val.size = 4,
mtry=c(1:(3*4)), nodesize=c(1,3,5,8), ntree=1000)
rf.1q.3lag <- RF(warm.end=warm.end, lags = 3, forecast.ahead = 1, val.size = 4,
mtry=c(1:(3*3)), nodesize=c(1,3,5,8), ntree=1000)
rf.1q.2lag <- RF(warm.end=warm.end, lags = 2, forecast.ahead = 1, val.size = 4,
mtry=c(1:(3*2)), nodesize=c(1,3,5,8), ntree=1000)
rf.1q.1lag <- RF(warm.end=warm.end, lags = 1, forecast.ahead = 1, val.size = 4,
mtry=c(1:(3*1)), nodesize=c(1,3,5,8), ntree=1000)
| /code/1Q_trainer.R | no_license | limmyh53/thesis-code | R | false | false | 4,290 | r | ###########################################################
# This script trains 1Q-ahead RR, SVR, KNN and RF models #
# Preliminaries: #
source("code/prem_v1.R") # Import data #
# Import libraries #
library(MASS) #
library(e1071) #
library(caret) #
library(randomForest) #
# Import functions #
source("code/rr.R") # RR function #
source("code/svr.R") # SVR function #
source("code/knn.R") # KNN function #
source("code/rf.R") # RF function #
###########################################################
### Warmup period
warm.end <- c(1965,4)
### Ridge regression
set.seed(123)
# 1q
rr.1q.4lag <- RidgeReg(warm.end=warm.end, lags = 4, lambdas = 2^seq.int(-5, 5, 0.5), forecast.ahead = 1,
val.size = 4)
rr.1q.3lag <- RidgeReg(warm.end=warm.end, lags = 3, lambdas = 2^seq.int(-5, 5, 0.5), forecast.ahead = 1,
val.size = 4)
rr.1q.2lag <- RidgeReg(warm.end=warm.end, lags = 2, lambdas = 2^seq.int(-5, 5, 0.5), forecast.ahead = 1,
val.size = 4)
rr.1q.1lag <- RidgeReg(warm.end=warm.end, lags = 1, lambdas = 2^seq.int(-5, 5, 0.5), forecast.ahead = 1,
val.size = 4)
### SVR: Linear
set.seed(123)
# 1q
svr.linear.1q.4lag <- SVR(warm.end=warm.end, lags = 4, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-7, 1, 0.5), kernel="linear")
svr.linear.1q.3lag <- SVR(warm.end=warm.end, lags = 3, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-7, 1, 0.5), kernel="linear")
svr.linear.1q.2lag <- SVR(warm.end=warm.end, lags = 2, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-7, 1, 0.5), kernel="linear")
svr.linear.1q.1lag <- SVR(warm.end=warm.end, lags = 1, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-7, 1, 0.5), kernel="linear")
### SVR: Radial
set.seed(123)
# 1q
svr.radial.1q.4lag <- SVR(warm.end=warm.end, lags = 4, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-3, 3, 0.5), gamma=2^seq.int(-5,1,0.5),
kernel="radial")
svr.radial.1q.3lag <- SVR(warm.end=warm.end, lags = 3, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-3, 3, 0.5), gamma=2^seq.int(-5,1,0.5),
kernel="radial")
svr.radial.1q.2lag <- SVR(warm.end=warm.end, lags = 2, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-3, 3, 0.5), gamma=2^seq.int(-5,1,0.5),
kernel="radial")
svr.radial.1q.1lag <- SVR(warm.end=warm.end, lags = 1, forecast.ahead = 1, val.size = 4,
cost = 2^seq.int(-3, 3, 0.5), gamma=2^seq.int(-5,1,0.5),
kernel="radial")
### KNN
set.seed(123)
# 1q ahead
knn.1q.4lag <- KNNReg(warm.end=warm.end, lags = 4, forecast.ahead = 1, val.size = 4,
neighbours = 1:50)
knn.1q.3lag <- KNNReg(warm.end=warm.end, lags = 3, forecast.ahead = 1, val.size = 4,
neighbours = 1:50)
knn.1q.2lag <- KNNReg(warm.end=warm.end, lags = 2, forecast.ahead = 1, val.size = 4,
neighbours = 1:50)
knn.1q.1lag <- KNNReg(warm.end=warm.end, lags = 1, forecast.ahead = 1, val.size = 4,
neighbours = 1:50)
### RF
set.seed(123)
# 1q
rf.1q.4lag <- RF(warm.end=warm.end, lags = 4, forecast.ahead = 1, val.size = 4,
mtry=c(1:(3*4)), nodesize=c(1,3,5,8), ntree=1000)
rf.1q.3lag <- RF(warm.end=warm.end, lags = 3, forecast.ahead = 1, val.size = 4,
mtry=c(1:(3*3)), nodesize=c(1,3,5,8), ntree=1000)
rf.1q.2lag <- RF(warm.end=warm.end, lags = 2, forecast.ahead = 1, val.size = 4,
mtry=c(1:(3*2)), nodesize=c(1,3,5,8), ntree=1000)
rf.1q.1lag <- RF(warm.end=warm.end, lags = 1, forecast.ahead = 1, val.size = 4,
mtry=c(1:(3*1)), nodesize=c(1,3,5,8), ntree=1000)
|
library(shiny);library(shinydashboard);library(dplyr);library(plotly);
library(shinyWidgets);library(scales);library(tidyr);library(zoo);
library(reshape2);library(ggplot2);library(DT);library(rsconnect);
library(lubridate);library(gtable);library(viridis);library(grid);
library(rsconnect);library(googleVis)
function(input, output, session) {
load("data/00 loan.RData")
load("data/00 macro.RData")
load("data/01 zdata.RData")
load("data/02 df_back.RData")
load("data/03 macro_desc.RData")
load("data/04 final_model_loose.RData")
load("data/04 final_model_tight.RData")
load("data/05 z_final.RData")
load("data/06 test_desc.RData")
load("data/07 sign_desc.RData")
load("data/08 df_final.RData")
source("functions.R", local = TRUE)
source("01 cnt.R", local = TRUE)
source("02 df.R", local = TRUE)
source("03 mg.R", local = TRUE)
source("04 runoff.R", local = TRUE)
source("05 zscore.R", local = TRUE)
source("06 df_back.R", local = TRUE)
source("07 z_macro.R", local = TRUE)
source("08 v_select.R", local = TRUE)
source("09 m_select.R", local = TRUE)
source("10 pred_z.R", local = TRUE)
} | /server.R | no_license | jiayingg/Transition-Matrix-Model-using-Moodys-Data | R | false | false | 1,142 | r | library(shiny);library(shinydashboard);library(dplyr);library(plotly);
library(shinyWidgets);library(scales);library(tidyr);library(zoo);
library(reshape2);library(ggplot2);library(DT);library(rsconnect);
library(lubridate);library(gtable);library(viridis);library(grid);
library(rsconnect);library(googleVis)
function(input, output, session) {
load("data/00 loan.RData")
load("data/00 macro.RData")
load("data/01 zdata.RData")
load("data/02 df_back.RData")
load("data/03 macro_desc.RData")
load("data/04 final_model_loose.RData")
load("data/04 final_model_tight.RData")
load("data/05 z_final.RData")
load("data/06 test_desc.RData")
load("data/07 sign_desc.RData")
load("data/08 df_final.RData")
source("functions.R", local = TRUE)
source("01 cnt.R", local = TRUE)
source("02 df.R", local = TRUE)
source("03 mg.R", local = TRUE)
source("04 runoff.R", local = TRUE)
source("05 zscore.R", local = TRUE)
source("06 df_back.R", local = TRUE)
source("07 z_macro.R", local = TRUE)
source("08 v_select.R", local = TRUE)
source("09 m_select.R", local = TRUE)
source("10 pred_z.R", local = TRUE)
} |
# Lab 3 - Decomposition and Forecasting
# Decomposition of air passenger data
library(forecast)
library(tseries)
y=AirPassengers
# Note the ACF
tsdisplay(y)
# ADF to check for unit roots
# We obtain a p-value here of less than 0.01 so we reject the null hypothesis that w = 0 i.e. phi1 = 1.
# Thus there is no unit root and the series does not require differencing to get to stationarity.
adf.test(y)
# We estimate the trend component by smoothing out the seasonal component first
TC=ma(y,12)
# We try to fit a linear model to this
linear_tc=lm(TC~time(y))
# We get an even clearer picture of the seasonal trend by plotting a detrended timer series
tsdisplay(y~TC)
# Taking the average of the resulting series
# for corresponding months gives us an estimate of the seasonal component.
pseudo_s = y/TC
matrix_s = matrix(pseudo_s,nrow=12)
s = rowMeans(matrix_s,na.rm=TRUE)
S = rep(s,length(y)/12)
# We centre our seasonal component
S = S/mean(S)
# Finally, we can estimate our random component
R=y/(TC*S)
# We can use decompose()
#################################################################################
# Forecasting
# Extrapolate the trend x seasonal components 2 years ahead
ftime=seq(time(y)[length(y)]+deltat(y),length=24,by=deltat(y)) # future times
d_fy=(linear_tc$coef[1]+linear_tc$coef[2]*ftime)*rep(S[1:12],2)
# Predict 2 years ahead for the random component
fit=Arima(R,order=c(2,0,1))
fy=forecast(fit,h=24)
# Multiply the trend prediction, seasonal prediction, and
# random prediction mean to get your mean forecast.
msef=d_fy*fy$mean
# Upper and lower 95% CI for the forecast
y.low95=d_fy*fy$lower[,2]
y.high95=d_fy*fy$upper[,2]
# Then plot the forecast
plot(y,xlim=c(time(y)[1],ftime[length(ftime)]),ylim=c(0,700))
lines(ftime, msef, col=4)
polygon(c(ftime, rev(ftime)), c(y.high95, rev(y.low95)),
col=rgb(0,0,1,alpha=0.1),border=NA)
###############################################################################
library(TSA)
data(beersales)
summary(beersales)
# Exercise 1
x <- ts(beersales, start = c(1975, 1), end = c(1990, 12), frequency = 12)
tsdisplay(beersales)
adf.test(beersales)
# Exercise 2
# Detrend using additive model and decompose()
x <- beersales
#A
TC=ma(x,12)
plot(TC)
#B
x = ts(x, freq = 12).
decompose_x = decompose(x,"additive")
plot(as.ts(decompose_x$seasonal))
plot(as.ts(decompose_x$trend))
plot(as.ts(decompose_x$random))
plot(decompose_x)
# Exercise 3
# Basics
# US monthly electricity production between 1973-2005
data("electricity")
head(electricity)
y<-electricity
plot(y)
decompose_y = decompose(y, type = "additive")
plot(decompose_y)
#A
fit<-forecast(decompose_y$seasonal+decompose_y$trend, h=24, level=0.95)
plot(fit)
#B
# Plot random component for next 2 years
plot(decompose_y$random)
plot(forecast(decompose_y$random, h=24))
#C
# plot the forecast @ 95% CI
plot(forecast(y, h=24, level=0.95))
#######
# Extrapolate the trend + seasonal components 2 years ahead
ftime=seq(time(y)[length(y)]+deltat(y),length=24,by=deltat(y)) # future times
d_fy=(linear_tc$coef[1]+linear_tc$coef[2]+ftime)*rep(S[1:12],2)
plot(forecast(d_fy, h=24))
# Predict 2 years ahead for the random component
fit=Arima(R,order=c(2,0,1))
fy=forecast(fit,h=24)
plot(fit)
plot(tsrandom(y))
# Then plot the forecast
fcast<-plot(forecast(y, h=24, level=0.95))
autoplot(forecast(y)) +
ylab="New orders index")
TC=ma(y,12)
linear_tc=lm(TC~time(y))
tsdisplay(y-TC)
library(TSA)
library(forecast)
###########################################################################
# A test of decomposition and forecasting
install.packages("fpp")
library(fpp)
data("electricity")
y = electricity
plot(as.ts(y))
# Detect the trend
install.packages("forecast")
library(forecast)
trend_y = ma(y, order = 12, centre = T)
plot(as.ts(y))
lines(trend_y)
plot(as.ts(trend_y))
# Now detrend to check seasonality
detrend_y = y - trend_y
plot(as.ts(detrend_y))
# Average seasonality
m_y = t(matrix(data = detrend_y, nrow = 12))
seasonal_y = colMeans(m_y, na.rm = T)
plot(as.ts(rep(seasonal_y,16)))
# Random noise remaining
random_y = y - trend_y - seasonal_y
plot(as.ts(random_y))
# Reconstruct original signal
recomposed_y = trend_y+seasonal_y+random_y
plot(as.ts(recomposed_y))
# Finally - using decompose()
y = ts(y, frequency = 12)
decompose_y = decompose(y, "additive")
plot(as.ts(decompose_y$seasonal))
plot(as.ts(decompose_y$trend))
plot(as.ts(decompose_y$random))
plot(decompose_y)
| /timeseries/Time_Series_Decomposition_Forecasting.R | no_license | damienmartindarcy/Fundamentals | R | false | false | 4,663 | r | # Lab 3 - Decomposition and Forecasting
# Decomposition of air passenger data
library(forecast)
library(tseries)
y=AirPassengers
# Note the ACF
tsdisplay(y)
# ADF to check for unit roots
# We obtain a p-value here of less than 0.01 so we reject the null hypothesis that w = 0 i.e. phi1 = 1.
# Thus there is no unit root and the series does not require differencing to get to stationarity.
adf.test(y)
# We estimate the trend component by smoothing out the seasonal component first
TC=ma(y,12)
# We try to fit a linear model to this
linear_tc=lm(TC~time(y))
# We get an even clearer picture of the seasonal trend by plotting a detrended timer series
tsdisplay(y~TC)
# Taking the average of the resulting series
# for corresponding months gives us an estimate of the seasonal component.
pseudo_s = y/TC
matrix_s = matrix(pseudo_s,nrow=12)
s = rowMeans(matrix_s,na.rm=TRUE)
S = rep(s,length(y)/12)
# We centre our seasonal component
S = S/mean(S)
# Finally, we can estimate our random component
R=y/(TC*S)
# We can use decompose()
#################################################################################
# Forecasting
# Extrapolate the trend x seasonal components 2 years ahead
ftime=seq(time(y)[length(y)]+deltat(y),length=24,by=deltat(y)) # future times
d_fy=(linear_tc$coef[1]+linear_tc$coef[2]*ftime)*rep(S[1:12],2)
# Predict 2 years ahead for the random component
fit=Arima(R,order=c(2,0,1))
fy=forecast(fit,h=24)
# Multiply the trend prediction, seasonal prediction, and
# random prediction mean to get your mean forecast.
msef=d_fy*fy$mean
# Upper and lower 95% CI for the forecast
y.low95=d_fy*fy$lower[,2]
y.high95=d_fy*fy$upper[,2]
# Then plot the forecast
plot(y,xlim=c(time(y)[1],ftime[length(ftime)]),ylim=c(0,700))
lines(ftime, msef, col=4)
polygon(c(ftime, rev(ftime)), c(y.high95, rev(y.low95)),
col=rgb(0,0,1,alpha=0.1),border=NA)
###############################################################################
library(TSA)
data(beersales)
summary(beersales)
# Exercise 1
x <- ts(beersales, start = c(1975, 1), end = c(1990, 12), frequency = 12)
tsdisplay(beersales)
adf.test(beersales)
# Exercise 2
# Detrend using additive model and decompose()
x <- beersales
#A
TC=ma(x,12)
plot(TC)
#B
x = ts(x, freq = 12).
decompose_x = decompose(x,"additive")
plot(as.ts(decompose_x$seasonal))
plot(as.ts(decompose_x$trend))
plot(as.ts(decompose_x$random))
plot(decompose_x)
# Exercise 3
# Basics
# US monthly electricity production between 1973-2005
data("electricity")
head(electricity)
y<-electricity
plot(y)
decompose_y = decompose(y, type = "additive")
plot(decompose_y)
#A
fit<-forecast(decompose_y$seasonal+decompose_y$trend, h=24, level=0.95)
plot(fit)
#B
# Plot random component for next 2 years
plot(decompose_y$random)
plot(forecast(decompose_y$random, h=24))
#C
# plot the forecast @ 95% CI
plot(forecast(y, h=24, level=0.95))
#######
# Extrapolate the trend + seasonal components 2 years ahead
ftime=seq(time(y)[length(y)]+deltat(y),length=24,by=deltat(y)) # future times
d_fy=(linear_tc$coef[1]+linear_tc$coef[2]+ftime)*rep(S[1:12],2)
plot(forecast(d_fy, h=24))
# Predict 2 years ahead for the random component
fit=Arima(R,order=c(2,0,1))
fy=forecast(fit,h=24)
plot(fit)
plot(tsrandom(y))
# Then plot the forecast
fcast<-plot(forecast(y, h=24, level=0.95))
autoplot(forecast(y)) +
ylab="New orders index")
TC=ma(y,12)
linear_tc=lm(TC~time(y))
tsdisplay(y-TC)
library(TSA)
library(forecast)
###########################################################################
# A test of decomposition and forecasting
install.packages("fpp")
library(fpp)
data("electricity")
y = electricity
plot(as.ts(y))
# Detect the trend
install.packages("forecast")
library(forecast)
trend_y = ma(y, order = 12, centre = T)
plot(as.ts(y))
lines(trend_y)
plot(as.ts(trend_y))
# Now detrend to check seasonality
detrend_y = y - trend_y
plot(as.ts(detrend_y))
# Average seasonality
m_y = t(matrix(data = detrend_y, nrow = 12))
seasonal_y = colMeans(m_y, na.rm = T)
plot(as.ts(rep(seasonal_y,16)))
# Random noise remaining
random_y = y - trend_y - seasonal_y
plot(as.ts(random_y))
# Reconstruct original signal
recomposed_y = trend_y+seasonal_y+random_y
plot(as.ts(recomposed_y))
# Finally - using decompose()
y = ts(y, frequency = 12)
decompose_y = decompose(y, "additive")
plot(as.ts(decompose_y$seasonal))
plot(as.ts(decompose_y$trend))
plot(as.ts(decompose_y$random))
plot(decompose_y)
|
context("Testing Darfur Example")
# runs regression model
data("darfur")
model2 <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village,
data = within(darfur, directlyharmed <- directlyharmed*(-1)))
model <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur)
test_that("testing darfur data", {
expect_equal(dim(darfur), c(1276, 14))
expect_equal(colnames(darfur),
c("wouldvote",
"peacefactor",
"peace_formerenemies",
"peace_jjindiv",
"peace_jjtribes",
"gos_soldier_execute",
"directlyharmed",
"age",
"farmer_dar",
"herder_dar",
"pastvoted",
"hhsize_darfur",
"village",
"female"))
})
test_that(desc = "testing darfur sensemakr",
{
darfur_out <- sensemakr(model, treatment = "directlyharmed", benchmark_covariates = "female", kd = 1:3)
plot(darfur_out)
ovb_contour_plot(darfur_out)
ovb_extreme_plot(darfur_out)
# info
expect_equal(darfur_out$info$formula, peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village)
expect_equal(darfur_out$info$treatment, "directlyharmed")
expect_equal(darfur_out$info$q, 1)
expect_equal(darfur_out$info$alpha, 0.05)
expect_equal(darfur_out$info$reduce, TRUE)
# sensitivity stats
expect_equal(darfur_out$sensitivity_stats$dof, 783)
expect_equal(darfur_out$sensitivity_stats$r2yd.x, 0.02187, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_q), 0.13878, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_qa), 0.07626, tolerance = 1e-5)
# bounds
check_bounds <- structure(list(bound_label = c("1x female", "2x female", "3x female"),
r2dz.x = c(0.00916428667504862, 0.0183285733500972, 0.0274928600251459),
r2yz.dx = c(0.12464092303637, 0.249324064199975, 0.374050471038094),
treatment = rep("directlyharmed", 3),
adjusted_estimate = c(0.0752202712144491, 0.0529151723844518, 0.0303960234641548),
adjusted_se = c(0.0218733277437572, 0.0203500620779637, 0.0186700648170924),
adjusted_t = c(3.43890386024675, 2.60024623913809, 1.62806202131271),
adjusted_lower_CI = c(0.032282966, 0.012968035,-0.006253282),
adjusted_upper_CI = c(0.11815758, 0.09286231, 0.06704533)
),
.Names = c("bound_label", "r2dz.x", "r2yz.dx", "treatment",
"adjusted_estimate", "adjusted_se", "adjusted_t",
"adjusted_lower_CI", "adjusted_upper_CI"),
row.names = c(NA, -3L), class = c("ovb_bounds", "data.frame"))
expect_equivalent(darfur_out$bounds, check_bounds)
out1 <- capture.output(darfur_out)
out1 <- capture.output(summary(darfur_out))
out3 <- capture.output(ovb_minimal_reporting(darfur_out))
darfur_out2 <- sensemakr(model, treatment = "directlyharmed")
plot(darfur_out2)
ovb_contour_plot(darfur_out2)
ovb_extreme_plot(darfur_out2)
out3 <- capture.output(ovb_minimal_reporting(darfur_out2))
})
test_that(desc = "testing darfur sensemakr but negative",
{
darfur_out <- sensemakr(model2, treatment = "directlyharmed", benchmark_covariates = "female", kd = 1:3)
plot(darfur_out)
ovb_contour_plot(darfur_out)
ovb_extreme_plot(darfur_out)
# info
expect_equal(darfur_out$info$formula, peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village)
expect_equal(darfur_out$info$treatment, "directlyharmed")
expect_equal(darfur_out$info$q, 1)
expect_equal(darfur_out$info$alpha, 0.05)
expect_equal(darfur_out$info$reduce, TRUE)
# sensitivity stats
expect_equal(darfur_out$sensitivity_stats$dof, 783)
expect_equal(darfur_out$sensitivity_stats$r2yd.x, 0.02187, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_q), 0.13878, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_qa), 0.07626, tolerance = 1e-5)
# bounds
check_bounds <- structure(list(bound_label = c("1x female", "2x female", "3x female"),
r2dz.x = c(0.00916428667504862, 0.0183285733500972, 0.0274928600251459),
r2yz.dx = c(0.12464092303637, 0.249324064199975, 0.374050471038094),
treatment = rep("directlyharmed", 3),
adjusted_estimate = c(-0.0752202712144491, -0.0529151723844518, -0.0303960234641548),
adjusted_se = c(0.0218733277437572, 0.0203500620779637, 0.0186700648170924),
adjusted_t = c(-3.43890386024675, -2.60024623913809, -1.62806202131271),
adjusted_lower_CI = -1*c(0.11815758, 0.09286231, 0.06704533),
adjusted_upper_CI = -1*c(0.032282966, 0.012968035,-0.006253282)
),
.Names = c("bound_label", "r2dz.x", "r2yz.dx", "treatment",
"adjusted_estimate", "adjusted_se", "adjusted_t",
"adjusted_lower_CI", "adjusted_upper_CI"),
row.names = c(NA, -3L), class = c("ovb_bounds", "data.frame"))
expect_equivalent(darfur_out$bounds, check_bounds)
out1 <- capture.output(darfur_out)
out1 <- capture.output(summary(darfur_out))
out3 <- capture.output(ovb_minimal_reporting(darfur_out))
darfur_out2 <- sensemakr(model, treatment = "directlyharmed")
plot(darfur_out2)
ovb_contour_plot(darfur_out2)
ovb_extreme_plot(darfur_out2)
out3 <- capture.output(ovb_minimal_reporting(darfur_out2))
})
test_that("testing darfur manual bounds",
{
sense.out <- sensemakr(model, treatment = "directlyharmed", benchmark_covariates = "female", r2dz.x = .1)
bounds.check <- sense.out$bounds
to_check <- bounds.check$adjusted_se[1]
true_check <- adjusted_se(model, treatment = "directlyharmed", r2dz.x = .1, r2yz.dx = .1)
expect_equal(to_check, unname(true_check))
}
)
test_that(desc = "testing darfur sensemakr with formula",
{
darfur_out <- sensemakr(formula = peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur, treatment = "directlyharmed", benchmark_covariates = "female", kd = 1:3)
# info
expect_equal(darfur_out$info$formula, peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village)
expect_equal(darfur_out$info$treatment, "directlyharmed")
expect_equal(darfur_out$info$q, 1)
expect_equal(darfur_out$info$alpha, 0.05)
expect_equal(darfur_out$info$reduce, TRUE)
# sensitivity stats
expect_equal(darfur_out$sensitivity_stats$dof, 783)
expect_equal(darfur_out$sensitivity_stats$r2yd.x, 0.02187, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_q), 0.13878, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_qa), 0.07626, tolerance = 1e-5)
# bounds
check_bounds <- structure(list(bound_label = c("1x female", "2x female", "3x female"),
r2dz.x = c(0.00916428667504862, 0.0183285733500972, 0.0274928600251459),
r2yz.dx = c(0.12464092303637, 0.249324064199975, 0.374050471038094),
treatment = rep("directlyharmed", 3),
adjusted_estimate = c(0.0752202712144491, 0.0529151723844518, 0.0303960234641548),
adjusted_se = c(0.0218733277437572, 0.0203500620779637, 0.0186700648170924),
adjusted_t = c(3.43890386024675, 2.60024623913809, 1.62806202131271),
adjusted_lower_CI = c(0.032282966, 0.012968035,-0.006253282),
adjusted_upper_CI = c(0.11815758, 0.09286231, 0.06704533)),
.Names = c("bound_label", "r2dz.x", "r2yz.dx", "treatment",
"adjusted_estimate", "adjusted_se", "adjusted_t",
"adjusted_lower_CI", "adjusted_upper_CI"),
row.names = c(NA, -3L), class = c("ovb_bounds", "data.frame"))
expect_equivalent(darfur_out$bounds, check_bounds)
})
test_that(desc = "testing darfur sensemakr manually",
{
model.treat <- lm(directlyharmed ~ age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur)
darfur_out <- sensemakr(estimate = 0.09731582,
se = 0.02325654,
dof = 783,
treatment = "directlyharmed",
benchmark_covariates = "female",
r2dxj.x = partial_r2(model.treat, covariates = "female"),
r2yxj.dx = partial_r2(model, covariates = "female"),
kd = 1:3)
plot(darfur_out)
plot(darfur_out, type = "extreme")
plot(darfur_out, sensitivity.of = "t-value")
add_bound_to_contour(0.3,0.3, "test")
# info
expect_equal(darfur_out$info$formula, "Data provided manually")
expect_equal(darfur_out$info$treatment, "directlyharmed")
expect_equal(darfur_out$info$q, 1)
expect_equal(darfur_out$info$alpha, 0.05)
expect_equal(darfur_out$info$reduce, TRUE)
# sensitivity stats
expect_equal(darfur_out$sensitivity_stats$dof, 783)
expect_equal(darfur_out$sensitivity_stats$r2yd.x, 0.02187, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_q), 0.13878, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_qa), 0.07626, tolerance = 1e-5)
# bounds
check_bounds <-
structure(
list(
bound_label = c("1x female", "2x female", "3x female"),
r2dz.x = c(0.00916428667504862, 0.0183285733500972, 0.0274928600251459),
r2yz.dx = c(0.12464092303637, 0.249324064199975, 0.374050471038094),
adjusted_estimate = c(0.0752202698486415, 0.0529151689180575,
0.0303960178770157),
adjusted_se = c(0.0218733298036818, 0.0203500639944344,
0.0186700665753491),
adjusted_t = c(3.43890347394571, 2.60024582392121,
1.62806156873318),
adjusted_lower_CI = c(0.0322829603180086,
0.0129680276030601, -0.00625329133645187),
adjusted_upper_CI = c(0.118157579379274,
0.092862310233055, 0.0670453270904833)
),
row.names = c(NA, -3L),
class = "data.frame"
)
expect_equivalent(as.data.frame(darfur_out$bounds), as.data.frame(check_bounds))
})
test_that(desc = "testing darfur sensitivity stats",{
# checks RV
## RV q = 1
rv <- robustness_value(model, covariates = "directlyharmed")
expect_equivalent(c(rv), 0.138776, tolerance = 1e-5)
expect_equivalent(attributes(rv)$q, 1)
expect_equivalent(attributes(rv)$names, "directlyharmed")
## RV q = 1, alpha = 0.05
rv <- robustness_value(model, covariates = "directlyharmed", q = 1, alpha = 0.05)
expect_equivalent(c(rv), 0.07625797, tolerance = 1e-5)
expect_equivalent(attributes(rv)$q, 1)
expect_equivalent(attributes(rv)$alpha, 0.05)
expect_equivalent(attributes(rv)$names, "directlyharmed")
# checks partial R2
r2 <- partial_r2(model, covariates = "directlyharmed")
expect_equivalent(r2, 0.02187309, tolerance = 1e-5)
# checks partial f2
f2 <- partial_f2(model, covariates = "directlyharmed")
expect_equivalent(f2, 0.02236222, tolerance = 1e-5)
# sensitivity stats
sens_stats <- sensitivity_stats(model, treatment = "directlyharmed")
expect_equivalent(sens_stats$treatment, "directlyharmed")
expect_equivalent(sens_stats$estimate, 0.09731582, tolerance = 1e5)
expect_equivalent(sens_stats$se, 0.02325654, tolerance = 1e5)
expect_equivalent(sens_stats$t_statistic, 4.18445, tolerance = 1e5)
expect_equivalent(sens_stats$r2yd.x, 0.02187309, tolerance = 1e5)
expect_equivalent(sens_stats$rv_q , 0.1387764, tolerance = 1e5)
expect_equivalent(sens_stats$rv_qa , 0.07625797, tolerance = 1e5)
expect_equivalent(sens_stats$f2yd.x , 0.02236222, tolerance = 1e5)
expect_equivalent(sens_stats$dof , 783, tolerance = 1e5)
expect_equivalent(group_partial_r2(model, covariates = "directlyharmed"), partial_r2(model, covariates = "directlyharmed"))
expect_error(group_partial_r2(model))
expect_equal(group_partial_r2(model, covariates = c("directlyharmed", "female")), 0.1350435, tolerance = 1e-5)
})
test_that(desc = "testing darfur adjusted estimates",{
should_be_zero <- adjusted_estimate(model, treatment = "directlyharmed", r2yz.dx = 1, r2dz.x = partial_r2(model, covariates = "directlyharmed"))
expect_equivalent(should_be_zero, 0)
rv <- robustness_value(model, covariates = "directlyharmed")
should_be_zero <- adjusted_estimate(model, treatment = "directlyharmed", r2yz.dx = rv, r2dz.x = rv)
expect_equivalent(should_be_zero, 0)
rv <- robustness_value(model, covariates = "directlyharmed", alpha = 0.05)
thr <- qt(0.975, df = 783 - 1)
should_be_1.96 <- adjusted_t(model, treatment = "directlyharmed", r2yz.dx = rv, r2dz.x = rv)
expect_equivalent(c(should_be_1.96), thr)
should_be_estimate <- bias(model, treatment = "directlyharmed", r2yz.dx = 1, r2dz.x = partial_r2(model, covariates = "directlyharmed"))
expect_equivalent(should_be_estimate, coef(model)["directlyharmed"])
rv <- robustness_value(model, covariates = "directlyharmed")
should_be_estimate <- bias(model, treatment = "directlyharmed", r2yz.dx = rv, r2dz.x = rv)
expect_equivalent(should_be_estimate, coef(model)["directlyharmed"])
rv <- robustness_value(model, covariates = "directlyharmed", q = 0.5)
should_be_half_estimate <- bias(model, treatment = "directlyharmed", r2yz.dx = rv, r2dz.x = rv)
expect_equivalent(should_be_half_estimate, coef(model)["directlyharmed"]/2)
})
test_that(desc = "testing darfur plots",
{
# testing countour output with internal functions
## point estimate
contour_out <- ovb_contour_plot(model, treatment = "directlyharmed",
benchmark_covariates = "female",kd = 1:3)
add_bound_to_contour(model, treatment = "directlyharmed",
benchmark_covariates = "age", kd = 10)
add_bound_to_contour(model, treatment = "directlyharmed",
benchmark_covariates = "age", kd = 200, ky = 20)
adj_est <- adjusted_estimate(model, treatment = "directlyharmed",
r2dz.x = contour_out$r2dz.x[10],
r2yz.dx = contour_out$r2yz.dx[1])
expect_equivalent(adj_est, contour_out$value[10])
bounds <- ovb_bounds(model,
treatment = "directlyharmed",
benchmark_covariates = "female",
kd = 1:3)
expect_equivalent(contour_out$bounds, bounds[c(2,3,1)])
## t-value
contour_out <- ovb_contour_plot(model, treatment = "directlyharmed",
benchmark_covariates = "female",kd = 1:3,
sensitivity.of = "t-value")
add_bound_to_contour(model, treatment = "directlyharmed", benchmark_covariates = "age",
kd = 200, ky = 10, sensitivity.of = "t-value")
adj_t <- adjusted_t(model, treatment = "directlyharmed",
r2dz.x = contour_out$r2dz.x[10],
r2yz.dx = contour_out$r2yz.dx[1])
expect_equivalent(adj_t, contour_out$value[10])
bounds <- ovb_bounds(model,
treatment = "directlyharmed",
benchmark_covariates = "female",
kd = 1:3)
expect_equivalent(contour_out$bounds, bounds[c(2,3,1)])
# tests bounds numerically
expect_equivalent(bounds$adjusted_estimate, c(0.0752202712144491, 0.0529151723844518, 0.0303960234641548))
expect_equivalent(bounds$adjusted_t, c(3.43890386024675, 2.60024623913809, 1.62806202131271))
# test extreme scenario plot
extreme_out <- ovb_extreme_plot(model, treatment = "directlyharmed", kd = 1:3)
adj_est <- adjusted_estimate(model, treatment = "directlyharmed",
r2yz.dx = 1,
r2dz.x = extreme_out$scenario_r2yz.dx_1$r2dz.x[5])
expect_equivalent(adj_est, extreme_out$scenario_r2yz.dx_1$adjusted_estimate[5])
}
)
test_that("testing darfur print",
{
skip_on_cran()
darfur_out <- sensemakr(model, treatment = "directlyharmed", benchmark_covariates = "female", kd = 1:3)
darfur_out2 <- sensemakr(model, treatment = "directlyharmed")
print.sense <- "Sensitivity Analysis to Unobserved Confounding\n\nModel Formula: peacefactor ~ directlyharmed + age + farmer_dar + herder_dar + \n pastvoted + hhsize_darfur + female + village\n\nNull hypothesis: q = 1 and reduce = TRUE \n\nUnadjusted Estimates of ' directlyharmed ':\n Coef. estimate: 0.09732 \n Standard Error: 0.02326 \n t-value: 4.18445 \n\nSensitivity Statistics:\n Partial R2 of treatment with outcome: 0.02187 \n Robustness Value, q = 1 : 0.13878 \n Robustness Value, q = 1 alpha = 0.05 : 0.07626 \n\nFor more information, check summary."
compare <- capture_output(print(darfur_out))
expect_equal(compare, print.sense)
summary.sense <- "Sensitivity Analysis to Unobserved Confounding\n\nModel Formula: peacefactor ~ directlyharmed + age + farmer_dar + herder_dar + \n pastvoted + hhsize_darfur + female + village\n\nNull hypothesis: q = 1 and reduce = TRUE \n-- This means we are considering biases that reduce the absolute value of the current estimate.\n-- The null hypothesis deemed problematic is H0:tau = 0 \n\nUnadjusted Estimates of 'directlyharmed': \n Coef. estimate: 0.0973 \n Standard Error: 0.0233 \n t-value (H0:tau = 0): 4.1844 \n\nSensitivity Statistics:\n Partial R2 of treatment with outcome: 0.0219 \n Robustness Value, q = 1: 0.1388 \n Robustness Value, q = 1, alpha = 0.05: 0.0763 \n\nVerbal interpretation of sensitivity statistics:\n\n-- Partial R2 of the treatment with the outcome: an extreme confounder (orthogonal to the covariates) that explains 100% of the residual variance of the outcome, would need to explain at least 2.19% of the residual variance of the treatment to fully account for the observed estimated effect.\n\n-- Robustness Value, q = 1: unobserved confounders (orthogonal to the covariates) that explain more than 13.88% of the residual variance of both the treatment and the outcome are strong enough to bring the point estimate to 0 (a bias of 100% of the original estimate). Conversely, unobserved confounders that do not explain more than 13.88% of the residual variance of both the treatment and the outcome are not strong enough to bring the point estimate to 0.\n\n-- Robustness Value, q = 1, alpha = 0.05: unobserved confounders (orthogonal to the covariates) that explain more than 7.63% of the residual variance of both the treatment and the outcome are strong enough to bring the estimate to a range where it is no longer 'statistically different' from 0 (a bias of 100% of the original estimate), at the significance level of alpha = 0.05. Conversely, unobserved confounders that do not explain more than 7.63% of the residual variance of both the treatment and the outcome are not strong enough to bring the estimate to a range where it is no longer 'statistically different' from 0, at the significance level of alpha = 0.05.\n\nBounds on omitted variable bias:\n\n--The table below shows the maximum strength of unobserved confounders with association with the treatment and the outcome bounded by a multiple of the observed explanatory power of the chosen benchmark covariate(s).\n\n Bound Label R2dz.x R2yz.dx Treatment Adjusted Estimate Adjusted Se\n 1x female 0.0092 0.1246 directlyharmed 0.0752 0.0219\n 2x female 0.0183 0.2493 directlyharmed 0.0529 0.0204\n 3x female 0.0275 0.3741 directlyharmed 0.0304 0.0187\n Adjusted T Adjusted Lower CI Adjusted Upper CI\n 3.4389 0.0323 0.1182\n 2.6002 0.0130 0.0929\n 1.6281 -0.0063 0.0670"
compare <- capture_output(summary(darfur_out))
expect_equal(compare, summary.sense)
latex.table <- c("\\begin{table}[!h]", "\\centering", "\\begin{tabular}{lrrrrrr}",
"\\multicolumn{7}{c}{Outcome: \\textit{peacefactor}} \\\\", "\\hline \\hline ",
"Treatment: & Est. & S.E. & t-value & $R^2_{Y \\sim D |{\\bf X}}$ & $RV_{q = 1}$ & $RV_{q = 1, \\alpha = 0.05}$ \\\\ ",
"\\hline ", "\\textit{directlyharmed} & 0.097 & 0.023 & 4.184 & 2.2\\% & 13.9\\% & 7.6\\% \\\\ ",
"\\hline ", "df = 783 & & \\multicolumn{5}{r}{ \\small \\textit{Bound (1x female)}: $R^2_{Y\\sim Z| {\\bf X}, D}$ = 12.5\\%, $R^2_{D\\sim Z| {\\bf X} }$ = 0.9\\%} \\\\",
"\\end{tabular}", "\\end{table}")
expect_equal(capture.output(ovb_minimal_reporting(darfur_out)), latex.table)
latex2 <- c("\\begin{table}[!h]", "\\centering", "\\begin{tabular}{lrrrrrr}",
"\\multicolumn{7}{c}{Outcome: \\textit{peacefactor}} \\\\", "\\hline \\hline ",
"Treatment: & Est. & S.E. & t-value & $R^2_{Y \\sim D |{\\bf X}}$ & $RV_{q = 1}$ & $RV_{q = 1, \\alpha = 0.05}$ \\\\ ",
"\\hline ", "\\textit{directlyharmed} & 0.097 & 0.023 & 4.184 & 2.2\\% & 13.9\\% & 7.6\\% \\\\ ",
"\\hline ", "df = 783 & & \\multicolumn{5}{r}{ }\\end{tabular}",
"\\end{table}")
expect_equal(capture.output(ovb_minimal_reporting(darfur_out2)), latex2)
})
test_that("testing darfur different q",
{
darfur_out <- sensemakr(model, treatment = "directlyharmed", benchmark_covariates = "female", q = 2, kd = 1:3)
rvq <- darfur_out$sensitivity_stats$rv_q
rvqa <- darfur_out$sensitivity_stats$rv_qa
expect_equivalent(rvq, robustness_value(model, covariates = "directlyharmed", q = 2))
expect_equivalent(rvqa, robustness_value(model, covariates = "directlyharmed", q = 2,alpha = 0.05))
}
)
test_that("Darfur group benchmarks", {
village <- grep(pattern = "village", names(coef(model)), value = T)
sensitivity <- sensemakr(model, treatment = "directlyharmed",
benchmark_covariates = list(village = village),
kd = 0.3)
r2y <- group_partial_r2(model, covariates = village)
treat.model <- update(model, directlyharmed ~ .-directlyharmed)
r2d <- group_partial_r2(treat.model, covariates = village)
bounds.check <- ovb_partial_r2_bound(r2dxj.x = r2d, r2yxj.dx = r2y, kd = 0.3)
bounds <- sensitivity$bounds
expect_equal(bounds$r2dz.x, bounds.check$r2dz.x)
expect_equal(bounds$r2yz.dx, bounds.check$r2yz.dx)
}
)
| /tests/testthat/test-02-darfur.R | no_license | cran/sensemakr | R | false | false | 26,274 | r | context("Testing Darfur Example")
# runs regression model
data("darfur")
model2 <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village,
data = within(darfur, directlyharmed <- directlyharmed*(-1)))
model <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur)
test_that("testing darfur data", {
expect_equal(dim(darfur), c(1276, 14))
expect_equal(colnames(darfur),
c("wouldvote",
"peacefactor",
"peace_formerenemies",
"peace_jjindiv",
"peace_jjtribes",
"gos_soldier_execute",
"directlyharmed",
"age",
"farmer_dar",
"herder_dar",
"pastvoted",
"hhsize_darfur",
"village",
"female"))
})
test_that(desc = "testing darfur sensemakr",
{
darfur_out <- sensemakr(model, treatment = "directlyharmed", benchmark_covariates = "female", kd = 1:3)
plot(darfur_out)
ovb_contour_plot(darfur_out)
ovb_extreme_plot(darfur_out)
# info
expect_equal(darfur_out$info$formula, peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village)
expect_equal(darfur_out$info$treatment, "directlyharmed")
expect_equal(darfur_out$info$q, 1)
expect_equal(darfur_out$info$alpha, 0.05)
expect_equal(darfur_out$info$reduce, TRUE)
# sensitivity stats
expect_equal(darfur_out$sensitivity_stats$dof, 783)
expect_equal(darfur_out$sensitivity_stats$r2yd.x, 0.02187, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_q), 0.13878, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_qa), 0.07626, tolerance = 1e-5)
# bounds
check_bounds <- structure(list(bound_label = c("1x female", "2x female", "3x female"),
r2dz.x = c(0.00916428667504862, 0.0183285733500972, 0.0274928600251459),
r2yz.dx = c(0.12464092303637, 0.249324064199975, 0.374050471038094),
treatment = rep("directlyharmed", 3),
adjusted_estimate = c(0.0752202712144491, 0.0529151723844518, 0.0303960234641548),
adjusted_se = c(0.0218733277437572, 0.0203500620779637, 0.0186700648170924),
adjusted_t = c(3.43890386024675, 2.60024623913809, 1.62806202131271),
adjusted_lower_CI = c(0.032282966, 0.012968035,-0.006253282),
adjusted_upper_CI = c(0.11815758, 0.09286231, 0.06704533)
),
.Names = c("bound_label", "r2dz.x", "r2yz.dx", "treatment",
"adjusted_estimate", "adjusted_se", "adjusted_t",
"adjusted_lower_CI", "adjusted_upper_CI"),
row.names = c(NA, -3L), class = c("ovb_bounds", "data.frame"))
expect_equivalent(darfur_out$bounds, check_bounds)
out1 <- capture.output(darfur_out)
out1 <- capture.output(summary(darfur_out))
out3 <- capture.output(ovb_minimal_reporting(darfur_out))
darfur_out2 <- sensemakr(model, treatment = "directlyharmed")
plot(darfur_out2)
ovb_contour_plot(darfur_out2)
ovb_extreme_plot(darfur_out2)
out3 <- capture.output(ovb_minimal_reporting(darfur_out2))
})
test_that(desc = "testing darfur sensemakr but negative",
{
darfur_out <- sensemakr(model2, treatment = "directlyharmed", benchmark_covariates = "female", kd = 1:3)
plot(darfur_out)
ovb_contour_plot(darfur_out)
ovb_extreme_plot(darfur_out)
# info
expect_equal(darfur_out$info$formula, peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village)
expect_equal(darfur_out$info$treatment, "directlyharmed")
expect_equal(darfur_out$info$q, 1)
expect_equal(darfur_out$info$alpha, 0.05)
expect_equal(darfur_out$info$reduce, TRUE)
# sensitivity stats
expect_equal(darfur_out$sensitivity_stats$dof, 783)
expect_equal(darfur_out$sensitivity_stats$r2yd.x, 0.02187, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_q), 0.13878, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_qa), 0.07626, tolerance = 1e-5)
# bounds
check_bounds <- structure(list(bound_label = c("1x female", "2x female", "3x female"),
r2dz.x = c(0.00916428667504862, 0.0183285733500972, 0.0274928600251459),
r2yz.dx = c(0.12464092303637, 0.249324064199975, 0.374050471038094),
treatment = rep("directlyharmed", 3),
adjusted_estimate = c(-0.0752202712144491, -0.0529151723844518, -0.0303960234641548),
adjusted_se = c(0.0218733277437572, 0.0203500620779637, 0.0186700648170924),
adjusted_t = c(-3.43890386024675, -2.60024623913809, -1.62806202131271),
adjusted_lower_CI = -1*c(0.11815758, 0.09286231, 0.06704533),
adjusted_upper_CI = -1*c(0.032282966, 0.012968035,-0.006253282)
),
.Names = c("bound_label", "r2dz.x", "r2yz.dx", "treatment",
"adjusted_estimate", "adjusted_se", "adjusted_t",
"adjusted_lower_CI", "adjusted_upper_CI"),
row.names = c(NA, -3L), class = c("ovb_bounds", "data.frame"))
expect_equivalent(darfur_out$bounds, check_bounds)
out1 <- capture.output(darfur_out)
out1 <- capture.output(summary(darfur_out))
out3 <- capture.output(ovb_minimal_reporting(darfur_out))
darfur_out2 <- sensemakr(model, treatment = "directlyharmed")
plot(darfur_out2)
ovb_contour_plot(darfur_out2)
ovb_extreme_plot(darfur_out2)
out3 <- capture.output(ovb_minimal_reporting(darfur_out2))
})
test_that("testing darfur manual bounds",
{
sense.out <- sensemakr(model, treatment = "directlyharmed", benchmark_covariates = "female", r2dz.x = .1)
bounds.check <- sense.out$bounds
to_check <- bounds.check$adjusted_se[1]
true_check <- adjusted_se(model, treatment = "directlyharmed", r2dz.x = .1, r2yz.dx = .1)
expect_equal(to_check, unname(true_check))
}
)
test_that(desc = "testing darfur sensemakr with formula",
{
darfur_out <- sensemakr(formula = peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur, treatment = "directlyharmed", benchmark_covariates = "female", kd = 1:3)
# info
expect_equal(darfur_out$info$formula, peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village)
expect_equal(darfur_out$info$treatment, "directlyharmed")
expect_equal(darfur_out$info$q, 1)
expect_equal(darfur_out$info$alpha, 0.05)
expect_equal(darfur_out$info$reduce, TRUE)
# sensitivity stats
expect_equal(darfur_out$sensitivity_stats$dof, 783)
expect_equal(darfur_out$sensitivity_stats$r2yd.x, 0.02187, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_q), 0.13878, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_qa), 0.07626, tolerance = 1e-5)
# bounds
check_bounds <- structure(list(bound_label = c("1x female", "2x female", "3x female"),
r2dz.x = c(0.00916428667504862, 0.0183285733500972, 0.0274928600251459),
r2yz.dx = c(0.12464092303637, 0.249324064199975, 0.374050471038094),
treatment = rep("directlyharmed", 3),
adjusted_estimate = c(0.0752202712144491, 0.0529151723844518, 0.0303960234641548),
adjusted_se = c(0.0218733277437572, 0.0203500620779637, 0.0186700648170924),
adjusted_t = c(3.43890386024675, 2.60024623913809, 1.62806202131271),
adjusted_lower_CI = c(0.032282966, 0.012968035,-0.006253282),
adjusted_upper_CI = c(0.11815758, 0.09286231, 0.06704533)),
.Names = c("bound_label", "r2dz.x", "r2yz.dx", "treatment",
"adjusted_estimate", "adjusted_se", "adjusted_t",
"adjusted_lower_CI", "adjusted_upper_CI"),
row.names = c(NA, -3L), class = c("ovb_bounds", "data.frame"))
expect_equivalent(darfur_out$bounds, check_bounds)
})
test_that(desc = "testing darfur sensemakr manually",
{
model.treat <- lm(directlyharmed ~ age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur)
darfur_out <- sensemakr(estimate = 0.09731582,
se = 0.02325654,
dof = 783,
treatment = "directlyharmed",
benchmark_covariates = "female",
r2dxj.x = partial_r2(model.treat, covariates = "female"),
r2yxj.dx = partial_r2(model, covariates = "female"),
kd = 1:3)
plot(darfur_out)
plot(darfur_out, type = "extreme")
plot(darfur_out, sensitivity.of = "t-value")
add_bound_to_contour(0.3,0.3, "test")
# info
expect_equal(darfur_out$info$formula, "Data provided manually")
expect_equal(darfur_out$info$treatment, "directlyharmed")
expect_equal(darfur_out$info$q, 1)
expect_equal(darfur_out$info$alpha, 0.05)
expect_equal(darfur_out$info$reduce, TRUE)
# sensitivity stats
expect_equal(darfur_out$sensitivity_stats$dof, 783)
expect_equal(darfur_out$sensitivity_stats$r2yd.x, 0.02187, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_q), 0.13878, tolerance = 1e-5)
expect_equivalent(c(darfur_out$sensitivity_stats$rv_qa), 0.07626, tolerance = 1e-5)
# bounds
check_bounds <-
structure(
list(
bound_label = c("1x female", "2x female", "3x female"),
r2dz.x = c(0.00916428667504862, 0.0183285733500972, 0.0274928600251459),
r2yz.dx = c(0.12464092303637, 0.249324064199975, 0.374050471038094),
adjusted_estimate = c(0.0752202698486415, 0.0529151689180575,
0.0303960178770157),
adjusted_se = c(0.0218733298036818, 0.0203500639944344,
0.0186700665753491),
adjusted_t = c(3.43890347394571, 2.60024582392121,
1.62806156873318),
adjusted_lower_CI = c(0.0322829603180086,
0.0129680276030601, -0.00625329133645187),
adjusted_upper_CI = c(0.118157579379274,
0.092862310233055, 0.0670453270904833)
),
row.names = c(NA, -3L),
class = "data.frame"
)
expect_equivalent(as.data.frame(darfur_out$bounds), as.data.frame(check_bounds))
})
test_that(desc = "testing darfur sensitivity stats",{
# checks RV
## RV q = 1
rv <- robustness_value(model, covariates = "directlyharmed")
expect_equivalent(c(rv), 0.138776, tolerance = 1e-5)
expect_equivalent(attributes(rv)$q, 1)
expect_equivalent(attributes(rv)$names, "directlyharmed")
## RV q = 1, alpha = 0.05
rv <- robustness_value(model, covariates = "directlyharmed", q = 1, alpha = 0.05)
expect_equivalent(c(rv), 0.07625797, tolerance = 1e-5)
expect_equivalent(attributes(rv)$q, 1)
expect_equivalent(attributes(rv)$alpha, 0.05)
expect_equivalent(attributes(rv)$names, "directlyharmed")
# checks partial R2
r2 <- partial_r2(model, covariates = "directlyharmed")
expect_equivalent(r2, 0.02187309, tolerance = 1e-5)
# checks partial f2
f2 <- partial_f2(model, covariates = "directlyharmed")
expect_equivalent(f2, 0.02236222, tolerance = 1e-5)
# sensitivity stats
sens_stats <- sensitivity_stats(model, treatment = "directlyharmed")
expect_equivalent(sens_stats$treatment, "directlyharmed")
expect_equivalent(sens_stats$estimate, 0.09731582, tolerance = 1e5)
expect_equivalent(sens_stats$se, 0.02325654, tolerance = 1e5)
expect_equivalent(sens_stats$t_statistic, 4.18445, tolerance = 1e5)
expect_equivalent(sens_stats$r2yd.x, 0.02187309, tolerance = 1e5)
expect_equivalent(sens_stats$rv_q , 0.1387764, tolerance = 1e5)
expect_equivalent(sens_stats$rv_qa , 0.07625797, tolerance = 1e5)
expect_equivalent(sens_stats$f2yd.x , 0.02236222, tolerance = 1e5)
expect_equivalent(sens_stats$dof , 783, tolerance = 1e5)
expect_equivalent(group_partial_r2(model, covariates = "directlyharmed"), partial_r2(model, covariates = "directlyharmed"))
expect_error(group_partial_r2(model))
expect_equal(group_partial_r2(model, covariates = c("directlyharmed", "female")), 0.1350435, tolerance = 1e-5)
})
test_that(desc = "testing darfur adjusted estimates",{
should_be_zero <- adjusted_estimate(model, treatment = "directlyharmed", r2yz.dx = 1, r2dz.x = partial_r2(model, covariates = "directlyharmed"))
expect_equivalent(should_be_zero, 0)
rv <- robustness_value(model, covariates = "directlyharmed")
should_be_zero <- adjusted_estimate(model, treatment = "directlyharmed", r2yz.dx = rv, r2dz.x = rv)
expect_equivalent(should_be_zero, 0)
rv <- robustness_value(model, covariates = "directlyharmed", alpha = 0.05)
thr <- qt(0.975, df = 783 - 1)
should_be_1.96 <- adjusted_t(model, treatment = "directlyharmed", r2yz.dx = rv, r2dz.x = rv)
expect_equivalent(c(should_be_1.96), thr)
should_be_estimate <- bias(model, treatment = "directlyharmed", r2yz.dx = 1, r2dz.x = partial_r2(model, covariates = "directlyharmed"))
expect_equivalent(should_be_estimate, coef(model)["directlyharmed"])
rv <- robustness_value(model, covariates = "directlyharmed")
should_be_estimate <- bias(model, treatment = "directlyharmed", r2yz.dx = rv, r2dz.x = rv)
expect_equivalent(should_be_estimate, coef(model)["directlyharmed"])
rv <- robustness_value(model, covariates = "directlyharmed", q = 0.5)
should_be_half_estimate <- bias(model, treatment = "directlyharmed", r2yz.dx = rv, r2dz.x = rv)
expect_equivalent(should_be_half_estimate, coef(model)["directlyharmed"]/2)
})
test_that(desc = "testing darfur plots",
{
# testing countour output with internal functions
## point estimate
contour_out <- ovb_contour_plot(model, treatment = "directlyharmed",
benchmark_covariates = "female",kd = 1:3)
add_bound_to_contour(model, treatment = "directlyharmed",
benchmark_covariates = "age", kd = 10)
add_bound_to_contour(model, treatment = "directlyharmed",
benchmark_covariates = "age", kd = 200, ky = 20)
adj_est <- adjusted_estimate(model, treatment = "directlyharmed",
r2dz.x = contour_out$r2dz.x[10],
r2yz.dx = contour_out$r2yz.dx[1])
expect_equivalent(adj_est, contour_out$value[10])
bounds <- ovb_bounds(model,
treatment = "directlyharmed",
benchmark_covariates = "female",
kd = 1:3)
expect_equivalent(contour_out$bounds, bounds[c(2,3,1)])
## t-value
contour_out <- ovb_contour_plot(model, treatment = "directlyharmed",
benchmark_covariates = "female",kd = 1:3,
sensitivity.of = "t-value")
add_bound_to_contour(model, treatment = "directlyharmed", benchmark_covariates = "age",
kd = 200, ky = 10, sensitivity.of = "t-value")
adj_t <- adjusted_t(model, treatment = "directlyharmed",
r2dz.x = contour_out$r2dz.x[10],
r2yz.dx = contour_out$r2yz.dx[1])
expect_equivalent(adj_t, contour_out$value[10])
bounds <- ovb_bounds(model,
treatment = "directlyharmed",
benchmark_covariates = "female",
kd = 1:3)
expect_equivalent(contour_out$bounds, bounds[c(2,3,1)])
# tests bounds numerically
expect_equivalent(bounds$adjusted_estimate, c(0.0752202712144491, 0.0529151723844518, 0.0303960234641548))
expect_equivalent(bounds$adjusted_t, c(3.43890386024675, 2.60024623913809, 1.62806202131271))
# test extreme scenario plot
extreme_out <- ovb_extreme_plot(model, treatment = "directlyharmed", kd = 1:3)
adj_est <- adjusted_estimate(model, treatment = "directlyharmed",
r2yz.dx = 1,
r2dz.x = extreme_out$scenario_r2yz.dx_1$r2dz.x[5])
expect_equivalent(adj_est, extreme_out$scenario_r2yz.dx_1$adjusted_estimate[5])
}
)
test_that("testing darfur print",
{
skip_on_cran()
darfur_out <- sensemakr(model, treatment = "directlyharmed", benchmark_covariates = "female", kd = 1:3)
darfur_out2 <- sensemakr(model, treatment = "directlyharmed")
print.sense <- "Sensitivity Analysis to Unobserved Confounding\n\nModel Formula: peacefactor ~ directlyharmed + age + farmer_dar + herder_dar + \n pastvoted + hhsize_darfur + female + village\n\nNull hypothesis: q = 1 and reduce = TRUE \n\nUnadjusted Estimates of ' directlyharmed ':\n Coef. estimate: 0.09732 \n Standard Error: 0.02326 \n t-value: 4.18445 \n\nSensitivity Statistics:\n Partial R2 of treatment with outcome: 0.02187 \n Robustness Value, q = 1 : 0.13878 \n Robustness Value, q = 1 alpha = 0.05 : 0.07626 \n\nFor more information, check summary."
compare <- capture_output(print(darfur_out))
expect_equal(compare, print.sense)
summary.sense <- "Sensitivity Analysis to Unobserved Confounding\n\nModel Formula: peacefactor ~ directlyharmed + age + farmer_dar + herder_dar + \n pastvoted + hhsize_darfur + female + village\n\nNull hypothesis: q = 1 and reduce = TRUE \n-- This means we are considering biases that reduce the absolute value of the current estimate.\n-- The null hypothesis deemed problematic is H0:tau = 0 \n\nUnadjusted Estimates of 'directlyharmed': \n Coef. estimate: 0.0973 \n Standard Error: 0.0233 \n t-value (H0:tau = 0): 4.1844 \n\nSensitivity Statistics:\n Partial R2 of treatment with outcome: 0.0219 \n Robustness Value, q = 1: 0.1388 \n Robustness Value, q = 1, alpha = 0.05: 0.0763 \n\nVerbal interpretation of sensitivity statistics:\n\n-- Partial R2 of the treatment with the outcome: an extreme confounder (orthogonal to the covariates) that explains 100% of the residual variance of the outcome, would need to explain at least 2.19% of the residual variance of the treatment to fully account for the observed estimated effect.\n\n-- Robustness Value, q = 1: unobserved confounders (orthogonal to the covariates) that explain more than 13.88% of the residual variance of both the treatment and the outcome are strong enough to bring the point estimate to 0 (a bias of 100% of the original estimate). Conversely, unobserved confounders that do not explain more than 13.88% of the residual variance of both the treatment and the outcome are not strong enough to bring the point estimate to 0.\n\n-- Robustness Value, q = 1, alpha = 0.05: unobserved confounders (orthogonal to the covariates) that explain more than 7.63% of the residual variance of both the treatment and the outcome are strong enough to bring the estimate to a range where it is no longer 'statistically different' from 0 (a bias of 100% of the original estimate), at the significance level of alpha = 0.05. Conversely, unobserved confounders that do not explain more than 7.63% of the residual variance of both the treatment and the outcome are not strong enough to bring the estimate to a range where it is no longer 'statistically different' from 0, at the significance level of alpha = 0.05.\n\nBounds on omitted variable bias:\n\n--The table below shows the maximum strength of unobserved confounders with association with the treatment and the outcome bounded by a multiple of the observed explanatory power of the chosen benchmark covariate(s).\n\n Bound Label R2dz.x R2yz.dx Treatment Adjusted Estimate Adjusted Se\n 1x female 0.0092 0.1246 directlyharmed 0.0752 0.0219\n 2x female 0.0183 0.2493 directlyharmed 0.0529 0.0204\n 3x female 0.0275 0.3741 directlyharmed 0.0304 0.0187\n Adjusted T Adjusted Lower CI Adjusted Upper CI\n 3.4389 0.0323 0.1182\n 2.6002 0.0130 0.0929\n 1.6281 -0.0063 0.0670"
compare <- capture_output(summary(darfur_out))
expect_equal(compare, summary.sense)
latex.table <- c("\\begin{table}[!h]", "\\centering", "\\begin{tabular}{lrrrrrr}",
"\\multicolumn{7}{c}{Outcome: \\textit{peacefactor}} \\\\", "\\hline \\hline ",
"Treatment: & Est. & S.E. & t-value & $R^2_{Y \\sim D |{\\bf X}}$ & $RV_{q = 1}$ & $RV_{q = 1, \\alpha = 0.05}$ \\\\ ",
"\\hline ", "\\textit{directlyharmed} & 0.097 & 0.023 & 4.184 & 2.2\\% & 13.9\\% & 7.6\\% \\\\ ",
"\\hline ", "df = 783 & & \\multicolumn{5}{r}{ \\small \\textit{Bound (1x female)}: $R^2_{Y\\sim Z| {\\bf X}, D}$ = 12.5\\%, $R^2_{D\\sim Z| {\\bf X} }$ = 0.9\\%} \\\\",
"\\end{tabular}", "\\end{table}")
expect_equal(capture.output(ovb_minimal_reporting(darfur_out)), latex.table)
latex2 <- c("\\begin{table}[!h]", "\\centering", "\\begin{tabular}{lrrrrrr}",
"\\multicolumn{7}{c}{Outcome: \\textit{peacefactor}} \\\\", "\\hline \\hline ",
"Treatment: & Est. & S.E. & t-value & $R^2_{Y \\sim D |{\\bf X}}$ & $RV_{q = 1}$ & $RV_{q = 1, \\alpha = 0.05}$ \\\\ ",
"\\hline ", "\\textit{directlyharmed} & 0.097 & 0.023 & 4.184 & 2.2\\% & 13.9\\% & 7.6\\% \\\\ ",
"\\hline ", "df = 783 & & \\multicolumn{5}{r}{ }\\end{tabular}",
"\\end{table}")
expect_equal(capture.output(ovb_minimal_reporting(darfur_out2)), latex2)
})
test_that("testing darfur different q",
{
darfur_out <- sensemakr(model, treatment = "directlyharmed", benchmark_covariates = "female", q = 2, kd = 1:3)
rvq <- darfur_out$sensitivity_stats$rv_q
rvqa <- darfur_out$sensitivity_stats$rv_qa
expect_equivalent(rvq, robustness_value(model, covariates = "directlyharmed", q = 2))
expect_equivalent(rvqa, robustness_value(model, covariates = "directlyharmed", q = 2,alpha = 0.05))
}
)
test_that("Darfur group benchmarks", {
village <- grep(pattern = "village", names(coef(model)), value = T)
sensitivity <- sensemakr(model, treatment = "directlyharmed",
benchmark_covariates = list(village = village),
kd = 0.3)
r2y <- group_partial_r2(model, covariates = village)
treat.model <- update(model, directlyharmed ~ .-directlyharmed)
r2d <- group_partial_r2(treat.model, covariates = village)
bounds.check <- ovb_partial_r2_bound(r2dxj.x = r2d, r2yxj.dx = r2y, kd = 0.3)
bounds <- sensitivity$bounds
expect_equal(bounds$r2dz.x, bounds.check$r2dz.x)
expect_equal(bounds$r2yz.dx, bounds.check$r2yz.dx)
}
)
|
#' Propensity_score_estimation
#'
#' @description This function provides estimates of the propensity scores that can be used in the BCF model
#'
#' Output: @return propensity_estimates .... n x samples*repeats or n x repeats draws of propensity score estimates
#' Input: @param predictors ... variables used to estimate the propensity scores
#' @param treatment ... variable that indicates treatment or not for each individual
#' @param samples .... number of posterior samples that user wants per individual per cross fold, default 1000
#' @param technique .... technique speciified by the user that is used for estimation. Default = "BARTMACHINE"
#' @param take_means_draws ... = note used anymore, default is to take posterior mean -- Logical variable indicating whether mean of all posterior draws for each k_fold needs to be taken, default TRUE
#' @param k_fold_cv .... number of cross validations, default 10
#' @param repeats ... number of repeats of cross validation, default 1
ps_estimator <-
function(predictors,
treatment,
samples = 1000,
technique = "BARTMACHINE",
take_means_draws = TRUE,
k_fold_cv = 10,
repeats = 1,
k_parameter = 2,
m_parameter = 50,
smote_kfold = FALSE,
convergence_check = FALSE
) {
#Preprocessing steps if needed
set.seed(30121997)
#Empty propensity scores matrix for all repeats
# if(take_means_draws){
# propensity_scores_total <-
# matrix(NA, nrow(predictors), ncol = repeats)
#}else{
propensity_scores_total <-
matrix(NA, nrow(predictors), ncol = repeats)
#}
#Make input from list to matrix if necessary (treatment is vector already so need no changes) ----- volgens mij gaat het hier fout???
# if (typeof(predictors) == "list") {
# predictors <- matrix(unlist(predictors), nrow = dim(predictors)[1], byrow = TRUE)
#}
#Set number of results per cross validation step
# if (take_means_draws) {
# results_per_cv = 1
#} else
# (
# results_per_cv = samples
# )
#Do repeats for repeated cross validation
for (rp in 1:repeats) {
#Make emtpty matrix for results of each repeat
propensity_scores_repeat <- matrix(NA, nrow(predictors), 1)
#Make sample for each repeat
original_order <- seq(1:nrow(predictors))
individuals_shuffle <- sample(nrow(predictors))
predictors$original_order <- original_order
treatment$original_order <- original_order
shuffled_predictors <- predictors[individuals_shuffle,]
shuffled_treatment <- treatment[individuals_shuffle,]
if (k_fold_cv > 1) {
folds <-
cut(seq(1, nrow(shuffled_predictors)), breaks = k_fold_cv, labels = FALSE)
}
#Loop over k cross folds
for (k_fold in 1:k_fold_cv) {
#Select train and test
if (k_fold_cv > 1) {
test_indicator <- which(folds == k_fold, arr.ind = TRUE)
train_predictors <-
shuffled_predictors[-test_indicator,!names(shuffled_predictors) %in% c("original_order")]
test_predictors <-
shuffled_predictors[test_indicator,!names(shuffled_predictors) %in% c("original_order")]
train_treatment <-
shuffled_treatment[-test_indicator,!names(shuffled_treatment) %in% c("original_order")]
train_treatment <- pull(train_treatment, expRDAll)
test_treatment <-
shuffled_treatment[test_indicator,!names(shuffled_treatment) %in% c("original_order")]
test_treatment <- pull(test_treatment, expRDAll)
} else if (k_fold_cv == 1) {
train_predictors <-
shuffled_predictors[,!names(shuffled_predictors) %in% c("original_order")]
train_treatment <-
shuffled_treatment[,!names(shuffled_treatment) %in% c("original_order")]
train_treatment <- pull(train_treatment, expRDAll)
}
#Make sure train and test predictors are dataframe (unlist function)
#Actual estimation - default method is BART #OLD - not used in thesis report
if (technique == "BART") {
library(BART)
model_execution <- gbart(
x.train = train_predictors,
y.train = train_treatment,
x.test = test_predictors,
#Probit - can use logit by lbart
type = 'pbart',
rho = NULL,
#Sigma prior specification - not used for binary outcome
sigest = NA,
sigdf = 3,
sigquant = 0.90,
#Conservativeness of estimate
k = 2,
#Tree prior specification
power = 2,
base = 0.95,
#Number of trees
ntree = 50L,
#Number of posterior draws
ndpost = samples,
#Burn in
nskip = 100L,
#Thinning
keepevery = c(1L, 10L, 10L)[2],
#print draws
printevery = 100L,
transposed = FALSE,
)
#Use bart execution pnorm output. Make user choose to take averages or not -- need to transpose if not taking averages!
} else if (technique == "BARTMACHINE") {
options(java.parameters = "-Xmx10g")
library(bartMachine)
set_bart_machine_num_cores(1)
#Check if train treatment is binary
if (typeof(train_treatment) == "double") {
train_treatment <- as_factor(train_treatment)
if (k_fold_cv > 1) {
test_treatment <- as_factor(test_treatment)
}
}
if (k_fold_cv > 1) {
#Estimate model
model_execution_obj <- bartMachine(
X = train_predictors,
y = train_treatment,
num_trees = m_parameter,
num_burn_in = 250,
num_iterations_after_burn_in = samples,
alpha = 0.95,
beta = 2,
k = k_parameter,
q = 0.9,
nu = 3,
prob_rule_class = 0.5,
mh_prob_steps = c(2.5, 2.5, 4) / 9,
debug_log = FALSE,
run_in_sample = FALSE,
s_sq_y = "mse",
sig_sq_est = NULL,
cov_prior_vec = NULL,
use_missing_data = FALSE,
covariates_to_permute = NULL,
num_rand_samps_in_library = 10000,
use_missing_data_dummies_as_covars = FALSE,
replace_missing_data_with_x_j_bar = FALSE,
impute_missingness_with_rf_impute = FALSE,
impute_missingness_with_x_j_bar_for_lm = TRUE,
mem_cache_for_speed = TRUE,
flush_indices_to_save_RAM = TRUE,
serialize = FALSE,
seed = NULL,
verbose = TRUE
)
#Obtain predictions - note that no treatment is predicted
model_execution <-
bart_predict_for_test_data(model_execution_obj,
test_predictors,
test_treatment,
prob_rule_class = 0.5)
} else if (k_fold_cv == 1) {
model_execution_obj <- bartMachine(
X = train_predictors,
y = train_treatment,
num_trees = 50,
num_burn_in = 250,
num_iterations_after_burn_in = samples,
alpha = 0.95,
beta = 2,
k = 2,
q = 0.9,
nu = 3,
prob_rule_class = 0.5,
mh_prob_steps = c(2.5, 2.5, 4) / 9,
debug_log = FALSE,
run_in_sample = TRUE,
s_sq_y = "mse",
sig_sq_est = NULL,
cov_prior_vec = NULL,
use_missing_data = FALSE,
covariates_to_permute = NULL,
num_rand_samps_in_library = 10000,
use_missing_data_dummies_as_covars = FALSE,
replace_missing_data_with_x_j_bar = FALSE,
impute_missingness_with_rf_impute = FALSE,
impute_missingness_with_x_j_bar_for_lm = TRUE,
mem_cache_for_speed = TRUE,
flush_indices_to_save_RAM = TRUE,
serialize = FALSE,
seed = NULL,
verbose = TRUE
)
# model_execution_obj <- bartMachineCV(
# X = train_predictors,
# y = train_treatment,
# Xy = NULL,
# num_tree_cvs = c("10", "50" ,"100", "200"),
# k_cvs = c(1,2,3,4,5),
# nu_q_cvs = NULL,
# k_folds <- 5,
# verbose = TRUE)
model_execution <- model_execution_obj$p_hat_train
# convergence_plots <- plot_convergence_diagnostics(model_execution_obj)
}
}
#Fill output matrix with output for crossfold
if (k_fold_cv > 1) {
predictions <- 1 - model_execution$p_hat
} else if (k_fold_cv == 1) {
predictions <- 1 - model_execution
}
#Note that the output needs to be transposed as the gbart function provides each posterior draw in each row
if (k_fold_cv > 1) {
propensity_scores_repeat[test_indicator,] <- predictions
} else if (k_fold_cv == 1) {
propensity_scores_repeat <- predictions
}
}
#Fill total matrix for with the numbers for each repeat and put back in order!
# if(take_means_draws){
# propensity_scores_repeat <- cbind(propensity_scores_repeat, shuffled_treatment$original_order)
#propensity_scores_repeat_ordered <- propensity_scores_repeat[order(propensity_scores_repeat[, 2])]
propensity_scores_total[, rp] <- propensity_scores_repeat[order(shuffled_treatment$original_order)]
# } else{
# propensity_scores_total[, ((rp - 1) * samples + 1):(rp*samples)] <- propensity_scores_repeat
# }
}
#Return all the propensity score estimates
if(smote_kfold == FALSE){
return(propensity_scores_total)
}else if(smote_kfold == TRUE){
return(model_execution_obj)
}
#if(convergence_check == TRUE){
# return(convergence_plots)
# }
}
#' ps_analysis
#'
#' This function analyses the estimated propensity scores. This is necessary to look whether enough support is provided in estimatoin
#' One key point to look out for is that there are not too much values close to 0 or 1. This makes the estimates uninformative
#' Output: Some graphs and statistics perhaps
#' Input: @estimated_ps ... propoensity score estimates
#' @control_variables ... control variables for which support needs to be checked
ps_analysis <- function(estimated_ps, control_variables, ...){
#Wat voor analysis is hier nodig
#Kijk naar de verdeling van de propensity scores
#Deel dit op op basis van bepaalde kenmerken
#En normaal
#Kijk naar de 'accuracy' van de propensity scores
#Kijk in hoeverre bepaalde variables zijn meegenomen in het model (mogelijk?)
} | /2_Propensity_estimation/propensity_score_estimation.R | no_license | pimvandervoet/master_thesis_code | R | false | false | 11,438 | r | #' Propensity_score_estimation
#'
#' @description This function provides estimates of the propensity scores that can be used in the BCF model
#'
#' Output: @return propensity_estimates .... n x samples*repeats or n x repeats draws of propensity score estimates
#' Input: @param predictors ... variables used to estimate the propensity scores
#' @param treatment ... variable that indicates treatment or not for each individual
#' @param samples .... number of posterior samples that user wants per individual per cross fold, default 1000
#' @param technique .... technique speciified by the user that is used for estimation. Default = "BARTMACHINE"
#' @param take_means_draws ... = note used anymore, default is to take posterior mean -- Logical variable indicating whether mean of all posterior draws for each k_fold needs to be taken, default TRUE
#' @param k_fold_cv .... number of cross validations, default 10
#' @param repeats ... number of repeats of cross validation, default 1
ps_estimator <-
function(predictors,
treatment,
samples = 1000,
technique = "BARTMACHINE",
take_means_draws = TRUE,
k_fold_cv = 10,
repeats = 1,
k_parameter = 2,
m_parameter = 50,
smote_kfold = FALSE,
convergence_check = FALSE
) {
#Preprocessing steps if needed
set.seed(30121997)
#Empty propensity scores matrix for all repeats
# if(take_means_draws){
# propensity_scores_total <-
# matrix(NA, nrow(predictors), ncol = repeats)
#}else{
propensity_scores_total <-
matrix(NA, nrow(predictors), ncol = repeats)
#}
#Make input from list to matrix if necessary (treatment is vector already so need no changes) ----- volgens mij gaat het hier fout???
# if (typeof(predictors) == "list") {
# predictors <- matrix(unlist(predictors), nrow = dim(predictors)[1], byrow = TRUE)
#}
#Set number of results per cross validation step
# if (take_means_draws) {
# results_per_cv = 1
#} else
# (
# results_per_cv = samples
# )
#Do repeats for repeated cross validation
for (rp in 1:repeats) {
#Make emtpty matrix for results of each repeat
propensity_scores_repeat <- matrix(NA, nrow(predictors), 1)
#Make sample for each repeat
original_order <- seq(1:nrow(predictors))
individuals_shuffle <- sample(nrow(predictors))
predictors$original_order <- original_order
treatment$original_order <- original_order
shuffled_predictors <- predictors[individuals_shuffle,]
shuffled_treatment <- treatment[individuals_shuffle,]
if (k_fold_cv > 1) {
folds <-
cut(seq(1, nrow(shuffled_predictors)), breaks = k_fold_cv, labels = FALSE)
}
#Loop over k cross folds
for (k_fold in 1:k_fold_cv) {
#Select train and test
if (k_fold_cv > 1) {
test_indicator <- which(folds == k_fold, arr.ind = TRUE)
train_predictors <-
shuffled_predictors[-test_indicator,!names(shuffled_predictors) %in% c("original_order")]
test_predictors <-
shuffled_predictors[test_indicator,!names(shuffled_predictors) %in% c("original_order")]
train_treatment <-
shuffled_treatment[-test_indicator,!names(shuffled_treatment) %in% c("original_order")]
train_treatment <- pull(train_treatment, expRDAll)
test_treatment <-
shuffled_treatment[test_indicator,!names(shuffled_treatment) %in% c("original_order")]
test_treatment <- pull(test_treatment, expRDAll)
} else if (k_fold_cv == 1) {
train_predictors <-
shuffled_predictors[,!names(shuffled_predictors) %in% c("original_order")]
train_treatment <-
shuffled_treatment[,!names(shuffled_treatment) %in% c("original_order")]
train_treatment <- pull(train_treatment, expRDAll)
}
#Make sure train and test predictors are dataframe (unlist function)
#Actual estimation - default method is BART #OLD - not used in thesis report
if (technique == "BART") {
library(BART)
model_execution <- gbart(
x.train = train_predictors,
y.train = train_treatment,
x.test = test_predictors,
#Probit - can use logit by lbart
type = 'pbart',
rho = NULL,
#Sigma prior specification - not used for binary outcome
sigest = NA,
sigdf = 3,
sigquant = 0.90,
#Conservativeness of estimate
k = 2,
#Tree prior specification
power = 2,
base = 0.95,
#Number of trees
ntree = 50L,
#Number of posterior draws
ndpost = samples,
#Burn in
nskip = 100L,
#Thinning
keepevery = c(1L, 10L, 10L)[2],
#print draws
printevery = 100L,
transposed = FALSE,
)
#Use bart execution pnorm output. Make user choose to take averages or not -- need to transpose if not taking averages!
} else if (technique == "BARTMACHINE") {
options(java.parameters = "-Xmx10g")
library(bartMachine)
set_bart_machine_num_cores(1)
#Check if train treatment is binary
if (typeof(train_treatment) == "double") {
train_treatment <- as_factor(train_treatment)
if (k_fold_cv > 1) {
test_treatment <- as_factor(test_treatment)
}
}
if (k_fold_cv > 1) {
#Estimate model
model_execution_obj <- bartMachine(
X = train_predictors,
y = train_treatment,
num_trees = m_parameter,
num_burn_in = 250,
num_iterations_after_burn_in = samples,
alpha = 0.95,
beta = 2,
k = k_parameter,
q = 0.9,
nu = 3,
prob_rule_class = 0.5,
mh_prob_steps = c(2.5, 2.5, 4) / 9,
debug_log = FALSE,
run_in_sample = FALSE,
s_sq_y = "mse",
sig_sq_est = NULL,
cov_prior_vec = NULL,
use_missing_data = FALSE,
covariates_to_permute = NULL,
num_rand_samps_in_library = 10000,
use_missing_data_dummies_as_covars = FALSE,
replace_missing_data_with_x_j_bar = FALSE,
impute_missingness_with_rf_impute = FALSE,
impute_missingness_with_x_j_bar_for_lm = TRUE,
mem_cache_for_speed = TRUE,
flush_indices_to_save_RAM = TRUE,
serialize = FALSE,
seed = NULL,
verbose = TRUE
)
#Obtain predictions - note that no treatment is predicted
model_execution <-
bart_predict_for_test_data(model_execution_obj,
test_predictors,
test_treatment,
prob_rule_class = 0.5)
} else if (k_fold_cv == 1) {
model_execution_obj <- bartMachine(
X = train_predictors,
y = train_treatment,
num_trees = 50,
num_burn_in = 250,
num_iterations_after_burn_in = samples,
alpha = 0.95,
beta = 2,
k = 2,
q = 0.9,
nu = 3,
prob_rule_class = 0.5,
mh_prob_steps = c(2.5, 2.5, 4) / 9,
debug_log = FALSE,
run_in_sample = TRUE,
s_sq_y = "mse",
sig_sq_est = NULL,
cov_prior_vec = NULL,
use_missing_data = FALSE,
covariates_to_permute = NULL,
num_rand_samps_in_library = 10000,
use_missing_data_dummies_as_covars = FALSE,
replace_missing_data_with_x_j_bar = FALSE,
impute_missingness_with_rf_impute = FALSE,
impute_missingness_with_x_j_bar_for_lm = TRUE,
mem_cache_for_speed = TRUE,
flush_indices_to_save_RAM = TRUE,
serialize = FALSE,
seed = NULL,
verbose = TRUE
)
# model_execution_obj <- bartMachineCV(
# X = train_predictors,
# y = train_treatment,
# Xy = NULL,
# num_tree_cvs = c("10", "50" ,"100", "200"),
# k_cvs = c(1,2,3,4,5),
# nu_q_cvs = NULL,
# k_folds <- 5,
# verbose = TRUE)
model_execution <- model_execution_obj$p_hat_train
# convergence_plots <- plot_convergence_diagnostics(model_execution_obj)
}
}
#Fill output matrix with output for crossfold
if (k_fold_cv > 1) {
predictions <- 1 - model_execution$p_hat
} else if (k_fold_cv == 1) {
predictions <- 1 - model_execution
}
#Note that the output needs to be transposed as the gbart function provides each posterior draw in each row
if (k_fold_cv > 1) {
propensity_scores_repeat[test_indicator,] <- predictions
} else if (k_fold_cv == 1) {
propensity_scores_repeat <- predictions
}
}
#Fill total matrix for with the numbers for each repeat and put back in order!
# if(take_means_draws){
# propensity_scores_repeat <- cbind(propensity_scores_repeat, shuffled_treatment$original_order)
#propensity_scores_repeat_ordered <- propensity_scores_repeat[order(propensity_scores_repeat[, 2])]
propensity_scores_total[, rp] <- propensity_scores_repeat[order(shuffled_treatment$original_order)]
# } else{
# propensity_scores_total[, ((rp - 1) * samples + 1):(rp*samples)] <- propensity_scores_repeat
# }
}
#Return all the propensity score estimates
if(smote_kfold == FALSE){
return(propensity_scores_total)
}else if(smote_kfold == TRUE){
return(model_execution_obj)
}
#if(convergence_check == TRUE){
# return(convergence_plots)
# }
}
#' ps_analysis
#'
#' This function analyses the estimated propensity scores. This is necessary to look whether enough support is provided in estimatoin
#' One key point to look out for is that there are not too much values close to 0 or 1. This makes the estimates uninformative
#' Output: Some graphs and statistics perhaps
#' Input: @estimated_ps ... propoensity score estimates
#' @control_variables ... control variables for which support needs to be checked
ps_analysis <- function(estimated_ps, control_variables, ...){
#Wat voor analysis is hier nodig
#Kijk naar de verdeling van de propensity scores
#Deel dit op op basis van bepaalde kenmerken
#En normaal
#Kijk naar de 'accuracy' van de propensity scores
#Kijk in hoeverre bepaalde variables zijn meegenomen in het model (mogelijk?)
} |
\name{rankTransform}
\alias{rankTransform}
\title{
Rank transforms a response
}
\description{
Transforms a response by rank into critical values of the standard normal distribution. In the case of ties this function will
use the mean of the transformed response.
}
\usage{
rankTransform(Data, VecName)
}
\arguments{
\item{Data}{
A data set.
}
\item{VecName}{
The name (as a string) of the response to be transformed.
}
}
\value{
\item{Data}{The original data set with a new variable called 'TransformedResponse' which is the rank transform of the response.}
}
\author{
Joe Swintek
}
\examples{
#Data
data(lengthWeightData)
#Subset the data
SubData<-lengthWeightData[lengthWeightData$Age=='16 week', ]
SubData<-SubData[SubData$Generation=='F1', ]
SubData<-SubData[SubData$SEX=='M', ]
#Run
RankData<-rankTransform(Data=SubData, VecName='WEIGHT')
head(RankData)
}
| /man/rankTransform.Rd | no_license | cran/StatCharrms | R | false | false | 940 | rd | \name{rankTransform}
\alias{rankTransform}
\title{
Rank transforms a response
}
\description{
Transforms a response by rank into critical values of the standard normal distribution. In the case of ties this function will
use the mean of the transformed response.
}
\usage{
rankTransform(Data, VecName)
}
\arguments{
\item{Data}{
A data set.
}
\item{VecName}{
The name (as a string) of the response to be transformed.
}
}
\value{
\item{Data}{The original data set with a new variable called 'TransformedResponse' which is the rank transform of the response.}
}
\author{
Joe Swintek
}
\examples{
#Data
data(lengthWeightData)
#Subset the data
SubData<-lengthWeightData[lengthWeightData$Age=='16 week', ]
SubData<-SubData[SubData$Generation=='F1', ]
SubData<-SubData[SubData$SEX=='M', ]
#Run
RankData<-rankTransform(Data=SubData, VecName='WEIGHT')
head(RankData)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/apollo_op.R
\name{apollo_op}
\alias{apollo_op}
\title{Calculates Ordered Probit probabilities}
\usage{
apollo_op(op_settings, functionality)
}
\arguments{
\item{op_settings}{List of settings for the OP model. It should include the following.
\itemize{
\item \strong{\code{coding}}: Numeric or character vector. Optional argument. Defines the order of the levels in \code{outcomeOrdered}. The first value is associated with the lowest level of \code{outcomeOrdered}, and the last one with the highest value. If not provided, is assumed to be \code{1:(length(tau) + 1)}.
\item \strong{\code{componentName}}: Character. Name given to model component. If not provided by the user, Apollo will set the name automatically according to the element in \code{P} to which the function output is directed.
\item \strong{\code{outcomeOrdered}}: Numeric vector. Dependent variable. The coding of this variable is assumed to be from 1 to the maximum number of different levels. For example, if the ordered response has three possible values: "never", "sometimes" and "always", then it is assumed that outcomeOrdered contains "1" for "never", "2" for "sometimes", and 3 for "always". If another coding is used, then it should be specified using the \code{coding} argument.
\item \strong{\code{rows}}: Boolean vector. TRUE if a row must be considered in the calculations, FALSE if it must be excluded. It must have length equal to the length of argument \code{outcomeOrdered}. Default value is \code{"all"}, meaning all rows are considered in the calculation.
\item \strong{\code{tau}}: List of numeric vectors/matrices/3-dim arrays. Thresholds. As many as number of different levels in the dependent variable - 1. Extreme thresholds are fixed at -inf and +inf. Mixing is allowed in thresholds. Can also be a matrix with as many rows as observations and as many columns as thresholds.
\item \strong{\code{utilities}}: Numeric vector/matrix/3-sim array. A single explanatory variable (usually a latent variable). Must have the same number of rows as outcomeOrdered.
}}
\item{functionality}{Character. Setting instructing Apollo what processing to apply to the likelihood function. This is in general controlled by the functions that call \code{apollo_probabilities}, though the user can also call \code{apollo_probabilities} manually with a given functionality for testing/debugging. Possible values are:
\itemize{
\item \strong{\code{"components"}}: For further processing/debugging, produces likelihood for each model component (if multiple components are present), at the level of individual draws and observations.
\item \strong{\code{"conditionals"}}: For conditionals, produces likelihood of the full model, at the level of individual inter-individual draws.
\item \strong{\code{"estimate"}}: For model estimation, produces likelihood of the full model, at the level of individual decision-makers, after averaging across draws.
\item \strong{\code{"gradient"}}: For model estimation, produces analytical gradients of the likelihood, where possible.
\item \strong{\code{"output"}}: Prepares output for post-estimation reporting.
\item \strong{\code{"prediction"}}: For model prediction, produces probabilities for individual alternatives and individual model components (if multiple components are present) at the level of an observation, after averaging across draws.
\item \strong{\code{"preprocess"}}: Prepares likelihood functions for use in estimation.
\item \strong{\code{"raw"}}: For debugging, produces probabilities of all alternatives and individual model components at the level of an observation, at the level of individual draws.
\item \strong{\code{"report"}}: Prepares output summarising model and choiceset structure.
\item \strong{\code{"shares_LL"}}: Produces overall model likelihood with constants only.
\item \strong{\code{"validate"}}: Validates model specification, produces likelihood of the full model, at the level of individual decision-makers, after averaging across draws.
\item \strong{\code{"zero_LL"}}: Produces overall model likelihood with all parameters at zero.
}}
}
\value{
The returned object depends on the value of argument \code{functionality} as follows.
\itemize{
\item \strong{\code{"components"}}: Same as \code{"estimate"}
\item \strong{\code{"conditionals"}}: Same as \code{"estimate"}
\item \strong{\code{"estimate"}}: vector/matrix/array. Returns the probabilities for the chosen alternative for each observation.
\item \strong{\code{"gradient"}}: List containing the likelihood and gradient of the model component.
\item \strong{\code{"output"}}: Same as \code{"estimate"} but also writes summary of input data to internal Apollo log.
\item \strong{\code{"prediction"}}: List of vectors/matrices/arrays. Returns a list with the probabilities for all possible levels, with an extra element for the probability of the chosen alternative.
\item \strong{\code{"preprocess"}}: Returns a list with pre-processed inputs, based on \code{op_settings}.
\item \strong{\code{"raw"}}: Same as \code{"prediction"}
\item \strong{\code{"report"}}: Dependent variable overview.
\item \strong{\code{"shares_LL"}}: vector/matrix/array. Returns the probability of the chosen alternative when only constants are estimated.
\item \strong{\code{"validate"}}: Same as \code{"estimate"}, but it also runs a set of tests to validate the function inputs.
\item \strong{\code{"zero_LL"}}: Not implemented. Returns a vector of NA with as many elements as observations.
}
}
\description{
Calculates the probabilities of an Ordered Probit model and can also perform other operations based on the value of the \code{functionality} argument.
}
\details{
This function estimates an ordered probit model of the type:
\deqn{ y^{*} = V + \epsilon \\
y = 1 if -\infty < y^{*} < \tau_1,
2 if \tau_1 < y^{*} < \tau_2,
...,
max(y) if \tau_{max(y)-1} < y^{*} < \infty}
Where \eqn{\epsilon} is distributed standard normal, and the values 1, 2, ..., \eqn{max(y)} can be
replaced by \code{coding[1], coding[2], ..., coding[maxLvl]}.
The behaviour of the function changes depending on the value of the \code{functionality} argument.
}
| /man/apollo_op.Rd | no_license | cran/apollo | R | false | true | 6,392 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/apollo_op.R
\name{apollo_op}
\alias{apollo_op}
\title{Calculates Ordered Probit probabilities}
\usage{
apollo_op(op_settings, functionality)
}
\arguments{
\item{op_settings}{List of settings for the OP model. It should include the following.
\itemize{
\item \strong{\code{coding}}: Numeric or character vector. Optional argument. Defines the order of the levels in \code{outcomeOrdered}. The first value is associated with the lowest level of \code{outcomeOrdered}, and the last one with the highest value. If not provided, is assumed to be \code{1:(length(tau) + 1)}.
\item \strong{\code{componentName}}: Character. Name given to model component. If not provided by the user, Apollo will set the name automatically according to the element in \code{P} to which the function output is directed.
\item \strong{\code{outcomeOrdered}}: Numeric vector. Dependent variable. The coding of this variable is assumed to be from 1 to the maximum number of different levels. For example, if the ordered response has three possible values: "never", "sometimes" and "always", then it is assumed that outcomeOrdered contains "1" for "never", "2" for "sometimes", and 3 for "always". If another coding is used, then it should be specified using the \code{coding} argument.
\item \strong{\code{rows}}: Boolean vector. TRUE if a row must be considered in the calculations, FALSE if it must be excluded. It must have length equal to the length of argument \code{outcomeOrdered}. Default value is \code{"all"}, meaning all rows are considered in the calculation.
\item \strong{\code{tau}}: List of numeric vectors/matrices/3-dim arrays. Thresholds. As many as number of different levels in the dependent variable - 1. Extreme thresholds are fixed at -inf and +inf. Mixing is allowed in thresholds. Can also be a matrix with as many rows as observations and as many columns as thresholds.
\item \strong{\code{utilities}}: Numeric vector/matrix/3-sim array. A single explanatory variable (usually a latent variable). Must have the same number of rows as outcomeOrdered.
}}
\item{functionality}{Character. Setting instructing Apollo what processing to apply to the likelihood function. This is in general controlled by the functions that call \code{apollo_probabilities}, though the user can also call \code{apollo_probabilities} manually with a given functionality for testing/debugging. Possible values are:
\itemize{
\item \strong{\code{"components"}}: For further processing/debugging, produces likelihood for each model component (if multiple components are present), at the level of individual draws and observations.
\item \strong{\code{"conditionals"}}: For conditionals, produces likelihood of the full model, at the level of individual inter-individual draws.
\item \strong{\code{"estimate"}}: For model estimation, produces likelihood of the full model, at the level of individual decision-makers, after averaging across draws.
\item \strong{\code{"gradient"}}: For model estimation, produces analytical gradients of the likelihood, where possible.
\item \strong{\code{"output"}}: Prepares output for post-estimation reporting.
\item \strong{\code{"prediction"}}: For model prediction, produces probabilities for individual alternatives and individual model components (if multiple components are present) at the level of an observation, after averaging across draws.
\item \strong{\code{"preprocess"}}: Prepares likelihood functions for use in estimation.
\item \strong{\code{"raw"}}: For debugging, produces probabilities of all alternatives and individual model components at the level of an observation, at the level of individual draws.
\item \strong{\code{"report"}}: Prepares output summarising model and choiceset structure.
\item \strong{\code{"shares_LL"}}: Produces overall model likelihood with constants only.
\item \strong{\code{"validate"}}: Validates model specification, produces likelihood of the full model, at the level of individual decision-makers, after averaging across draws.
\item \strong{\code{"zero_LL"}}: Produces overall model likelihood with all parameters at zero.
}}
}
\value{
The returned object depends on the value of argument \code{functionality} as follows.
\itemize{
\item \strong{\code{"components"}}: Same as \code{"estimate"}
\item \strong{\code{"conditionals"}}: Same as \code{"estimate"}
\item \strong{\code{"estimate"}}: vector/matrix/array. Returns the probabilities for the chosen alternative for each observation.
\item \strong{\code{"gradient"}}: List containing the likelihood and gradient of the model component.
\item \strong{\code{"output"}}: Same as \code{"estimate"} but also writes summary of input data to internal Apollo log.
\item \strong{\code{"prediction"}}: List of vectors/matrices/arrays. Returns a list with the probabilities for all possible levels, with an extra element for the probability of the chosen alternative.
\item \strong{\code{"preprocess"}}: Returns a list with pre-processed inputs, based on \code{op_settings}.
\item \strong{\code{"raw"}}: Same as \code{"prediction"}
\item \strong{\code{"report"}}: Dependent variable overview.
\item \strong{\code{"shares_LL"}}: vector/matrix/array. Returns the probability of the chosen alternative when only constants are estimated.
\item \strong{\code{"validate"}}: Same as \code{"estimate"}, but it also runs a set of tests to validate the function inputs.
\item \strong{\code{"zero_LL"}}: Not implemented. Returns a vector of NA with as many elements as observations.
}
}
\description{
Calculates the probabilities of an Ordered Probit model and can also perform other operations based on the value of the \code{functionality} argument.
}
\details{
This function estimates an ordered probit model of the type:
\deqn{ y^{*} = V + \epsilon \\
y = 1 if -\infty < y^{*} < \tau_1,
2 if \tau_1 < y^{*} < \tau_2,
...,
max(y) if \tau_{max(y)-1} < y^{*} < \infty}
Where \eqn{\epsilon} is distributed standard normal, and the values 1, 2, ..., \eqn{max(y)} can be
replaced by \code{coding[1], coding[2], ..., coding[maxLvl]}.
The behaviour of the function changes depending on the value of the \code{functionality} argument.
}
|
\name{get.bw}
\alias{get.bw}
\title{Bandwidth Selection}
\usage{
get.bw(x, bw = c("nrd", "ucv", "bcv", "SJ"), nb)
}
\arguments{
\item{x}{n by p maxtrix containing observations of p biomarkers of n subjects.}
\item{bw}{bandwidth selectors of nrd, ucv, bcv, and SJ corresponding to R functions bw.nrd, bw.ucv, bw.bcv, and bw.SJ.}
\item{nb}{number of bins to use, 'na' if bw='nrd'}
}
\description{
get.bw applies a specified bandwidth selection method to the dataset subject-wisely and return the median of the n selected bandwidths as the choice of bandwidth for entropy.weight.
}
\examples{
library(MASS)
# a ten biomarkers dataset generated from independent normal(0,1)
x = mvrnorm(n = 100, mu=rep(0,10), Sigma=diag(10), tol = 1e-6, empirical = FALSE, EISPACK = FALSE)
get.bw(x,bw='ucv',nb=100)
get.bw(x,bw='nrd',nb='na')
}
\keyword{bandwidth}
\keyword{selection}
| /man/get.bw.Rd | no_license | cran/mdw | R | false | false | 891 | rd | \name{get.bw}
\alias{get.bw}
\title{Bandwidth Selection}
\usage{
get.bw(x, bw = c("nrd", "ucv", "bcv", "SJ"), nb)
}
\arguments{
\item{x}{n by p maxtrix containing observations of p biomarkers of n subjects.}
\item{bw}{bandwidth selectors of nrd, ucv, bcv, and SJ corresponding to R functions bw.nrd, bw.ucv, bw.bcv, and bw.SJ.}
\item{nb}{number of bins to use, 'na' if bw='nrd'}
}
\description{
get.bw applies a specified bandwidth selection method to the dataset subject-wisely and return the median of the n selected bandwidths as the choice of bandwidth for entropy.weight.
}
\examples{
library(MASS)
# a ten biomarkers dataset generated from independent normal(0,1)
x = mvrnorm(n = 100, mu=rep(0,10), Sigma=diag(10), tol = 1e-6, empirical = FALSE, EISPACK = FALSE)
get.bw(x,bw='ucv',nb=100)
get.bw(x,bw='nrd',nb='na')
}
\keyword{bandwidth}
\keyword{selection}
|
res_lfc_signi1 <- subset(reslfc1, padj < 0.05)
res_lfc1_signi_df <- as.data.frame(res_lfc1_signi)
reslfc1_pourGO <- na.omit(res_lfc_signi1_df)
write.csv(reslfc1_pourGO, "reslfc1_pourGO.csv")
###get GO tab from https://toppgene.cchmc.org/ with reslfc1_pourGO gene list
res_lfc1_df <- as.data.frame(reslfc1)
de_df <- res_lfc1_df[res_lfc1_df$padj < .05 & !is.na(res_lfc1_df$padj) & !is.na(res_lfc1_df$symbol),]
de_symbols <- de_df$symbol
# extract background genes
bg_ids <- rownames(ddds)[rowSums(counts(ddds)) > 0]
bg_symbols <- mapIds(org.Hs.eg.db,
keys=bg_ids,
column="SYMBOL",
keytype="ENSEMBL",
multiVals="first")
toppgene_tout <- read.csv("GOtoppgene_reslfc1_de_df_test.txt", sep="\t", head=T)
genes <- reslfc1_pourGO[,c("symbol","log2FoldChange")]
colnames(genes) <- c("ID","logFC") #est-ce qu'il faut changer log2FC en log FC ?
colnames(terms) <- c("category","ID","term","adj_pval","genes")
terms$category <- gsub("GO: Cellular Component", "CC", terms$category)
terms$category <- gsub("GO: Biological Process", "BP", terms$category)
terms$category <- gsub("GO: Molecular Function", "MF", terms$category)
library(GOplot)
circle_dat_lfc1up1 <- circle_dat(terms, genes)
circ <- circle_dat_lfc1up1
reduced_circ <- reduce_overlap(circ, overlap = 0.75) # Reduce redundant terms with a gene overlap >= 0.75...
GOBubble(reduced_circ, labels = 2.8, ID=FALSE, title = 'Bubble plot',display = 'multiple',bg.col = T )
IDs <- c('GO:0002053', 'GO:0060537', 'GO:0048333', 'GO:0072359','GO:0030198')
GOCircle(circ, nsub = IDs)
| /gene_ontology.R | no_license | maximemahe/Loffet_2018 | R | false | false | 1,608 | r | res_lfc_signi1 <- subset(reslfc1, padj < 0.05)
res_lfc1_signi_df <- as.data.frame(res_lfc1_signi)
reslfc1_pourGO <- na.omit(res_lfc_signi1_df)
write.csv(reslfc1_pourGO, "reslfc1_pourGO.csv")
###get GO tab from https://toppgene.cchmc.org/ with reslfc1_pourGO gene list
res_lfc1_df <- as.data.frame(reslfc1)
de_df <- res_lfc1_df[res_lfc1_df$padj < .05 & !is.na(res_lfc1_df$padj) & !is.na(res_lfc1_df$symbol),]
de_symbols <- de_df$symbol
# extract background genes
bg_ids <- rownames(ddds)[rowSums(counts(ddds)) > 0]
bg_symbols <- mapIds(org.Hs.eg.db,
keys=bg_ids,
column="SYMBOL",
keytype="ENSEMBL",
multiVals="first")
toppgene_tout <- read.csv("GOtoppgene_reslfc1_de_df_test.txt", sep="\t", head=T)
genes <- reslfc1_pourGO[,c("symbol","log2FoldChange")]
colnames(genes) <- c("ID","logFC") #est-ce qu'il faut changer log2FC en log FC ?
colnames(terms) <- c("category","ID","term","adj_pval","genes")
terms$category <- gsub("GO: Cellular Component", "CC", terms$category)
terms$category <- gsub("GO: Biological Process", "BP", terms$category)
terms$category <- gsub("GO: Molecular Function", "MF", terms$category)
library(GOplot)
circle_dat_lfc1up1 <- circle_dat(terms, genes)
circ <- circle_dat_lfc1up1
reduced_circ <- reduce_overlap(circ, overlap = 0.75) # Reduce redundant terms with a gene overlap >= 0.75...
GOBubble(reduced_circ, labels = 2.8, ID=FALSE, title = 'Bubble plot',display = 'multiple',bg.col = T )
IDs <- c('GO:0002053', 'GO:0060537', 'GO:0048333', 'GO:0072359','GO:0030198')
GOCircle(circ, nsub = IDs)
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/nassqs.R
\name{nassqs}
\alias{nassqs}
\title{Get data and return a data frame}
\usage{
nassqs(params, ...)
}
\arguments{
\item{params}{a named list of parameters to pass to quick stats}
\item{...}{additional parameters passed to low level functions \code{\link{get_nass.single}}
and \code{\link{get_nass.multi}}.}
}
\value{
a data frame of requested data.
}
\description{
Calls nassqs_GET and nassqs_parse and returns a data frame by default.
}
\examples{
\dontrun{
params = list(COMMODITY_NAME="Corn", YEAR=2012, STATE_ALPHA="WA")
get_nass(params)
}
}
| /man/nassqs.Rd | permissive | mespe/rnassqs | R | false | false | 641 | rd | % Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/nassqs.R
\name{nassqs}
\alias{nassqs}
\title{Get data and return a data frame}
\usage{
nassqs(params, ...)
}
\arguments{
\item{params}{a named list of parameters to pass to quick stats}
\item{...}{additional parameters passed to low level functions \code{\link{get_nass.single}}
and \code{\link{get_nass.multi}}.}
}
\value{
a data frame of requested data.
}
\description{
Calls nassqs_GET and nassqs_parse and returns a data frame by default.
}
\examples{
\dontrun{
params = list(COMMODITY_NAME="Corn", YEAR=2012, STATE_ALPHA="WA")
get_nass(params)
}
}
|
# gdxcompare Standalone for online applications
require('data.table')
require('stringr')
require('docopt')
require('countrycode')
require('taRifx')
require('ggplot2')
require('ggpubr')
require('scales')
require('RColorBrewer')
require('dplyr')
require('openxlsx')
require('gsubfn')
require('tidyr')
require('rlang')
require('shiny')
require('shinythemes')
require('rworldmap')
require('sf')
require('rnaturalearth')
require('plotly')
require('purrr')
shinyServer(function(input, output, session) {
#some global flags
verbose = FALSE
save_plot = FALSE
list_of_variables <- c("Q", "Q_EN", "Q_FUEL", "Q_OUT", "Q_EMI", "K", "K_EN", "I_EN", "I", "I_RD", "MCOST_INV", "COST_EMI", "MCOST_EMI", "CPRICE", "MCOST_FUEL", "TEMP", "TRF", "OMEGA", "Q_IN", "ykali", "tpes", "carbonprice", "emi_cap", "l")
#Scenario selector
output$select_scenarios <- renderUI({
selectInput("scenarios_selected", "Select scenarios", scenlist, size=length(scenlist), selectize = F, multiple = T, selected = scenlist)
})
#Variable selector
output$select_variable <- renderUI({
selectInput("variable_selected", "Select variable", list_of_variables, size=1, selectize = F, multiple = F, selected = list_of_variables[1])
})
variable_selected_reactive <- reactive({input$variable_selected})
#Display selected variable and set
output$varname <- renderText({
paste("Variable:", variable_selected_reactive()," Element 1:", paste(input$additional_set_id_selected, collapse=","), " Element 2:", paste(input$additional_set_id_selected2, collapse=","))
})
#REGION selector
output$select_regions <- renderUI({
regions_for_selector <- c(witch_regions, "World")
selectInput("regions_selected", "Select regions", regions_for_selector, size=length(regions_for_selector), selectize = F, multiple = T, selected = witch_regions)
})
#Additional selector for specific Panels
# MAIN CODE FOR PLOT GENERATION
output$gdxompaRplot <- renderPlot({
assign("historical", input$add_historical, envir = .GlobalEnv)
ylim_zero <- input$ylim_zero
#plotly_dynamic <- input$plotly_dynamic
variable <- input$variable_selected
if(is.null(variable)) variable <- list_of_variables[1]
#get data
#afd <- get_witch_simple(variable, check_calibration=TRUE, results = "return")
#now instead from preloaded environment
afd <- get(variable)
if(verbose) print(str_glue("Variable {variable} loaded."))
#get the name of the additional set
additional_sets <- setdiff(colnames(afd), c(file_group_columns, "pathdir", "t", "n", "value"))
#extract additional set elements
if(length(additional_sets)==0){additional_set_id="na"; set_elements = "na"; additional_set_id2="na"; set_elements2 = "na"}
else if(length(additional_sets)==1)
{
additional_set_id <- additional_sets[1]
set_elements <- unique(tolower(as.data.frame(afd)[, match(additional_set_id, colnames(afd))]))
additional_set_id2="na"; set_elements2 = "na"
}
else if(length(additional_sets)==2)
{
additional_set_id <- additional_sets[1]
set_elements <- unique(tolower(as.data.frame(afd)[, match(additional_set_id, colnames(afd))]))
additional_set_id2 <- additional_sets[2]
set_elements2 <- unique(tolower(as.data.frame(afd)[, match(additional_set_id2, colnames(afd))]))
}
#Selector for additional set
output$choose_additional_set <- renderUI({
variable <- variable_selected_reactive()
if(is.null(variable)) variable <- list_of_variables[1]
sel <- input$additional_set_id_selected
size_elements <- min(length(set_elements), 5)
selectInput("additional_set_id_selected", "Additional set element", set_elements, size=size_elements, selectize = F, multiple = T, selected = sel)
})
#Selector for additional set #2
output$choose_additional_set2 <- renderUI({
variable <- variable_selected_reactive()
if(is.null(variable)) variable <- list_of_variables[1]
sel2 <- input$additional_set_id_selected2
size_elements2 <- min(length(set_elements2), 5)
selectInput("additional_set_id_selected2", "Additional set element 2", set_elements2, size=size_elements2, selectize = F, multiple = T, selected = sel2)
})
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
print(deploy_online)
#in case they have not yet been set, set to default values
if(is.null(regions)) regions <- display_regions
if(is.null(additional_set_selected)) additional_set_selected <- set_elements[1]
if((additional_set_id!="na" & additional_set_selected[1]=="na") | !(additional_set_selected[1] %in% set_elements)) additional_set_selected <- set_elements[1]
if(is.null(additional_set_selected2)) additional_set_selected2 <- set_elements2[1]
if((additional_set_id2!="na" & additional_set_selected2[1]=="na") | !(additional_set_selected2[1] %in% set_elements2)) additional_set_selected2 <- set_elements2[1]
# SUBSET data and PLOT
#choose additional selected element
if(additional_set_id!="na"){
afd[[additional_set_id]] <- tolower(afd[[additional_set_id]]) # to fix erroneous gams cases (y and Y etc.)
afd <- subset(afd, get(additional_set_id) %in% additional_set_selected)
afd[[additional_set_id]] <- NULL #remove additional set column
#afd$t <- as.character(afd$t)
if(length(additional_set_selected) >1) afd <- afd %>% group_by_at(setdiff(names(afd), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
if(additional_set_id2!="na"){
afd[[additional_set_id2]] <- tolower(afd[[additional_set_id2]]) # to fix erroneous gams cases (y and Y etc.)
afd <- subset(afd, get(additional_set_id2) %in% additional_set_selected2)
afd[[additional_set_id2]] <- NULL #remove additional set column
if(length(additional_set_selected2) >1) afd <- afd %>% group_by_at(setdiff(names(afd), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
#time frame
afd <- subset(afd, ttoyear(t)>=yearmin & ttoyear(t)<=yearmax)
#clean data
afd <- afd %>% filter(!is.na(value))
#Computation of World/global sum/average
#now based on meta param to guess max, mean, sum
if(nrow(afd)>0){
afd_global <- afd
afd_global$n <- NULL
if(variable %in% default_meta_param()$parameter){
if(default_meta_param()[parameter==variable & type=="nagg"]$value=="sum"){
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}else if(default_meta_param()[parameter==variable & type=="nagg"]$value=="mean"){
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=mean(value), .groups = 'drop')
}
}else{
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
afd_global <- afd_global %>% mutate(n = "World") %>% as.data.frame()
afd <- rbind(afd, afd_global[,c("t","n","value",file_group_columns, "pathdir")])
}
#scenarios, potentially add stochastic scenarios to show
afd <- subset(afd, file %in% c(scenarios, paste0(scenarios, "(b1)"),paste0(scenarios, "(b2)"), paste0(scenarios, "(b3)")) | str_detect(file, "historical") | str_detect(file, "valid"))
#Unit conversion
unit_conv <- unit_conversion(variable)
afd$value <- afd$value * unit_conv$convert
afd$year <- ttoyear(afd$t)
if(regions[1]=="World" | length(regions)==1){#if only World is displayed or only one region, show files with colors
p <- ggplot(subset(afd, n %in% regions & (!str_detect(file, "historical") & !str_detect(file, "valid"))),aes(ttoyear(t),value,colour=file)) + geom_line(stat="identity", size=1.5) + xlab("year") + ylab(unit_conv$unit) + xlim(yearmin,yearmax)
if(ylim_zero) p <- p + ylim(0, NA)
p <- p + geom_line(data=subset(afd, n %in% regions & str_detect(file, "historical")),aes(year,value,colour=file), stat="identity", size=1.0, linetype="solid")
p <- p + geom_point(data=subset(afd, n %in% regions & str_detect(file, "valid")),aes(year,value,colour=file), size=4.0, shape=18)
#legends:
p <- p + theme(text = element_text(size=16), legend.position="bottom", legend.direction = "horizontal", legend.box = "vertical", legend.key = element_rect(colour = NA), legend.title=element_blank()) + guides(color=guide_legend(title=NULL))
}else{
p <- ggplot(subset(afd, n %in% regions & (!str_detect(file, "historical") & !str_detect(file, "valid"))),aes(ttoyear(t),value,colour=n, linetype=file)) + geom_line(stat="identity", size=1.5) + xlab("year") + ylab(unit_conv$unit) + scale_colour_manual(values = region_palette) + xlim(yearmin,yearmax)
p <- p + geom_line(data=subset(afd, n %in% regions & str_detect(file, "historical")),aes(year, value, colour=n, group=interaction(n, file)), linetype = "solid", stat="identity", size=1.0)
p <- p + geom_point(data=subset(afd, n %in% regions & str_detect(file, "valid")),aes(year, value, colour=n, shape=file), size=4.0)
#legends:
p <- p + theme(text = element_text(size=16), legend.position="bottom", legend.direction = "horizontal", legend.box = "vertical", legend.key = element_rect(colour = NA), legend.title=element_blank()) + guides(color=guide_legend(title=NULL, nrow = 2), linetype=guide_legend(title=NULL))
}
if(length(fullpathdir)!=1){p <- p + facet_grid(. ~ pathdir)}
print(p + labs(title=variable))
if(save_plot) saveplot(variable)
})
# MAIN CODE FOR PLOTLY GENERATION (copied from standard ggplot)
output$gdxompaRplotly <- renderPlotly({
assign("historical", input$add_historical, envir = .GlobalEnv)
ylim_zero <- input$ylim_zero
plotly_dynamic <- input$plotly_dynamic
variable <- input$variable_selected
if(is.null(variable)) variable <- list_of_variables[1]
#get data
afd <- get_witch_simple(variable, check_calibration=TRUE, results = "return")
if(verbose) print(str_glue("Variable {variable} loaded."))
#get the name of the additional set
additional_sets <- setdiff(colnames(afd), c(file_group_columns, "pathdir", "t", "n", "value"))
#extract additional set elements
if(length(additional_sets)==0){additional_set_id="na"; set_elements = "na"; additional_set_id2="na"; set_elements2 = "na"}
else if(length(additional_sets)==1)
{
additional_set_id <- additional_sets[1]
set_elements <- unique(tolower(as.data.frame(afd)[, match(additional_set_id, colnames(afd))]))
additional_set_id2="na"; set_elements2 = "na"
}
else if(length(additional_sets)==2)
{
additional_set_id <- additional_sets[1]
set_elements <- unique(tolower(as.data.frame(afd)[, match(additional_set_id, colnames(afd))]))
additional_set_id2 <- additional_sets[2]
set_elements2 <- unique(tolower(as.data.frame(afd)[, match(additional_set_id2, colnames(afd))]))
}
#Selector for additional set
output$choose_additional_set <- renderUI({
variable <- variable_selected_reactive()
if(is.null(variable)) variable <- list_of_variables[1]
sel <- input$additional_set_id_selected
size_elements <- min(length(set_elements), 5)
selectInput("additional_set_id_selected", "Additional set element", set_elements, size=size_elements, selectize = F, multiple = T, selected = sel)
})
#Selector for additional set #2
output$choose_additional_set2 <- renderUI({
variable <- variable_selected_reactive()
if(is.null(variable)) variable <- list_of_variables[1]
sel2 <- input$additional_set_id_selected2
size_elements2 <- min(length(set_elements2), 5)
selectInput("additional_set_id_selected2", "Additional set element 2", set_elements2, size=size_elements2, selectize = F, multiple = T, selected = sel2)
})
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
#in case they have not yet been set, set to default values
if(is.null(regions)) regions <- display_regions
if(is.null(additional_set_selected)) additional_set_selected <- set_elements[1]
if((additional_set_id!="na" & additional_set_selected[1]=="na") | !(additional_set_selected[1] %in% set_elements)) additional_set_selected <- set_elements[1]
if(is.null(additional_set_selected2)) additional_set_selected2 <- set_elements2[1]
if((additional_set_id2!="na" & additional_set_selected2[1]=="na") | !(additional_set_selected2[1] %in% set_elements2)) additional_set_selected2 <- set_elements2[1]
# SUBSET data and PLOT
#choose additional selected element
if(additional_set_id!="na"){
afd[[additional_set_id]] <- tolower(afd[[additional_set_id]]) # to fix erroneous gams cases (y and Y etc.)
afd <- subset(afd, get(additional_set_id) %in% additional_set_selected)
afd[[additional_set_id]] <- NULL #remove additional set column
#afd$t <- as.character(afd$t)
if(length(additional_set_selected) >1) afd <- afd %>% group_by_at(setdiff(names(afd), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
if(additional_set_id2!="na"){
afd[[additional_set_id2]] <- tolower(afd[[additional_set_id2]]) # to fix erroneous gams cases (y and Y etc.)
afd <- subset(afd, get(additional_set_id2) %in% additional_set_selected2)
afd[[additional_set_id2]] <- NULL #remove additional set column
if(length(additional_set_selected2) >1) afd <- afd %>% group_by_at(setdiff(names(afd), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
#time frame
afd <- subset(afd, ttoyear(t)>=yearmin & ttoyear(t)<=yearmax)
#clean data
afd <- afd %>% filter(!is.na(value))
#Computation of World/glboal sum/average
#now based on meta param to guess max, mean, sum
if(nrow(afd)>0){
afd_global <- afd
afd_global$n <- NULL
if(variable %in% default_meta_param()$parameter){
if(default_meta_param()[parameter==variable & type=="nagg"]$value=="sum"){
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}else if(default_meta_param()[parameter==variable & type=="nagg"]$value=="mean"){
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=mean(value), .groups = 'drop')
}else{
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
}
afd_global <- afd_global %>% mutate(n = "World") %>% as.data.frame()
afd <- rbind(afd, afd_global[,c("t","n","value",file_group_columns, "pathdir")])
}
#scenarios, potentially add stochastic scenarios to show
afd <- subset(afd, file %in% c(scenarios, paste0(scenarios, "(b1)"),paste0(scenarios, "(b2)"), paste0(scenarios, "(b3)")) | str_detect(file, "historical") | str_detect(file, "valid"))
#Unit conversion
unit_conv <- unit_conversion(variable)
afd$value <- afd$value * unit_conv$convert
afd$year <- ttoyear(afd$t)
if(regions[1]=="World" | length(regions)==1){#if only World is displayed or only one region, show files with colors
p_dyn <- ggplot(subset(afd, n %in% regions & (!str_detect(file, "historical") & !str_detect(file, "valid"))),aes(year,value,colour=file)) + geom_line(stat="identity", size=1.5) + xlab("year") + ylab(unit_conv$unit) + xlim(yearmin,yearmax)
if(ylim_zero) p_dyn <- p_dyn + ylim(0, NA)
#p_dyn <- p_dyn + geom_line(data=subset(afd, n %in% regions & str_detect(file, "historical")),aes(year,value,colour=file), stat="identity", size=1.0, linetype="solid")
p_dyn <- p_dyn + geom_point(data=subset(afd, n %in% regions & str_detect(file, "valid")),aes(year,value,colour=file), size=4.0, shape=18)
#legends:
p_dyn <- p_dyn + theme(text = element_text(size=16), legend.position="bottom", legend.direction = "horizontal", legend.box = "vertical", legend.key = element_rect(colour = NA), legend.title=element_blank()) + guides(color=guide_legend(title=NULL))
}else{
p_dyn <- ggplot(subset(afd, n %in% regions & (!str_detect(file, "historical") & !str_detect(file, "valid"))),aes(year,value,colour=n, linetype=file)) + geom_line(stat="identity", size=1.5) + xlab("year") + ylab(unit_conv$unit) + scale_colour_manual(values = region_palette) + xlim(yearmin,yearmax)
#p_dyn <- p_dyn + geom_line(data=subset(afd, n %in% regions & str_detect(file, "historical")),aes(ttoyear(t),value,colour=n), linetype = "solid", stat="identity", size=1.0)
p_dyn <- p_dyn + geom_point(data=subset(afd, n %in% regions & str_detect(file, "valid")),aes(year,value, shape=file), size=4.0)
#legends:
p_dyn <- p_dyn + theme(text = element_text(size=16), legend.position="bottom", legend.direction = "horizontal", legend.box = "vertical", legend.key = element_rect(colour = NA), legend.title=element_blank()) + guides(color=guide_legend(title=NULL, nrow = 2), linetype=guide_legend(title=NULL))
}
if(length(fullpathdir)!=1){p_dyn <- p_dyn + facet_grid(. ~ pathdir)}
p_dyn <- p_dyn + theme(legend.position = "none")
print(p_dyn)
suppressWarnings(ggplotly()) #to be done: fix error "argument 1 is not a vector", shoudl be done by plotly package
})
output$inequalityplot <- renderPlot({
#get input from sliders/buttons
variable_ineq <- input$variable_selected
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
inequality_plot_type_selected <- input$inequality_plot_type_selected
inequality_value_share <- input$inequality_value_share
plot_inequality(variable = variable_ineq, plot_type = inequality_plot_type_selected, value_share = inequality_value_share, quantile_set = "dist", regions = regions[1], years = seq(yearmin, yearmax), years_lorenz = range(yearmin, yearmax), scenplot = scenarios)
})
output$Diagnostics <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
diagnostics_plots(scenplot = scenarios)
})
output$energymixplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
mix_plot_type_selected <- input$mix_plot_type_selected
mix_y_value_selected <- input$mix_y_value_selected
Primary_Energy_Mix(PES_y = mix_y_value_selected, regions = regions[1], years = seq(yearmin, yearmax, 1), plot_type = mix_plot_type_selected, scenplot = scenarios)
})
output$electricitymixplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
mix_plot_type_selected <- input$mix_plot_type_selected
mix_y_value_selected <- input$mix_y_value_selected
Electricity_Mix(Electricity_y = mix_y_value_selected, regions = regions[1], years = seq(yearmin, yearmax, 1), plot_type = mix_plot_type_selected, scenplot = scenarios)
})
output$investmentplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
Investment_Plot(regions="World", scenplot = scenarios)
})
output$policycostplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
Policy_Cost(discount_rate=5, regions=regions, bauscen = scenarios[1], show_numbers=TRUE, tmax=yeartot(yearmax))
})
output$intensityplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
Intensity_Plot(years=c(yearmax, yearmax-50), regions = regions, year0=2010, scenplot = scenarios, animate_plot = FALSE)
})
output$impactmap <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
t_map = yeartot(yearmax); bau_scen = scenarios[1]
get_witch_simple("Q")
impact_map_data <- Q %>% filter(iq=="y" & t==t_map) %>% group_by(n, pathdir) %>% mutate(value = -((value/sum(value[file==bau_scen]))-1)*100) %>% filter(is.finite(value))
scen <- scenarios[2]
witchmap(impact_map_data, file_report=scen, t_report=t_map, mapcolor="Reds", map_name="Impact Map", map_legend = str_glue("GDP loss [%] in {scen}."))
})
output$climate_plot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
climate_plot(scenplot = scenarios)
})
output$SCC_plot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
scc_normalization_region <- input$scc_normalization_region
SCC_plot(scenplot = scenarios, regions = regions, normalization_region = scc_normalization_region)
})
})
| /gdxcompaR/witch-online/server.R | permissive | Mareasunami/witch-plot | R | false | false | 24,303 | r | # gdxcompare Standalone for online applications
require('data.table')
require('stringr')
require('docopt')
require('countrycode')
require('taRifx')
require('ggplot2')
require('ggpubr')
require('scales')
require('RColorBrewer')
require('dplyr')
require('openxlsx')
require('gsubfn')
require('tidyr')
require('rlang')
require('shiny')
require('shinythemes')
require('rworldmap')
require('sf')
require('rnaturalearth')
require('plotly')
require('purrr')
shinyServer(function(input, output, session) {
#some global flags
verbose = FALSE
save_plot = FALSE
list_of_variables <- c("Q", "Q_EN", "Q_FUEL", "Q_OUT", "Q_EMI", "K", "K_EN", "I_EN", "I", "I_RD", "MCOST_INV", "COST_EMI", "MCOST_EMI", "CPRICE", "MCOST_FUEL", "TEMP", "TRF", "OMEGA", "Q_IN", "ykali", "tpes", "carbonprice", "emi_cap", "l")
#Scenario selector
output$select_scenarios <- renderUI({
selectInput("scenarios_selected", "Select scenarios", scenlist, size=length(scenlist), selectize = F, multiple = T, selected = scenlist)
})
#Variable selector
output$select_variable <- renderUI({
selectInput("variable_selected", "Select variable", list_of_variables, size=1, selectize = F, multiple = F, selected = list_of_variables[1])
})
variable_selected_reactive <- reactive({input$variable_selected})
#Display selected variable and set
output$varname <- renderText({
paste("Variable:", variable_selected_reactive()," Element 1:", paste(input$additional_set_id_selected, collapse=","), " Element 2:", paste(input$additional_set_id_selected2, collapse=","))
})
#REGION selector
output$select_regions <- renderUI({
regions_for_selector <- c(witch_regions, "World")
selectInput("regions_selected", "Select regions", regions_for_selector, size=length(regions_for_selector), selectize = F, multiple = T, selected = witch_regions)
})
#Additional selector for specific Panels
# MAIN CODE FOR PLOT GENERATION
output$gdxompaRplot <- renderPlot({
assign("historical", input$add_historical, envir = .GlobalEnv)
ylim_zero <- input$ylim_zero
#plotly_dynamic <- input$plotly_dynamic
variable <- input$variable_selected
if(is.null(variable)) variable <- list_of_variables[1]
#get data
#afd <- get_witch_simple(variable, check_calibration=TRUE, results = "return")
#now instead from preloaded environment
afd <- get(variable)
if(verbose) print(str_glue("Variable {variable} loaded."))
#get the name of the additional set
additional_sets <- setdiff(colnames(afd), c(file_group_columns, "pathdir", "t", "n", "value"))
#extract additional set elements
if(length(additional_sets)==0){additional_set_id="na"; set_elements = "na"; additional_set_id2="na"; set_elements2 = "na"}
else if(length(additional_sets)==1)
{
additional_set_id <- additional_sets[1]
set_elements <- unique(tolower(as.data.frame(afd)[, match(additional_set_id, colnames(afd))]))
additional_set_id2="na"; set_elements2 = "na"
}
else if(length(additional_sets)==2)
{
additional_set_id <- additional_sets[1]
set_elements <- unique(tolower(as.data.frame(afd)[, match(additional_set_id, colnames(afd))]))
additional_set_id2 <- additional_sets[2]
set_elements2 <- unique(tolower(as.data.frame(afd)[, match(additional_set_id2, colnames(afd))]))
}
#Selector for additional set
output$choose_additional_set <- renderUI({
variable <- variable_selected_reactive()
if(is.null(variable)) variable <- list_of_variables[1]
sel <- input$additional_set_id_selected
size_elements <- min(length(set_elements), 5)
selectInput("additional_set_id_selected", "Additional set element", set_elements, size=size_elements, selectize = F, multiple = T, selected = sel)
})
#Selector for additional set #2
output$choose_additional_set2 <- renderUI({
variable <- variable_selected_reactive()
if(is.null(variable)) variable <- list_of_variables[1]
sel2 <- input$additional_set_id_selected2
size_elements2 <- min(length(set_elements2), 5)
selectInput("additional_set_id_selected2", "Additional set element 2", set_elements2, size=size_elements2, selectize = F, multiple = T, selected = sel2)
})
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
print(deploy_online)
#in case they have not yet been set, set to default values
if(is.null(regions)) regions <- display_regions
if(is.null(additional_set_selected)) additional_set_selected <- set_elements[1]
if((additional_set_id!="na" & additional_set_selected[1]=="na") | !(additional_set_selected[1] %in% set_elements)) additional_set_selected <- set_elements[1]
if(is.null(additional_set_selected2)) additional_set_selected2 <- set_elements2[1]
if((additional_set_id2!="na" & additional_set_selected2[1]=="na") | !(additional_set_selected2[1] %in% set_elements2)) additional_set_selected2 <- set_elements2[1]
# SUBSET data and PLOT
#choose additional selected element
if(additional_set_id!="na"){
afd[[additional_set_id]] <- tolower(afd[[additional_set_id]]) # to fix erroneous gams cases (y and Y etc.)
afd <- subset(afd, get(additional_set_id) %in% additional_set_selected)
afd[[additional_set_id]] <- NULL #remove additional set column
#afd$t <- as.character(afd$t)
if(length(additional_set_selected) >1) afd <- afd %>% group_by_at(setdiff(names(afd), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
if(additional_set_id2!="na"){
afd[[additional_set_id2]] <- tolower(afd[[additional_set_id2]]) # to fix erroneous gams cases (y and Y etc.)
afd <- subset(afd, get(additional_set_id2) %in% additional_set_selected2)
afd[[additional_set_id2]] <- NULL #remove additional set column
if(length(additional_set_selected2) >1) afd <- afd %>% group_by_at(setdiff(names(afd), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
#time frame
afd <- subset(afd, ttoyear(t)>=yearmin & ttoyear(t)<=yearmax)
#clean data
afd <- afd %>% filter(!is.na(value))
#Computation of World/global sum/average
#now based on meta param to guess max, mean, sum
if(nrow(afd)>0){
afd_global <- afd
afd_global$n <- NULL
if(variable %in% default_meta_param()$parameter){
if(default_meta_param()[parameter==variable & type=="nagg"]$value=="sum"){
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}else if(default_meta_param()[parameter==variable & type=="nagg"]$value=="mean"){
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=mean(value), .groups = 'drop')
}
}else{
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
afd_global <- afd_global %>% mutate(n = "World") %>% as.data.frame()
afd <- rbind(afd, afd_global[,c("t","n","value",file_group_columns, "pathdir")])
}
#scenarios, potentially add stochastic scenarios to show
afd <- subset(afd, file %in% c(scenarios, paste0(scenarios, "(b1)"),paste0(scenarios, "(b2)"), paste0(scenarios, "(b3)")) | str_detect(file, "historical") | str_detect(file, "valid"))
#Unit conversion
unit_conv <- unit_conversion(variable)
afd$value <- afd$value * unit_conv$convert
afd$year <- ttoyear(afd$t)
if(regions[1]=="World" | length(regions)==1){#if only World is displayed or only one region, show files with colors
p <- ggplot(subset(afd, n %in% regions & (!str_detect(file, "historical") & !str_detect(file, "valid"))),aes(ttoyear(t),value,colour=file)) + geom_line(stat="identity", size=1.5) + xlab("year") + ylab(unit_conv$unit) + xlim(yearmin,yearmax)
if(ylim_zero) p <- p + ylim(0, NA)
p <- p + geom_line(data=subset(afd, n %in% regions & str_detect(file, "historical")),aes(year,value,colour=file), stat="identity", size=1.0, linetype="solid")
p <- p + geom_point(data=subset(afd, n %in% regions & str_detect(file, "valid")),aes(year,value,colour=file), size=4.0, shape=18)
#legends:
p <- p + theme(text = element_text(size=16), legend.position="bottom", legend.direction = "horizontal", legend.box = "vertical", legend.key = element_rect(colour = NA), legend.title=element_blank()) + guides(color=guide_legend(title=NULL))
}else{
p <- ggplot(subset(afd, n %in% regions & (!str_detect(file, "historical") & !str_detect(file, "valid"))),aes(ttoyear(t),value,colour=n, linetype=file)) + geom_line(stat="identity", size=1.5) + xlab("year") + ylab(unit_conv$unit) + scale_colour_manual(values = region_palette) + xlim(yearmin,yearmax)
p <- p + geom_line(data=subset(afd, n %in% regions & str_detect(file, "historical")),aes(year, value, colour=n, group=interaction(n, file)), linetype = "solid", stat="identity", size=1.0)
p <- p + geom_point(data=subset(afd, n %in% regions & str_detect(file, "valid")),aes(year, value, colour=n, shape=file), size=4.0)
#legends:
p <- p + theme(text = element_text(size=16), legend.position="bottom", legend.direction = "horizontal", legend.box = "vertical", legend.key = element_rect(colour = NA), legend.title=element_blank()) + guides(color=guide_legend(title=NULL, nrow = 2), linetype=guide_legend(title=NULL))
}
if(length(fullpathdir)!=1){p <- p + facet_grid(. ~ pathdir)}
print(p + labs(title=variable))
if(save_plot) saveplot(variable)
})
# MAIN CODE FOR PLOTLY GENERATION (copied from standard ggplot)
output$gdxompaRplotly <- renderPlotly({
assign("historical", input$add_historical, envir = .GlobalEnv)
ylim_zero <- input$ylim_zero
plotly_dynamic <- input$plotly_dynamic
variable <- input$variable_selected
if(is.null(variable)) variable <- list_of_variables[1]
#get data
afd <- get_witch_simple(variable, check_calibration=TRUE, results = "return")
if(verbose) print(str_glue("Variable {variable} loaded."))
#get the name of the additional set
additional_sets <- setdiff(colnames(afd), c(file_group_columns, "pathdir", "t", "n", "value"))
#extract additional set elements
if(length(additional_sets)==0){additional_set_id="na"; set_elements = "na"; additional_set_id2="na"; set_elements2 = "na"}
else if(length(additional_sets)==1)
{
additional_set_id <- additional_sets[1]
set_elements <- unique(tolower(as.data.frame(afd)[, match(additional_set_id, colnames(afd))]))
additional_set_id2="na"; set_elements2 = "na"
}
else if(length(additional_sets)==2)
{
additional_set_id <- additional_sets[1]
set_elements <- unique(tolower(as.data.frame(afd)[, match(additional_set_id, colnames(afd))]))
additional_set_id2 <- additional_sets[2]
set_elements2 <- unique(tolower(as.data.frame(afd)[, match(additional_set_id2, colnames(afd))]))
}
#Selector for additional set
output$choose_additional_set <- renderUI({
variable <- variable_selected_reactive()
if(is.null(variable)) variable <- list_of_variables[1]
sel <- input$additional_set_id_selected
size_elements <- min(length(set_elements), 5)
selectInput("additional_set_id_selected", "Additional set element", set_elements, size=size_elements, selectize = F, multiple = T, selected = sel)
})
#Selector for additional set #2
output$choose_additional_set2 <- renderUI({
variable <- variable_selected_reactive()
if(is.null(variable)) variable <- list_of_variables[1]
sel2 <- input$additional_set_id_selected2
size_elements2 <- min(length(set_elements2), 5)
selectInput("additional_set_id_selected2", "Additional set element 2", set_elements2, size=size_elements2, selectize = F, multiple = T, selected = sel2)
})
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
#in case they have not yet been set, set to default values
if(is.null(regions)) regions <- display_regions
if(is.null(additional_set_selected)) additional_set_selected <- set_elements[1]
if((additional_set_id!="na" & additional_set_selected[1]=="na") | !(additional_set_selected[1] %in% set_elements)) additional_set_selected <- set_elements[1]
if(is.null(additional_set_selected2)) additional_set_selected2 <- set_elements2[1]
if((additional_set_id2!="na" & additional_set_selected2[1]=="na") | !(additional_set_selected2[1] %in% set_elements2)) additional_set_selected2 <- set_elements2[1]
# SUBSET data and PLOT
#choose additional selected element
if(additional_set_id!="na"){
afd[[additional_set_id]] <- tolower(afd[[additional_set_id]]) # to fix erroneous gams cases (y and Y etc.)
afd <- subset(afd, get(additional_set_id) %in% additional_set_selected)
afd[[additional_set_id]] <- NULL #remove additional set column
#afd$t <- as.character(afd$t)
if(length(additional_set_selected) >1) afd <- afd %>% group_by_at(setdiff(names(afd), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
if(additional_set_id2!="na"){
afd[[additional_set_id2]] <- tolower(afd[[additional_set_id2]]) # to fix erroneous gams cases (y and Y etc.)
afd <- subset(afd, get(additional_set_id2) %in% additional_set_selected2)
afd[[additional_set_id2]] <- NULL #remove additional set column
if(length(additional_set_selected2) >1) afd <- afd %>% group_by_at(setdiff(names(afd), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
#time frame
afd <- subset(afd, ttoyear(t)>=yearmin & ttoyear(t)<=yearmax)
#clean data
afd <- afd %>% filter(!is.na(value))
#Computation of World/glboal sum/average
#now based on meta param to guess max, mean, sum
if(nrow(afd)>0){
afd_global <- afd
afd_global$n <- NULL
if(variable %in% default_meta_param()$parameter){
if(default_meta_param()[parameter==variable & type=="nagg"]$value=="sum"){
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}else if(default_meta_param()[parameter==variable & type=="nagg"]$value=="mean"){
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=mean(value), .groups = 'drop')
}else{
afd_global <- afd_global %>% group_by_at(setdiff(names(afd_global), "value")) %>% summarize(value=sum(value), .groups = 'drop')
}
}
afd_global <- afd_global %>% mutate(n = "World") %>% as.data.frame()
afd <- rbind(afd, afd_global[,c("t","n","value",file_group_columns, "pathdir")])
}
#scenarios, potentially add stochastic scenarios to show
afd <- subset(afd, file %in% c(scenarios, paste0(scenarios, "(b1)"),paste0(scenarios, "(b2)"), paste0(scenarios, "(b3)")) | str_detect(file, "historical") | str_detect(file, "valid"))
#Unit conversion
unit_conv <- unit_conversion(variable)
afd$value <- afd$value * unit_conv$convert
afd$year <- ttoyear(afd$t)
if(regions[1]=="World" | length(regions)==1){#if only World is displayed or only one region, show files with colors
p_dyn <- ggplot(subset(afd, n %in% regions & (!str_detect(file, "historical") & !str_detect(file, "valid"))),aes(year,value,colour=file)) + geom_line(stat="identity", size=1.5) + xlab("year") + ylab(unit_conv$unit) + xlim(yearmin,yearmax)
if(ylim_zero) p_dyn <- p_dyn + ylim(0, NA)
#p_dyn <- p_dyn + geom_line(data=subset(afd, n %in% regions & str_detect(file, "historical")),aes(year,value,colour=file), stat="identity", size=1.0, linetype="solid")
p_dyn <- p_dyn + geom_point(data=subset(afd, n %in% regions & str_detect(file, "valid")),aes(year,value,colour=file), size=4.0, shape=18)
#legends:
p_dyn <- p_dyn + theme(text = element_text(size=16), legend.position="bottom", legend.direction = "horizontal", legend.box = "vertical", legend.key = element_rect(colour = NA), legend.title=element_blank()) + guides(color=guide_legend(title=NULL))
}else{
p_dyn <- ggplot(subset(afd, n %in% regions & (!str_detect(file, "historical") & !str_detect(file, "valid"))),aes(year,value,colour=n, linetype=file)) + geom_line(stat="identity", size=1.5) + xlab("year") + ylab(unit_conv$unit) + scale_colour_manual(values = region_palette) + xlim(yearmin,yearmax)
#p_dyn <- p_dyn + geom_line(data=subset(afd, n %in% regions & str_detect(file, "historical")),aes(ttoyear(t),value,colour=n), linetype = "solid", stat="identity", size=1.0)
p_dyn <- p_dyn + geom_point(data=subset(afd, n %in% regions & str_detect(file, "valid")),aes(year,value, shape=file), size=4.0)
#legends:
p_dyn <- p_dyn + theme(text = element_text(size=16), legend.position="bottom", legend.direction = "horizontal", legend.box = "vertical", legend.key = element_rect(colour = NA), legend.title=element_blank()) + guides(color=guide_legend(title=NULL, nrow = 2), linetype=guide_legend(title=NULL))
}
if(length(fullpathdir)!=1){p_dyn <- p_dyn + facet_grid(. ~ pathdir)}
p_dyn <- p_dyn + theme(legend.position = "none")
print(p_dyn)
suppressWarnings(ggplotly()) #to be done: fix error "argument 1 is not a vector", shoudl be done by plotly package
})
output$inequalityplot <- renderPlot({
#get input from sliders/buttons
variable_ineq <- input$variable_selected
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
inequality_plot_type_selected <- input$inequality_plot_type_selected
inequality_value_share <- input$inequality_value_share
plot_inequality(variable = variable_ineq, plot_type = inequality_plot_type_selected, value_share = inequality_value_share, quantile_set = "dist", regions = regions[1], years = seq(yearmin, yearmax), years_lorenz = range(yearmin, yearmax), scenplot = scenarios)
})
output$Diagnostics <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
diagnostics_plots(scenplot = scenarios)
})
output$energymixplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
mix_plot_type_selected <- input$mix_plot_type_selected
mix_y_value_selected <- input$mix_y_value_selected
Primary_Energy_Mix(PES_y = mix_y_value_selected, regions = regions[1], years = seq(yearmin, yearmax, 1), plot_type = mix_plot_type_selected, scenplot = scenarios)
})
output$electricitymixplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
mix_plot_type_selected <- input$mix_plot_type_selected
mix_y_value_selected <- input$mix_y_value_selected
Electricity_Mix(Electricity_y = mix_y_value_selected, regions = regions[1], years = seq(yearmin, yearmax, 1), plot_type = mix_plot_type_selected, scenplot = scenarios)
})
output$investmentplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
Investment_Plot(regions="World", scenplot = scenarios)
})
output$policycostplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
Policy_Cost(discount_rate=5, regions=regions, bauscen = scenarios[1], show_numbers=TRUE, tmax=yeartot(yearmax))
})
output$intensityplot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
Intensity_Plot(years=c(yearmax, yearmax-50), regions = regions, year0=2010, scenplot = scenarios, animate_plot = FALSE)
})
output$impactmap <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
t_map = yeartot(yearmax); bau_scen = scenarios[1]
get_witch_simple("Q")
impact_map_data <- Q %>% filter(iq=="y" & t==t_map) %>% group_by(n, pathdir) %>% mutate(value = -((value/sum(value[file==bau_scen]))-1)*100) %>% filter(is.finite(value))
scen <- scenarios[2]
witchmap(impact_map_data, file_report=scen, t_report=t_map, mapcolor="Reds", map_name="Impact Map", map_legend = str_glue("GDP loss [%] in {scen}."))
})
output$climate_plot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
climate_plot(scenplot = scenarios)
})
output$SCC_plot <- renderPlot({
#get input from sliders/buttons
yearmin = input$yearmin
yearmax = input$yearmax
additional_set_selected <- input$additional_set_id_selected
additional_set_selected2 <- input$additional_set_id_selected2
regions <- input$regions_selected
scenarios <- input$scenarios_selected
scc_normalization_region <- input$scc_normalization_region
SCC_plot(scenplot = scenarios, regions = regions, normalization_region = scc_normalization_region)
})
})
|
library(scales)
### Name: hue_pal
### Title: Hue palette (discrete).
### Aliases: hue_pal
### ** Examples
show_col(hue_pal()(4))
show_col(hue_pal()(9))
show_col(hue_pal(l = 90)(9))
show_col(hue_pal(l = 30)(9))
show_col(hue_pal()(9))
show_col(hue_pal(direction = -1)(9))
show_col(hue_pal()(9))
show_col(hue_pal(h = c(0, 90))(9))
show_col(hue_pal(h = c(90, 180))(9))
show_col(hue_pal(h = c(180, 270))(9))
show_col(hue_pal(h = c(270, 360))(9))
| /data/genthat_extracted_code/scales/examples/hue_pal.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 450 | r | library(scales)
### Name: hue_pal
### Title: Hue palette (discrete).
### Aliases: hue_pal
### ** Examples
show_col(hue_pal()(4))
show_col(hue_pal()(9))
show_col(hue_pal(l = 90)(9))
show_col(hue_pal(l = 30)(9))
show_col(hue_pal()(9))
show_col(hue_pal(direction = -1)(9))
show_col(hue_pal()(9))
show_col(hue_pal(h = c(0, 90))(9))
show_col(hue_pal(h = c(90, 180))(9))
show_col(hue_pal(h = c(180, 270))(9))
show_col(hue_pal(h = c(270, 360))(9))
|
context("System metadata")
test_that("the replication policy gets cleared", {
library(datapack)
sysmeta <- new("SystemMetadata")
expect_true(sysmeta@replicationAllowed)
sysmeta <- clear_replication_policy(sysmeta)
expect_false(sysmeta@replicationAllowed)
})
test_that("the replication policy gets defaulted correctly", {
# this is just a regression test
library(datapack)
sysmeta <- new("SystemMetadata")
sysmeta <- clear_replication_policy(sysmeta)
expect_false(sysmeta@replicationAllowed)
expect_equal(sysmeta@numberReplicas, 0)
expect_identical(sysmeta@blockedNodes, list("urn:node:KNB", "urn:node:mnUCSB1"))
})
| /tests/testthat/test_sysmeta.R | permissive | NCEAS/arcticdatautils | R | false | false | 646 | r | context("System metadata")
test_that("the replication policy gets cleared", {
library(datapack)
sysmeta <- new("SystemMetadata")
expect_true(sysmeta@replicationAllowed)
sysmeta <- clear_replication_policy(sysmeta)
expect_false(sysmeta@replicationAllowed)
})
test_that("the replication policy gets defaulted correctly", {
# this is just a regression test
library(datapack)
sysmeta <- new("SystemMetadata")
sysmeta <- clear_replication_policy(sysmeta)
expect_false(sysmeta@replicationAllowed)
expect_equal(sysmeta@numberReplicas, 0)
expect_identical(sysmeta@blockedNodes, list("urn:node:KNB", "urn:node:mnUCSB1"))
})
|
######
Work Flow working genrating a final Sigs_Input file for recurrent medulloblastoma cases.
#Packages used
maftools::
deconstructSigs::
BSgenome.Hsapiens.UCSC.hg19::
BSgenome::
###
#Cases : MB-REC-02, 03,41,06,09,10 from ICGC
#Variants called against germline.
#Recurrence at mestatic site.
#MAF files were generated by Megan Bowman
Germline_Met_Recur<- read.delim("~/Desktop/Data_Analysis/last MAF files/ICGC_germline_metastatic_reduced_maf_final.txt", header=TRUE)
View(Germline_Met_Recur)
Germline_Met_Recur_Maf <- read.maf(maf = "~/Desktop/Data_Analysis/last MAF files/ICGC_germline_metastatic_reduced_maf_final.txt")
mafSummary(Germline_Met_Recur_Maf)
##$variants.per.sample
##Tumor_Sample_Barcode Variants
1: MB-REC-06 511043
2: MB-REC-09 6293
3: MB-REC-10 4690
4: MB-REC-02 3728
5: MB-REC-41 2181
6: MB-REC-03 1419
#Cases : MB-REC-16, 14,11,07,08,04,13,12,15 from ICGC
#Variants called against germline.
#Recurrence at Primary site.
#This MAF file was generated by Ian Beddows.
Germline_Recur<- read.delim("~/Desktop/Data_Analysis/last MAF files/9_recurrent_germline_samples_GRCH38_crossmapped_to_GRCH37.maf.txt", header=FALSE, comment.char="#")
View(Germline_Recur)
Germline_Recur_Maf <- read.maf(maf = "~/Desktop/Data_Analysis/last MAF files/9_recurrent_germline_samples_GRCH38_crossmapped_to_GRCH37.maf.txt" )
mafSummary(Germline_Recur_Maf)
##$variant.per.sampple
##Tumor_Sample_Barcode Variants
1: MB-REC-16 28931
2: MB-REC-14 11212
3: MB-REC-11 9789
4: MB-REC-07 7300
5: MB-REC-08 6913
6: MB-REC-04 6250
7: MB-REC-13 5689
8: MB-REC-12 5332
9: MB-REC-15 4453
## To create a DF with rows with number of cases (Recurrent) and 96 columns of of the types of single nucleotide subsitution.
##Subset_Met_GermLine_73.csv was created earlier after deleting the 73 variants from the original MAF file that didnot match the context.
Germline_Met_Recur_Sigs_Input_file <- read.csv("~/Desktop/Data_Analysis/last MAF files/SUbset_Mets_Germline_73.csv")
Germline_Recur_Met_Sigs <- mut.to.sigs.input(Germline_Met_Recur_Sigs_Input_file, sample.id = "Sample", chr = "chr", pos = "X",
ref = "ref", alt = "alt", bsg = NULL)
View(Germline_Recur_Met_Sigs)
RecurrentMB <- whichSignatures(tumor.ref = Germline_Recur_Met_Sigs , sample.id = "MB-REC-03",
signatures.ref = signatures.nature2013, associated = c(),
signatures.limit = NA, signature.cutoff = 0.06, contexts.needed = TRUE,
tri.counts.method = "default")
plotSignatures(RecurrentMB03)
makePie(RecurrentMB03, sub = "RecurrentMB03", add.color = NULL)
##To create a DF with rows with number of cases (Recurrent) and 96 columns of of the types of single nucleotide subsitution
## This will be done on the 9 cases in Germline_Recur_Maf
#Create a CSV File with "Sample", "chr", 'pos", "ref", "alt" ; a subset of the maffile.
Germline_Recur_Maf_Subset <- read.csv("~/Desktop/Data_Analysis/last MAF files/Germline_Recur_Maf_Subset.csv")
Germline_Recur_Maf_Subset <- as.data.frame(Germline_Recur_Maf_Subset)
Germline_Met_Recur_Sigs <- mut.to.sigs.input(Germline_Recur_Maf_Subset, sample.id = "sample", chr = "chr", pos = "pos",ref = "ref", alt = "alt", bsg = NULL)
View(Germline_Met_Recur_Sigs)
RecurrentMB16 <- whichSignatures(tumor.ref = Germline_Met_Recur_Sigs , sample.id = "MB-REC-16",
signatures.ref = signatures.nature2013, associated = c(),
signatures.limit = NA, signature.cutoff = 0.06, contexts.needed = TRUE,
tri.counts.method = "default")
plotSignatures(RecurrentMB16)
makePie(RecurrentMB16, sub = "RecurrentMB16", add.color = NULL)
##The DF
A[C>A]A A[C>A]C A[C>A]G A[C>A]T C[C>A]A C[C>A]C C[C>A]G C[C>A]T G[C>A]A G[C>A]C G[C>A]G G[C>A]T T[C>A]A T[C>A]C T[C>A]G
MB-REC-04 115 73 5 36 90 51 19 81 83 43 10 30 90 57 4
MB-REC-07 134 59 3 42 78 59 16 64 122 89 17 88 88 43 12
MB-REC-08 59 32 8 40 51 45 5 53 43 39 6 23 39 34 10
MB-REC-11 192 154 27 123 115 136 21 155 70 82 13 60 141 143 10
MB-REC-12 95 56 11 50 92 60 12 105 38 38 10 37 76 81 5
MB-REC-13 99 74 8 62 122 81 11 146 112 64 15 73 80 97 8
MB-REC-14 195 188 33 138 236 143 20 246 120 127 19 86 145 153 16
MB-REC-15 69 64 11 41 61 56 20 71 49 61 17 28 70 55 21
MB-REC-16 240 137 33 198 235 184 56 268 173 117 29 133 236 129 22
T[C>A]T A[C>G]A A[C>G]C A[C>G]G A[C>G]T C[C>G]A C[C>G]C C[C>G]G C[C>G]T G[C>G]A G[C>G]C G[C>G]G G[C>G]T T[C>G]A T[C>G]C
MB-REC-04 102 40 22 9 24 22 15 12 28 29 25 5 18 32 18
MB-REC-07 109 46 19 11 36 28 31 10 27 54 38 22 29 29 27
MB-REC-08 54 48 41 8 47 24 23 10 20 27 28 8 27 36 40
MB-REC-11 173 57 79 21 51 24 35 10 30 22 37 7 35 29 56
MB-REC-12 73 32 53 8 44 19 28 7 23 23 42 4 38 28 47
MB-REC-13 118 32 23 13 42 38 32 6 41 41 38 17 25 39 33
MB-REC-14 212 75 69 20 71 39 36 13 62 34 33 11 50 60 63
MB-REC-15 85 29 19 13 26 9 18 6 20 15 11 8 12 23 21
MB-REC-16 231 115 45 26 103 48 47 16 38 88 53 16 63 133 60
T[C>G]G T[C>G]T A[C>T]A A[C>T]C A[C>T]G A[C>T]T C[C>T]A C[C>T]C C[C>T]G C[C>T]T G[C>T]A G[C>T]C G[C>T]G G[C>T]T T[C>T]A
MB-REC-04 7 43 96 45 270 74 79 73 132 81 92 73 206 64 68
MB-REC-07 2 37 123 59 120 86 81 80 67 94 90 66 91 103 77
MB-REC-08 11 51 108 55 105 90 86 68 90 68 60 55 103 59 65
MB-REC-11 7 79 239 134 494 151 162 205 312 207 127 152 357 133 165
MB-REC-12 5 84 104 77 93 86 68 127 68 119 61 104 56 92 65
MB-REC-13 9 46 105 83 101 124 62 117 85 124 113 128 122 126 79
MB-REC-14 8 120 229 153 437 175 168 219 238 208 107 149 252 127 133
MB-REC-15 8 21 81 59 334 66 70 156 210 111 65 73 257 54 48
MB-REC-16 12 132 219 119 130 263 152 112 80 234 163 101 111 182 201
T[C>T]C T[C>T]G T[C>T]T A[T>A]A A[T>A]C A[T>A]G A[T>A]T C[T>A]A C[T>A]C C[T>A]G C[T>A]T G[T>A]A G[T>A]C G[T>A]G G[T>A]T
MB-REC-04 68 117 79 37 22 24 49 17 26 31 37 23 8 17 16
MB-REC-07 76 42 114 33 20 27 30 28 36 37 42 15 15 18 26
MB-REC-08 80 52 87 23 31 18 24 22 29 24 30 9 19 26 20
MB-REC-11 193 201 164 57 57 65 92 34 66 74 82 32 29 37 42
MB-REC-12 126 40 144 48 25 44 53 33 44 39 56 27 20 20 23
MB-REC-13 107 50 136 36 31 41 68 51 63 68 86 39 22 40 35
MB-REC-14 206 158 192 78 66 78 126 104 121 125 169 46 54 58 60
MB-REC-15 73 125 77 19 17 19 44 20 25 22 38 13 8 17 12
MB-REC-16 164 56 289 153 70 103 157 102 74 102 155 80 31 63 84
T[T>A]A T[T>A]C T[T>A]G T[T>A]T A[T>C]A A[T>C]C A[T>C]G A[T>C]T C[T>C]A C[T>C]C C[T>C]G C[T>C]T G[T>C]A G[T>C]C G[T>C]G
MB-REC-04 64 34 14 47 88 51 70 75 36 55 53 49 44 40 53
MB-REC-07 39 18 22 55 89 47 53 57 35 59 50 49 59 47 50
MB-REC-08 23 13 12 25 89 36 69 66 41 40 64 46 43 42 44
MB-REC-11 62 56 48 115 105 63 90 124 34 68 56 64 59 44 66
MB-REC-12 41 24 23 68 88 38 43 77 30 36 41 58 43 34 28
MB-REC-13 65 36 26 83 83 44 39 84 54 51 33 53 72 53 44
MB-REC-14 110 69 66 153 160 63 115 159 77 106 91 108 82 64 92
MB-REC-15 46 22 15 37 49 23 39 58 26 21 22 38 25 35 21
MB-REC-16 156 87 84 207 123 57 52 119 80 62 50 104 70 50 41
G[T>C]T T[T>C]A T[T>C]C T[T>C]G T[T>C]T A[T>G]A A[T>G]C A[T>G]G A[T>G]T C[T>G]A C[T>G]C C[T>G]G C[T>G]T G[T>G]A G[T>G]C
MB-REC-04 59 64 60 44 62 21 12 20 35 11 12 20 13 145 70
MB-REC-07 46 53 56 49 85 27 13 18 18 12 6 21 16 33 18
MB-REC-08 62 44 53 49 49 23 14 28 32 5 16 15 27 17 20
MB-REC-11 75 52 61 49 83 20 25 49 49 21 22 29 27 42 35
MB-REC-12 48 54 36 29 68 25 26 35 52 12 16 21 20 33 28
MB-REC-13 92 52 45 30 105 16 9 16 4 19 10 28 16 14 13
MB-REC-14 106 98 99 73 133 55 41 58 90 19 29 34 26 31 36
MB-REC-15 33 27 40 19 45 16 5 17 18 8 7 7 13 5 13
MB-REC-16 72 112 86 41 148 87 42 65 91 27 20 29 25 53 23
G[T>G]G G[T>G]T T[T>G]A T[T>G]C T[T>G]G T[T>G]T
MB-REC-04 411 129 25 15 21 45
MB-REC-07 96 51 24 23 38 52
MB-REC-08 51 49 17 24 21 51
MB-REC-11 181 62 19 32 39 81
MB-REC-12 110 52 26 20 24 40
MB-REC-13 59 24 25 5 24 33
MB-REC-14 78 57 32 38 47 74
MB-REC-15 29 10 16 11 12 31
MB-REC-16 66 36 80 54 45 109
##To create a DF with rows with number of cases (Recurrent) and 96 columns of of the types of single nucleotide subsitution
## This will be done on the cases in Primary_Recurrent_ICGCDF_96.1.csv ,
#These are recurrent cases in data base with no matched primary but matched germline and also recurrent cases
#with matched primary and no germline control. The variants for cases with no germline control were called against primary medullblastoma.
Recurrent_Med<- read.csv("~/Desktop/Data_Analysis/Data_analysis_June _2018/Initial_plan_for_analysis/Primary_recurrent_ICGC_DF_96_1.csv")
######
##Final DF with all recurrent cases with rows as number of cases and 96 columns
## In the following Data Frame all recurrent cases are presnt; the ones with germline control, the varianst were called against
## Germline , the ones with only matched primary cases the variants well called against primary.
Final_recurrant_DF <- read.csv("~/Desktop/Data_Analysis/last MAF files/DF_Sigs_Input_Recurrent.csv")
Final_recurrant_DF <- as.data.frame(Final_recurrant_DF)
View(Final_recurrant_DF)
Packages Used
##MutationalPatterns
##BSgenome.Hsapiens.UCSC.hg19
Final_recurrent_DF1 <- read_csv("~/Desktop/DF-Sigs_Input_Recurrent.csv")
samples <- c("MB-REC-06", "MB-REC-02", "MB-REC-09", "MB-REC-10", "MB-REC-41", "MB-REC-03", "MB-REC-04", "MB-REC-07",
"MB-REC-08", "MB-REC-11", "MB-REC-12", "MB-REC-13", "MB-REC-14", "MB-REC-15", "MB-REC-16", "MB-REC-26",
"MB-REC-40", "MB-REC-45", "MB-REC-44", "MB-REC-46", "MB-REC-24", "MB-REC-43", "MB-REC-32", "MB-REC-39",
"MB-REC-19", "MB-REC-01", "MB-REC-28", "MB-REC-47", "MB-REC-18", "MB-REC-33", "MB-REC-31", "MB-REC-23",
"MB-REC-30", "MB-REC-42", "MB-REC-21", "MB-REC-34", "MB-REC-22", "MB-REC-35", "MB-REC-29", "MB-REC-27")
Final_recurrent_DF1 <- as.data.frame(Final_recurrent_DF1, row.names = samples)
View(Final_recurrent_DF1)
Final_recurrent_DF1<- Final_recurrent_DF1[,c(2:97)]
View(Final_recurrent_DF1)
Final_recurrent_DF1_t <- t(Final_recurrent_DF1)
View(Final_recurrent_DF1_t)
Packages Used
##Packages Used
##MutationalPatterns
##BSgenome.Hsapiens.UCSC.hg19
sp_url <- paste("http://cancer.sanger.ac.uk/cancergenome/assets/","signatures_probabilities.txt", sep = "")
cancer_signatures = read.table(sp_url, sep = "\t", header = TRUE)
# Match the order of the mutation types to MutationalPatterns standard
new_order = match(row.names(Final_recurrent_DF1_t), cancer_signatures$Somatic.Mutation.Type)
# Reorder cancer signatures dataframe
cancer_signatures = cancer_signatures[as.vector(new_order),]
# Add trinucletiode changes names as row.names
row.names(cancer_signatures) = cancer_signatures$Somatic.Mutation.Type
# Keep only 96 contributions of the signatures in matrix
cancer_signatures = as.matrix(cancer_signatures[,4:33])
cos_sim(Final_recurrent_DF1_t[,1], cancer_signatures[,1])
## 0.7438926
cos_sim_samples_signatures = cos_sim_matrix(Final_recurrent_DF1_t, cancer_signatures)
# Plot heatmap with specified signature order
plot_cosine_heatmap(cos_sim_samples_signatures,cluster_rows = TRUE)
##Fit Mutation matrix to the cosmic mutational signature
fit_res <- F, cancer_signatures)
# Select signatures with some contribution
select <- which(rowSums(fit_res$contribution) > 10)
# Plot contribution barplot
plot_contribution(fit_res$contribution[select,],cancer_signatures[,select],coord_flip = FALSE, mode = "absolute")
##
## Further subsetting for comparison puroposes only these the samples that have matched primarya dn germline both, a total of 14 cases with all three samples Germline, primary and recurrent.
DF_Sigs_Input_Recurrent_matched_Primary <- read_csv("~/Desktop/DF-Sigs_Input_Recurrent_matched_Primary.csv")
samples <- c("MB-REC-06", "MB-REC-02", "MB-REC-09", "MB-REC-10","MB-REC-03", "MB-REC-04", "MB-REC-07",
"MB-REC-08", "MB-REC-11", "MB-REC-12", "MB-REC-13", "MB-REC-14", "MB-REC-15", "MB-REC-16")
DF_Sigs_Input_Recurrent_matched_Primary <- as.data.frame(DF_Sigs_Input_Recurrent_matched_Primary, row.names = samples)
View(DF_Sigs_Input_Recurrent_matched_Primary)
DF_Sigs_Input_Recurrent_matched_Primary <- DF_Sigs_Input_Recurrent_matched_Primary[,c(2:97)]
View(DF_Sigs_Input_Recurrent_matched_Primary)
DF_Sigs_Input_Recurrent_matched_Primary_t <- t(DF_Sigs_Input_Recurrent_matched_Primary)
View(DF_Sigs_Input_Recurrent_matched_Primary_t)
sp_url <- paste("http://cancer.sanger.ac.uk/cancergenome/assets/","signatures_probabilities.txt", sep = "")
cancer_signatures = read.table(sp_url, sep = "\t", header = TRUE)
# Match the order of the mutation types to MutationalPatterns standard
new_order = match(row.names(DF_Sigs_Input_Recurrent_matched_Primary_t), cancer_signatures$Somatic.Mutation.Type)
# Reorder cancer signatures dataframe
cancer_signatures = cancer_signatures[as.vector(new_order),]
# Add trinucletiode changes names as row.names
row.names(cancer_signatures) = cancer_signatures$Somatic.Mutation.Type
# Keep only 96 contributions of the signatures in matrix
cancer_signatures = as.matrix(cancer_signatures[,4:33])
cos_sim(DF_Sigs_Input_Recurrent_matched_Primary_t[,1], cancer_signatures[,1])
cos_sim_samples_signatures = cos_sim_matrix(DF_Sigs_Input_Recurrent_matched_Primary_t, cancer_signatures)
# Plot heatmap with specified signature order
plot_cosine_heatmap(cos_sim_samples_signatures,cluster_rows = TRUE)
##Fit Mutation matrix to the cosmic mutational signature
fit_res <- fit_to_signatures(Germline_Primary_sigs_t, cancer_signatures)
# Select signatures with some contribution
select <- which(rowSums(fit_res$contribution) > 10)
# Plot contribution barplot
plot_contribution(fit_res$contribution[select,],cancer_signatures[,select],coord_flip = FALSE, mode = "absolute") | /Recurrent_Signatures.R | no_license | aditibagchi/Comprehensive-analysis-of-mutational-processses-in-Primary-and-recurrent-Medulloblastoma | R | false | false | 18,109 | r | ######
Work Flow working genrating a final Sigs_Input file for recurrent medulloblastoma cases.
#Packages used
maftools::
deconstructSigs::
BSgenome.Hsapiens.UCSC.hg19::
BSgenome::
###
#Cases : MB-REC-02, 03,41,06,09,10 from ICGC
#Variants called against germline.
#Recurrence at mestatic site.
#MAF files were generated by Megan Bowman
Germline_Met_Recur<- read.delim("~/Desktop/Data_Analysis/last MAF files/ICGC_germline_metastatic_reduced_maf_final.txt", header=TRUE)
View(Germline_Met_Recur)
Germline_Met_Recur_Maf <- read.maf(maf = "~/Desktop/Data_Analysis/last MAF files/ICGC_germline_metastatic_reduced_maf_final.txt")
mafSummary(Germline_Met_Recur_Maf)
##$variants.per.sample
##Tumor_Sample_Barcode Variants
1: MB-REC-06 511043
2: MB-REC-09 6293
3: MB-REC-10 4690
4: MB-REC-02 3728
5: MB-REC-41 2181
6: MB-REC-03 1419
#Cases : MB-REC-16, 14,11,07,08,04,13,12,15 from ICGC
#Variants called against germline.
#Recurrence at Primary site.
#This MAF file was generated by Ian Beddows.
Germline_Recur<- read.delim("~/Desktop/Data_Analysis/last MAF files/9_recurrent_germline_samples_GRCH38_crossmapped_to_GRCH37.maf.txt", header=FALSE, comment.char="#")
View(Germline_Recur)
Germline_Recur_Maf <- read.maf(maf = "~/Desktop/Data_Analysis/last MAF files/9_recurrent_germline_samples_GRCH38_crossmapped_to_GRCH37.maf.txt" )
mafSummary(Germline_Recur_Maf)
##$variant.per.sampple
##Tumor_Sample_Barcode Variants
1: MB-REC-16 28931
2: MB-REC-14 11212
3: MB-REC-11 9789
4: MB-REC-07 7300
5: MB-REC-08 6913
6: MB-REC-04 6250
7: MB-REC-13 5689
8: MB-REC-12 5332
9: MB-REC-15 4453
## To create a DF with rows with number of cases (Recurrent) and 96 columns of of the types of single nucleotide subsitution.
##Subset_Met_GermLine_73.csv was created earlier after deleting the 73 variants from the original MAF file that didnot match the context.
Germline_Met_Recur_Sigs_Input_file <- read.csv("~/Desktop/Data_Analysis/last MAF files/SUbset_Mets_Germline_73.csv")
Germline_Recur_Met_Sigs <- mut.to.sigs.input(Germline_Met_Recur_Sigs_Input_file, sample.id = "Sample", chr = "chr", pos = "X",
ref = "ref", alt = "alt", bsg = NULL)
View(Germline_Recur_Met_Sigs)
RecurrentMB <- whichSignatures(tumor.ref = Germline_Recur_Met_Sigs , sample.id = "MB-REC-03",
signatures.ref = signatures.nature2013, associated = c(),
signatures.limit = NA, signature.cutoff = 0.06, contexts.needed = TRUE,
tri.counts.method = "default")
plotSignatures(RecurrentMB03)
makePie(RecurrentMB03, sub = "RecurrentMB03", add.color = NULL)
##To create a DF with rows with number of cases (Recurrent) and 96 columns of of the types of single nucleotide subsitution
## This will be done on the 9 cases in Germline_Recur_Maf
#Create a CSV File with "Sample", "chr", 'pos", "ref", "alt" ; a subset of the maffile.
Germline_Recur_Maf_Subset <- read.csv("~/Desktop/Data_Analysis/last MAF files/Germline_Recur_Maf_Subset.csv")
Germline_Recur_Maf_Subset <- as.data.frame(Germline_Recur_Maf_Subset)
Germline_Met_Recur_Sigs <- mut.to.sigs.input(Germline_Recur_Maf_Subset, sample.id = "sample", chr = "chr", pos = "pos",ref = "ref", alt = "alt", bsg = NULL)
View(Germline_Met_Recur_Sigs)
RecurrentMB16 <- whichSignatures(tumor.ref = Germline_Met_Recur_Sigs , sample.id = "MB-REC-16",
signatures.ref = signatures.nature2013, associated = c(),
signatures.limit = NA, signature.cutoff = 0.06, contexts.needed = TRUE,
tri.counts.method = "default")
plotSignatures(RecurrentMB16)
makePie(RecurrentMB16, sub = "RecurrentMB16", add.color = NULL)
##The DF
A[C>A]A A[C>A]C A[C>A]G A[C>A]T C[C>A]A C[C>A]C C[C>A]G C[C>A]T G[C>A]A G[C>A]C G[C>A]G G[C>A]T T[C>A]A T[C>A]C T[C>A]G
MB-REC-04 115 73 5 36 90 51 19 81 83 43 10 30 90 57 4
MB-REC-07 134 59 3 42 78 59 16 64 122 89 17 88 88 43 12
MB-REC-08 59 32 8 40 51 45 5 53 43 39 6 23 39 34 10
MB-REC-11 192 154 27 123 115 136 21 155 70 82 13 60 141 143 10
MB-REC-12 95 56 11 50 92 60 12 105 38 38 10 37 76 81 5
MB-REC-13 99 74 8 62 122 81 11 146 112 64 15 73 80 97 8
MB-REC-14 195 188 33 138 236 143 20 246 120 127 19 86 145 153 16
MB-REC-15 69 64 11 41 61 56 20 71 49 61 17 28 70 55 21
MB-REC-16 240 137 33 198 235 184 56 268 173 117 29 133 236 129 22
T[C>A]T A[C>G]A A[C>G]C A[C>G]G A[C>G]T C[C>G]A C[C>G]C C[C>G]G C[C>G]T G[C>G]A G[C>G]C G[C>G]G G[C>G]T T[C>G]A T[C>G]C
MB-REC-04 102 40 22 9 24 22 15 12 28 29 25 5 18 32 18
MB-REC-07 109 46 19 11 36 28 31 10 27 54 38 22 29 29 27
MB-REC-08 54 48 41 8 47 24 23 10 20 27 28 8 27 36 40
MB-REC-11 173 57 79 21 51 24 35 10 30 22 37 7 35 29 56
MB-REC-12 73 32 53 8 44 19 28 7 23 23 42 4 38 28 47
MB-REC-13 118 32 23 13 42 38 32 6 41 41 38 17 25 39 33
MB-REC-14 212 75 69 20 71 39 36 13 62 34 33 11 50 60 63
MB-REC-15 85 29 19 13 26 9 18 6 20 15 11 8 12 23 21
MB-REC-16 231 115 45 26 103 48 47 16 38 88 53 16 63 133 60
T[C>G]G T[C>G]T A[C>T]A A[C>T]C A[C>T]G A[C>T]T C[C>T]A C[C>T]C C[C>T]G C[C>T]T G[C>T]A G[C>T]C G[C>T]G G[C>T]T T[C>T]A
MB-REC-04 7 43 96 45 270 74 79 73 132 81 92 73 206 64 68
MB-REC-07 2 37 123 59 120 86 81 80 67 94 90 66 91 103 77
MB-REC-08 11 51 108 55 105 90 86 68 90 68 60 55 103 59 65
MB-REC-11 7 79 239 134 494 151 162 205 312 207 127 152 357 133 165
MB-REC-12 5 84 104 77 93 86 68 127 68 119 61 104 56 92 65
MB-REC-13 9 46 105 83 101 124 62 117 85 124 113 128 122 126 79
MB-REC-14 8 120 229 153 437 175 168 219 238 208 107 149 252 127 133
MB-REC-15 8 21 81 59 334 66 70 156 210 111 65 73 257 54 48
MB-REC-16 12 132 219 119 130 263 152 112 80 234 163 101 111 182 201
T[C>T]C T[C>T]G T[C>T]T A[T>A]A A[T>A]C A[T>A]G A[T>A]T C[T>A]A C[T>A]C C[T>A]G C[T>A]T G[T>A]A G[T>A]C G[T>A]G G[T>A]T
MB-REC-04 68 117 79 37 22 24 49 17 26 31 37 23 8 17 16
MB-REC-07 76 42 114 33 20 27 30 28 36 37 42 15 15 18 26
MB-REC-08 80 52 87 23 31 18 24 22 29 24 30 9 19 26 20
MB-REC-11 193 201 164 57 57 65 92 34 66 74 82 32 29 37 42
MB-REC-12 126 40 144 48 25 44 53 33 44 39 56 27 20 20 23
MB-REC-13 107 50 136 36 31 41 68 51 63 68 86 39 22 40 35
MB-REC-14 206 158 192 78 66 78 126 104 121 125 169 46 54 58 60
MB-REC-15 73 125 77 19 17 19 44 20 25 22 38 13 8 17 12
MB-REC-16 164 56 289 153 70 103 157 102 74 102 155 80 31 63 84
T[T>A]A T[T>A]C T[T>A]G T[T>A]T A[T>C]A A[T>C]C A[T>C]G A[T>C]T C[T>C]A C[T>C]C C[T>C]G C[T>C]T G[T>C]A G[T>C]C G[T>C]G
MB-REC-04 64 34 14 47 88 51 70 75 36 55 53 49 44 40 53
MB-REC-07 39 18 22 55 89 47 53 57 35 59 50 49 59 47 50
MB-REC-08 23 13 12 25 89 36 69 66 41 40 64 46 43 42 44
MB-REC-11 62 56 48 115 105 63 90 124 34 68 56 64 59 44 66
MB-REC-12 41 24 23 68 88 38 43 77 30 36 41 58 43 34 28
MB-REC-13 65 36 26 83 83 44 39 84 54 51 33 53 72 53 44
MB-REC-14 110 69 66 153 160 63 115 159 77 106 91 108 82 64 92
MB-REC-15 46 22 15 37 49 23 39 58 26 21 22 38 25 35 21
MB-REC-16 156 87 84 207 123 57 52 119 80 62 50 104 70 50 41
G[T>C]T T[T>C]A T[T>C]C T[T>C]G T[T>C]T A[T>G]A A[T>G]C A[T>G]G A[T>G]T C[T>G]A C[T>G]C C[T>G]G C[T>G]T G[T>G]A G[T>G]C
MB-REC-04 59 64 60 44 62 21 12 20 35 11 12 20 13 145 70
MB-REC-07 46 53 56 49 85 27 13 18 18 12 6 21 16 33 18
MB-REC-08 62 44 53 49 49 23 14 28 32 5 16 15 27 17 20
MB-REC-11 75 52 61 49 83 20 25 49 49 21 22 29 27 42 35
MB-REC-12 48 54 36 29 68 25 26 35 52 12 16 21 20 33 28
MB-REC-13 92 52 45 30 105 16 9 16 4 19 10 28 16 14 13
MB-REC-14 106 98 99 73 133 55 41 58 90 19 29 34 26 31 36
MB-REC-15 33 27 40 19 45 16 5 17 18 8 7 7 13 5 13
MB-REC-16 72 112 86 41 148 87 42 65 91 27 20 29 25 53 23
G[T>G]G G[T>G]T T[T>G]A T[T>G]C T[T>G]G T[T>G]T
MB-REC-04 411 129 25 15 21 45
MB-REC-07 96 51 24 23 38 52
MB-REC-08 51 49 17 24 21 51
MB-REC-11 181 62 19 32 39 81
MB-REC-12 110 52 26 20 24 40
MB-REC-13 59 24 25 5 24 33
MB-REC-14 78 57 32 38 47 74
MB-REC-15 29 10 16 11 12 31
MB-REC-16 66 36 80 54 45 109
##To create a DF with rows with number of cases (Recurrent) and 96 columns of of the types of single nucleotide subsitution
## This will be done on the cases in Primary_Recurrent_ICGCDF_96.1.csv ,
#These are recurrent cases in data base with no matched primary but matched germline and also recurrent cases
#with matched primary and no germline control. The variants for cases with no germline control were called against primary medullblastoma.
Recurrent_Med<- read.csv("~/Desktop/Data_Analysis/Data_analysis_June _2018/Initial_plan_for_analysis/Primary_recurrent_ICGC_DF_96_1.csv")
######
##Final DF with all recurrent cases with rows as number of cases and 96 columns
## In the following Data Frame all recurrent cases are presnt; the ones with germline control, the varianst were called against
## Germline , the ones with only matched primary cases the variants well called against primary.
Final_recurrant_DF <- read.csv("~/Desktop/Data_Analysis/last MAF files/DF_Sigs_Input_Recurrent.csv")
Final_recurrant_DF <- as.data.frame(Final_recurrant_DF)
View(Final_recurrant_DF)
Packages Used
##MutationalPatterns
##BSgenome.Hsapiens.UCSC.hg19
Final_recurrent_DF1 <- read_csv("~/Desktop/DF-Sigs_Input_Recurrent.csv")
samples <- c("MB-REC-06", "MB-REC-02", "MB-REC-09", "MB-REC-10", "MB-REC-41", "MB-REC-03", "MB-REC-04", "MB-REC-07",
"MB-REC-08", "MB-REC-11", "MB-REC-12", "MB-REC-13", "MB-REC-14", "MB-REC-15", "MB-REC-16", "MB-REC-26",
"MB-REC-40", "MB-REC-45", "MB-REC-44", "MB-REC-46", "MB-REC-24", "MB-REC-43", "MB-REC-32", "MB-REC-39",
"MB-REC-19", "MB-REC-01", "MB-REC-28", "MB-REC-47", "MB-REC-18", "MB-REC-33", "MB-REC-31", "MB-REC-23",
"MB-REC-30", "MB-REC-42", "MB-REC-21", "MB-REC-34", "MB-REC-22", "MB-REC-35", "MB-REC-29", "MB-REC-27")
Final_recurrent_DF1 <- as.data.frame(Final_recurrent_DF1, row.names = samples)
View(Final_recurrent_DF1)
Final_recurrent_DF1<- Final_recurrent_DF1[,c(2:97)]
View(Final_recurrent_DF1)
Final_recurrent_DF1_t <- t(Final_recurrent_DF1)
View(Final_recurrent_DF1_t)
Packages Used
##Packages Used
##MutationalPatterns
##BSgenome.Hsapiens.UCSC.hg19
sp_url <- paste("http://cancer.sanger.ac.uk/cancergenome/assets/","signatures_probabilities.txt", sep = "")
cancer_signatures = read.table(sp_url, sep = "\t", header = TRUE)
# Match the order of the mutation types to MutationalPatterns standard
new_order = match(row.names(Final_recurrent_DF1_t), cancer_signatures$Somatic.Mutation.Type)
# Reorder cancer signatures dataframe
cancer_signatures = cancer_signatures[as.vector(new_order),]
# Add trinucletiode changes names as row.names
row.names(cancer_signatures) = cancer_signatures$Somatic.Mutation.Type
# Keep only 96 contributions of the signatures in matrix
cancer_signatures = as.matrix(cancer_signatures[,4:33])
cos_sim(Final_recurrent_DF1_t[,1], cancer_signatures[,1])
## 0.7438926
cos_sim_samples_signatures = cos_sim_matrix(Final_recurrent_DF1_t, cancer_signatures)
# Plot heatmap with specified signature order
plot_cosine_heatmap(cos_sim_samples_signatures,cluster_rows = TRUE)
##Fit Mutation matrix to the cosmic mutational signature
fit_res <- F, cancer_signatures)
# Select signatures with some contribution
select <- which(rowSums(fit_res$contribution) > 10)
# Plot contribution barplot
plot_contribution(fit_res$contribution[select,],cancer_signatures[,select],coord_flip = FALSE, mode = "absolute")
##
## Further subsetting for comparison puroposes only these the samples that have matched primarya dn germline both, a total of 14 cases with all three samples Germline, primary and recurrent.
DF_Sigs_Input_Recurrent_matched_Primary <- read_csv("~/Desktop/DF-Sigs_Input_Recurrent_matched_Primary.csv")
samples <- c("MB-REC-06", "MB-REC-02", "MB-REC-09", "MB-REC-10","MB-REC-03", "MB-REC-04", "MB-REC-07",
"MB-REC-08", "MB-REC-11", "MB-REC-12", "MB-REC-13", "MB-REC-14", "MB-REC-15", "MB-REC-16")
DF_Sigs_Input_Recurrent_matched_Primary <- as.data.frame(DF_Sigs_Input_Recurrent_matched_Primary, row.names = samples)
View(DF_Sigs_Input_Recurrent_matched_Primary)
DF_Sigs_Input_Recurrent_matched_Primary <- DF_Sigs_Input_Recurrent_matched_Primary[,c(2:97)]
View(DF_Sigs_Input_Recurrent_matched_Primary)
DF_Sigs_Input_Recurrent_matched_Primary_t <- t(DF_Sigs_Input_Recurrent_matched_Primary)
View(DF_Sigs_Input_Recurrent_matched_Primary_t)
sp_url <- paste("http://cancer.sanger.ac.uk/cancergenome/assets/","signatures_probabilities.txt", sep = "")
cancer_signatures = read.table(sp_url, sep = "\t", header = TRUE)
# Match the order of the mutation types to MutationalPatterns standard
new_order = match(row.names(DF_Sigs_Input_Recurrent_matched_Primary_t), cancer_signatures$Somatic.Mutation.Type)
# Reorder cancer signatures dataframe
cancer_signatures = cancer_signatures[as.vector(new_order),]
# Add trinucletiode changes names as row.names
row.names(cancer_signatures) = cancer_signatures$Somatic.Mutation.Type
# Keep only 96 contributions of the signatures in matrix
cancer_signatures = as.matrix(cancer_signatures[,4:33])
cos_sim(DF_Sigs_Input_Recurrent_matched_Primary_t[,1], cancer_signatures[,1])
cos_sim_samples_signatures = cos_sim_matrix(DF_Sigs_Input_Recurrent_matched_Primary_t, cancer_signatures)
# Plot heatmap with specified signature order
plot_cosine_heatmap(cos_sim_samples_signatures,cluster_rows = TRUE)
##Fit Mutation matrix to the cosmic mutational signature
fit_res <- fit_to_signatures(Germline_Primary_sigs_t, cancer_signatures)
# Select signatures with some contribution
select <- which(rowSums(fit_res$contribution) > 10)
# Plot contribution barplot
plot_contribution(fit_res$contribution[select,],cancer_signatures[,select],coord_flip = FALSE, mode = "absolute") |
##########################################################################################
# RANDOM FORESTS PREDICTIONS
##########################################################################################
require(randomForest)
##########################################################################################
for (j in 1:3) {
nsp <- ncol(y_valid[[j]])
nsites <- nrow(y_valid[[j]])
ncovar<-(ncol(x_valid[[1]])-1)/2
Xv <- x_valid[[j]][,-1]
Xv <- Xv[,1:ncovar]
rf1_PAs <- array(NA, dim=list(nsites,nsp,REPs))
isNULL <- rep(FALSE, times = nsp)
for (k in 1:nsp) {
rff1<-NULL
#load(file=paste(FD,set_no,"/rfs/rf_",j,"_sp",k,"_",dataN[sz],".RData",sep=""))
load(file=file.path(FD2,set_no,paste("rfs/rf1_",j,"_sp",k,"_",dataN[sz],".RData",sep="")))
for (n in 1:REPs) {
Probs<-NULL
if (is.null(rff1)) {
Probs <- matrix(rep(mean(y_train[[j]][,k]),times=nsites),ncol=1)
isNULL[i] <- TRUE
} else {
class(rff1)<-"randomForest"
#Probs<-predict(rff1,newX=Xv,type="prob")
Probs<-predict(rff1,newX=Xv)
}
Probs[which(Probs<0)]<-0
Probs[which(Probs>1)]<-1
#rf1_PAs[,k,n] <- matrix(rbinom(Probs,1,Probs),ncol=ncol(Probs))
rf1_PAs[,k,n] <- matrix(rbinom(Probs,1,Probs),ncol=1)
}
}
save(isNULL, file = file.path(PD2,
set_no,
paste("rf1_isNULL_",j,"_",dataN[sz],".RData",sep="")))
save(rf1_PAs, file=file.path(PD2,
set_no,
paste("rf1_PAs_",j,"_",dataN[sz],".RData",sep="")))
rm(rff1)
rm(rf1_PAs)
gc()
}
########################################################################################## | /PREDICT/predict.rf.r | no_license | davan690/SDM-comparison | R | false | false | 1,757 | r | ##########################################################################################
# RANDOM FORESTS PREDICTIONS
##########################################################################################
require(randomForest)
##########################################################################################
for (j in 1:3) {
nsp <- ncol(y_valid[[j]])
nsites <- nrow(y_valid[[j]])
ncovar<-(ncol(x_valid[[1]])-1)/2
Xv <- x_valid[[j]][,-1]
Xv <- Xv[,1:ncovar]
rf1_PAs <- array(NA, dim=list(nsites,nsp,REPs))
isNULL <- rep(FALSE, times = nsp)
for (k in 1:nsp) {
rff1<-NULL
#load(file=paste(FD,set_no,"/rfs/rf_",j,"_sp",k,"_",dataN[sz],".RData",sep=""))
load(file=file.path(FD2,set_no,paste("rfs/rf1_",j,"_sp",k,"_",dataN[sz],".RData",sep="")))
for (n in 1:REPs) {
Probs<-NULL
if (is.null(rff1)) {
Probs <- matrix(rep(mean(y_train[[j]][,k]),times=nsites),ncol=1)
isNULL[i] <- TRUE
} else {
class(rff1)<-"randomForest"
#Probs<-predict(rff1,newX=Xv,type="prob")
Probs<-predict(rff1,newX=Xv)
}
Probs[which(Probs<0)]<-0
Probs[which(Probs>1)]<-1
#rf1_PAs[,k,n] <- matrix(rbinom(Probs,1,Probs),ncol=ncol(Probs))
rf1_PAs[,k,n] <- matrix(rbinom(Probs,1,Probs),ncol=1)
}
}
save(isNULL, file = file.path(PD2,
set_no,
paste("rf1_isNULL_",j,"_",dataN[sz],".RData",sep="")))
save(rf1_PAs, file=file.path(PD2,
set_no,
paste("rf1_PAs_",j,"_",dataN[sz],".RData",sep="")))
rm(rff1)
rm(rf1_PAs)
gc()
}
########################################################################################## |
#Title: Q-Learning - ATIVIDIDADE 22/JUL/21 - ACA CIn/UFPE
#Author: Jair Paulino de Sales (BASEADO NA SOLUÇAO DE JULIANA LOUREIRO)
# Limpa o ambiente R
rm(list=ls()); graphics.off()
# Chama as funções auxiliares implementadas
source("Auxiliar.R")
# Configura os parâmetros iniciais
alpha = 0.5; gamma = 0.8
# Inicializa a matriz Q
q_mt = data.frame(matrix(0,6,4)); q_mt[6,] = 10
names(q_mt) = c('UP', 'DOWN', 'LEFT', 'RIGHT')
R = c(-1, 10, -10)
names(R) <- c("Outro", "6", "Parede")
# Matriz de ação-estado
matrizResultado_df = data.frame(UP = c("2", "3", "Parede", "5", "6", "Parede"),
DOWN = c("Parede", "1", "2", "Parede", "4", "5"),
LEFT = c("Parede", "Parede", "Parede", "1", "2", "3"),
RIGHT = c("4", "5", "6", "Parede", "Parede", "Parede"))
matrizResultado_df
print("Matriz Q"); print(q_mt)
# Estado inicial - 1 UUUR
seq_init = c("UP", "UP", "UP", "RIGHT"); state = 1
print("Resultado (Estado Inicial 1) :")
# Executa função q_learning para a sequencia de ações informada
q_matrix_T1 = q_learning(state, seq_init,
matrizResultado_df,
R, q_mt, alpha, gamma)
# Estado inicial - 5 LLUR
seq_init_2 = c("LEFT", "LEFT", "UP", "RIGHT"); state = 5
# Executa função q_learning para a sequencia de ações informada
# Neste cenário já parte da matrix q resultante do aprendizado anterior
print("Resultado (Estado Inicial 5) :")
q_matrix_2 = q_learning(state, seq_init_2,
matrizResultado_df,
R, q_matrix_T1, alpha, gamma)
| /Problem_02/main.R | no_license | jairpaulino/ACA_CIn_20211 | R | false | false | 1,644 | r | #Title: Q-Learning - ATIVIDIDADE 22/JUL/21 - ACA CIn/UFPE
#Author: Jair Paulino de Sales (BASEADO NA SOLUÇAO DE JULIANA LOUREIRO)
# Limpa o ambiente R
rm(list=ls()); graphics.off()
# Chama as funções auxiliares implementadas
source("Auxiliar.R")
# Configura os parâmetros iniciais
alpha = 0.5; gamma = 0.8
# Inicializa a matriz Q
q_mt = data.frame(matrix(0,6,4)); q_mt[6,] = 10
names(q_mt) = c('UP', 'DOWN', 'LEFT', 'RIGHT')
R = c(-1, 10, -10)
names(R) <- c("Outro", "6", "Parede")
# Matriz de ação-estado
matrizResultado_df = data.frame(UP = c("2", "3", "Parede", "5", "6", "Parede"),
DOWN = c("Parede", "1", "2", "Parede", "4", "5"),
LEFT = c("Parede", "Parede", "Parede", "1", "2", "3"),
RIGHT = c("4", "5", "6", "Parede", "Parede", "Parede"))
matrizResultado_df
print("Matriz Q"); print(q_mt)
# Estado inicial - 1 UUUR
seq_init = c("UP", "UP", "UP", "RIGHT"); state = 1
print("Resultado (Estado Inicial 1) :")
# Executa função q_learning para a sequencia de ações informada
q_matrix_T1 = q_learning(state, seq_init,
matrizResultado_df,
R, q_mt, alpha, gamma)
# Estado inicial - 5 LLUR
seq_init_2 = c("LEFT", "LEFT", "UP", "RIGHT"); state = 5
# Executa função q_learning para a sequencia de ações informada
# Neste cenário já parte da matrix q resultante do aprendizado anterior
print("Resultado (Estado Inicial 5) :")
q_matrix_2 = q_learning(state, seq_init_2,
matrizResultado_df,
R, q_matrix_T1, alpha, gamma)
|
library(jomo) # imputation package
library(fastDummies) #to create dummy columns for treatment
setwd("C:/Users/mike/Desktop") #change directory
data <- read.csv("data_for_new_imputation.csv")
covariates <- c("AGE", "SEX", "HAMD_3", "HAMD_4", "HAMD_6", "HAMD_10", "HAMD_11", "HAMD_13", "HAMD_17", "HAMD_BASELINE",
"AE_CATEGORY_ABDOMINAL.PAIN.DISCOMFORT", "AE_CATEGORY_FATIGUE", "AE_CATEGORY_HEADACHE", "AE_CATEGORY_NAUSEA",
"AE_CATEGORY_SEDATION.SOMNOLENCE", "AE_CATEGORY_SEXUAL.DYSFUNCTION",
paste0("HAMD_WEEK_", 1:10))
# Merge two studies
data$STUDYID[data$STUDYID %in% c("29060/073", "29060/059")] <- "29060/059_073"
# Change treatment to dummy variables
data <- dummy_cols(data, select_columns = "TREATMENT_GROUP", remove_selected_columns = TRUE)
covariates <- c(covariates, grep("TREATMENT_GROUP", colnames(data), value = TRUE))
# Convert cluster variable STUDYID to integer
newdata <- data[, c("STUDYID", covariates)]
newdata$STUDYID <- as.numeric(as.factor(newdata$STUDYID))
newdata[, covariates] <- lapply(newdata[, covariates], as.numeric)
# The imputation model requires an intercept variable (simply a column of 1's)
newdata$cons <- 1
y_imputation <- newdata[, c(paste0("HAMD_WEEK_", 1:10), "HAMD_3", "HAMD_4", "HAMD_6", "HAMD_10", "HAMD_11", "HAMD_13", "HAMD_17")]
X_imputation <- newdata[, c("cons", "AGE", "SEX", "HAMD_BASELINE", "AE_CATEGORY_ABDOMINAL.PAIN.DISCOMFORT", "AE_CATEGORY_FATIGUE", "AE_CATEGORY_HEADACHE", "AE_CATEGORY_NAUSEA", "AE_CATEGORY_SEDATION.SOMNOLENCE", "AE_CATEGORY_SEXUAL.DYSFUNCTION",
grep("TREATMENT_GROUP", colnames(data), value = TRUE)
)]
clus <- newdata$STUDYID
imp <- jomo(Y = y_imputation, X = X_imputation, clus = clus, meth = "common", nburn = 1000, nbetween = 1000, nimp = 5)
#save(imp, file = "oxford-imputations.RData")
load("oxford-imputations.RData")
library(mitools)
#imp.list <- imputationList(split(imp, imp$Imputation)[-1])
imp.list <- imputationList(split(imp, imp$Imputation))
View(imp.list$imputations$`0`) #original data
View(imp.list$imputations$`1`) #imputed dataset 1
| /oxford/imputation code jomo.R | no_license | MikeJSeo/phd | R | false | false | 2,146 | r | library(jomo) # imputation package
library(fastDummies) #to create dummy columns for treatment
setwd("C:/Users/mike/Desktop") #change directory
data <- read.csv("data_for_new_imputation.csv")
covariates <- c("AGE", "SEX", "HAMD_3", "HAMD_4", "HAMD_6", "HAMD_10", "HAMD_11", "HAMD_13", "HAMD_17", "HAMD_BASELINE",
"AE_CATEGORY_ABDOMINAL.PAIN.DISCOMFORT", "AE_CATEGORY_FATIGUE", "AE_CATEGORY_HEADACHE", "AE_CATEGORY_NAUSEA",
"AE_CATEGORY_SEDATION.SOMNOLENCE", "AE_CATEGORY_SEXUAL.DYSFUNCTION",
paste0("HAMD_WEEK_", 1:10))
# Merge two studies
data$STUDYID[data$STUDYID %in% c("29060/073", "29060/059")] <- "29060/059_073"
# Change treatment to dummy variables
data <- dummy_cols(data, select_columns = "TREATMENT_GROUP", remove_selected_columns = TRUE)
covariates <- c(covariates, grep("TREATMENT_GROUP", colnames(data), value = TRUE))
# Convert cluster variable STUDYID to integer
newdata <- data[, c("STUDYID", covariates)]
newdata$STUDYID <- as.numeric(as.factor(newdata$STUDYID))
newdata[, covariates] <- lapply(newdata[, covariates], as.numeric)
# The imputation model requires an intercept variable (simply a column of 1's)
newdata$cons <- 1
y_imputation <- newdata[, c(paste0("HAMD_WEEK_", 1:10), "HAMD_3", "HAMD_4", "HAMD_6", "HAMD_10", "HAMD_11", "HAMD_13", "HAMD_17")]
X_imputation <- newdata[, c("cons", "AGE", "SEX", "HAMD_BASELINE", "AE_CATEGORY_ABDOMINAL.PAIN.DISCOMFORT", "AE_CATEGORY_FATIGUE", "AE_CATEGORY_HEADACHE", "AE_CATEGORY_NAUSEA", "AE_CATEGORY_SEDATION.SOMNOLENCE", "AE_CATEGORY_SEXUAL.DYSFUNCTION",
grep("TREATMENT_GROUP", colnames(data), value = TRUE)
)]
clus <- newdata$STUDYID
imp <- jomo(Y = y_imputation, X = X_imputation, clus = clus, meth = "common", nburn = 1000, nbetween = 1000, nimp = 5)
#save(imp, file = "oxford-imputations.RData")
load("oxford-imputations.RData")
library(mitools)
#imp.list <- imputationList(split(imp, imp$Imputation)[-1])
imp.list <- imputationList(split(imp, imp$Imputation))
View(imp.list$imputations$`0`) #original data
View(imp.list$imputations$`1`) #imputed dataset 1
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/gsw.R
\name{gsw_internal_energy}
\alias{gsw_internal_energy}
\title{Specific Internal Energy of Seawater (75-term equation)}
\usage{
gsw_internal_energy(SA, CT, p)
}
\arguments{
\item{SA}{Absolute Salinity [ g/kg ]}
\item{CT}{Conservative Temperature [ degC ]}
\item{p}{sea pressure [dbar], i.e. absolute pressure [dbar] minus 10.1325 dbar}
}
\value{
specific internal energy [ J/kg ]
}
\description{
Specific Internal Energy of Seawater (75-term equation)
}
\section{Implementation Note}{
This R function uses a wrapper to a C function contained within the GSW-C
system as updated 2021-12-28 at \url{https://github.com/TEOS-10/GSW-C} with
git commit `98f0fd40dd9ceb0ba82c9d47ac750e935a7d0459`.
The C function uses data from the \code{library/gsw_data_v3_0.mat}
file provided in the GSW-Matlab source code, version 3.06-11.
Unfortunately, this version of the mat file is no longer displayed on the
TEOS-10.org website. Therefore, in the interests of making GSW-R be
self-contained, a copy was downloaded from
\url{http://www.teos-10.org/software/gsw_matlab_v3_06_11.zip} on 2022-05-25,
the .mat file was stored in the developer/create_data directory of
\url{https://github.com/TEOS-10/GSW-R}, and then the dataset used in GSW-R
was created based on that .mat file.
Please consult \url{http://www.teos-10.org} to learn more about the various
TEOS-10 software systems.
}
\examples{
SA <- c(34.7118, 34.8915, 35.0256, 34.8472, 34.7366, 34.7324)
CT <- c(28.7856, 28.4329, 22.8103, 10.2600, 6.8863, 4.4036)
p <- c( 10, 50, 125, 250, 600, 1000)
e <- gsw_internal_energy(SA, CT, p)
stopifnot(all.equal(e/1e5, c(1.148091576956162, 1.134013145527675, 0.909571141498779,
0.408593072177020, 0.273985276460357, 0.175019409258405)))
}
\references{
\url{http://www.teos-10.org/pubs/gsw/html/gsw_internal_energy.html}
}
| /man/gsw_internal_energy.Rd | no_license | cran/gsw | R | false | true | 1,947 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/gsw.R
\name{gsw_internal_energy}
\alias{gsw_internal_energy}
\title{Specific Internal Energy of Seawater (75-term equation)}
\usage{
gsw_internal_energy(SA, CT, p)
}
\arguments{
\item{SA}{Absolute Salinity [ g/kg ]}
\item{CT}{Conservative Temperature [ degC ]}
\item{p}{sea pressure [dbar], i.e. absolute pressure [dbar] minus 10.1325 dbar}
}
\value{
specific internal energy [ J/kg ]
}
\description{
Specific Internal Energy of Seawater (75-term equation)
}
\section{Implementation Note}{
This R function uses a wrapper to a C function contained within the GSW-C
system as updated 2021-12-28 at \url{https://github.com/TEOS-10/GSW-C} with
git commit `98f0fd40dd9ceb0ba82c9d47ac750e935a7d0459`.
The C function uses data from the \code{library/gsw_data_v3_0.mat}
file provided in the GSW-Matlab source code, version 3.06-11.
Unfortunately, this version of the mat file is no longer displayed on the
TEOS-10.org website. Therefore, in the interests of making GSW-R be
self-contained, a copy was downloaded from
\url{http://www.teos-10.org/software/gsw_matlab_v3_06_11.zip} on 2022-05-25,
the .mat file was stored in the developer/create_data directory of
\url{https://github.com/TEOS-10/GSW-R}, and then the dataset used in GSW-R
was created based on that .mat file.
Please consult \url{http://www.teos-10.org} to learn more about the various
TEOS-10 software systems.
}
\examples{
SA <- c(34.7118, 34.8915, 35.0256, 34.8472, 34.7366, 34.7324)
CT <- c(28.7856, 28.4329, 22.8103, 10.2600, 6.8863, 4.4036)
p <- c( 10, 50, 125, 250, 600, 1000)
e <- gsw_internal_energy(SA, CT, p)
stopifnot(all.equal(e/1e5, c(1.148091576956162, 1.134013145527675, 0.909571141498779,
0.408593072177020, 0.273985276460357, 0.175019409258405)))
}
\references{
\url{http://www.teos-10.org/pubs/gsw/html/gsw_internal_energy.html}
}
|
svm_kde_dopar <- function(data, q, block, test, mean_mdl, variance_mdl){
if(nrow(data) < block + test) stop("Number of rows in 'data' is less than block + test")
source("C:/Users/Marius/Desktop/Simulation/SVRGARCHKDE_Functions/Source_File/Source_SVRGARCHKDE.R")
library(doParallel)
library(quantmod)
allData <- data
test_n <- test
block_size <- block
loop_start <- nrow(allData) - test_n
loop_end <- nrow(allData) - 1
results <- data.frame(Mean = numeric(),
Upper = numeric(),
Lower = numeric(),
Vola = numeric())
cl <- makeCluster(4)
registerDoParallel(cl)
results <- foreach(i = loop_start:loop_end, .combine = "rbind") %dopar% {
source("C:/Users/Marius/Desktop/Simulation/SVRGARCHKDE_Functions/Source_File/Source_SVRGARCHKDE.R")
library(quantmod)
library(e1071)
library(zoo)
x <- allData[(i-block_size+1):i,-1]
y <- allData[(i-block_size+1):i,1]
if(mean_mdl == "KDE" | variance_mdl == "KDE"){
KDE_VaR(y, q, kernel = "gaussian")
}else{
svm_kde(x = x, y = y, q = q, mean_mdl = mean_mdl, variance.mdl = variance_mdl, kernel = "gaussian")
}
}
stopCluster(cl)
results$Vola <- na.locf(results$Vola)
results <- plotResults(results, allData, test_n, q)
return(results)
}
svm_kde <- function(x, y, q, mean_mdl, variance.mdl, kernel){
#############################################################################
# 1. Fit mean model
#############################################################################
# Set parameters
svm_mean_eps <- mean_mdl$eps
svm_mean_cost <- mean_mdl$cost
sigma <- mean_mdl$sigma
svm_mean_gamma <- 1/(2*sigma^2)
# SVM for mean
svm_mean <- svm(x = x, y = y, type = "eps-regression", kernel = "radial",
gamma = svm_mean_gamma,
cost = svm_mean_cost,
epsilon = svm_mean_eps)
# Get fitted values and residual (format as xts for lagging in variance fitting)
mean <- xts(x = svm_mean$fitted, order.by = index(y))
eps <- xts(x = svm_mean$residuals, order.by = index(y))
# Prediction of next periods unseen return
mean_pred <- predict(svm_mean, newdata = y[nrow(y)])
#############################################################################
# 2. Fit variance model
#############################################################################
# Set paramters
svm_var_eps <- quantile(scale(eps)^2, variance.mdl$eps_quantile)
svm_var_cost <- variance.mdl$cost
sigma <- variance.mdl$sigma
svm_var_gamma <- 1/(2*sigma^2)
# Get data
u <- na.omit(cbind(eps, lag(eps)))^2
# Estimate model
svm_var <- svm_variance(x = u[,-1], y = u[,1], m = variance.mdl,
gamma = svm_var_gamma,
cost = svm_var_cost,
epsilon = svm_var_eps)
# Get fitted variances to standardize residuals
if(variance.mdl$model == "AR") fcast_vola <- svm_var$fitted
if(variance.mdl$model == "ARMA") fcast_vola <- svm_var$model$fitted
# Replace negativ variances by last positiv value
fcast_vola[fcast_vola<=0] <- NA
fcast_vola <- na.locf(fcast_vola)
fcast_vola[1] <- ifelse(is.na(fcast_vola[1]), u[1,2], fcast_vola[1])
# Prediction of next periods unseen variance
if(variance.mdl$model == "AR") vola_new_dat <- u[nrow(u),1]
if(variance.mdl$model == "ARMA") vola_new_dat <- cbind(u[nrow(u),1], svm_var$lagRes[length(svm_var$lagRes)])
if(variance.mdl$model == "AR") vola_pred <- predict(svm_var, newdata = vola_new_dat)
if(variance.mdl$model == "ARMA") vola_pred <- predict(svm_var$model, newdata = vola_new_dat)
#############################################################################
# 3. Compute quantiles of scaled standardized residuals
#############################################################################
# Standardize and scale residuals
if(variance.mdl$model == "AR") u_sc <- eps[-1]/sqrt(fcast_vola)
if(variance.mdl$model == "ARMA") u_sc <- eps[-(1:2)]/sqrt(fcast_vola)
u_sc <- scale(u_sc)
# Compute quantiles of scaled standardized residuals
q_upper <- QKDE(q, c(0, max(u_sc)*1.5), data = u_sc, kernel = kernel)
q_lower <- -QKDE(q, c(0, max(-u_sc)*1.5), data = -u_sc, kernel = kernel)
#############################################################################
# 4. Collect results
#############################################################################
# Specify data frame for storing results
results <- data.frame(matrix(NA, nrow = 1, ncol = 4))
names(results) <- c("Mean", "Upper", "Lower", "Vola")
# Save results in data frame
results$Mean <- mean_pred
results$Upper <- q_upper
results$Lower <- q_lower
results$Vola <- ifelse(vola_pred <= 0, u[nrow(u),2], sqrt(vola_pred))
return(results)
}
###############################################################################
# Function for variance estimation
svm_variance <- function(x, y, m, gamma, cost, epsilon){
if(m == "AR"){
model <- svm(x = x, y = y, scale = TRUE,
type = "eps-regression", kernel = "radial",
gamma = gamma, cost = cost, epsilon = epsilon)
result <- model
}
if(m == "ARMA"){
rnn_v1 <- svm(x = x, y = y, scale = TRUE,
type = "eps-regression", kernel = "radial",
gamma = gamma, cost = cost, epsilon = epsilon)
w <- xts(x = rnn_v1$residuals, order.by = index(y))
garch_input <- na.omit(cbind(y, x, lag(w)))
model <- svm(x = garch_input[,2:3], y = garch_input[,1], scale = TRUE,
type = "eps-regression", kernel = "radial",
gamma = gamma, cost = cost, epsilon = epsilon)
result <- list(model = model, lagRes = w)
}
return(result)
}
###############################################################################
# Mean model
svm_kde_mean <- function(x, y, mean_mdl){
#############################################################################
# 1. Fit mean model
#############################################################################
# Set parameters
svm_mean_eps <- mean_mdl$eps
svm_mean_cost <- mean_mdl$cost
sigma <- mean_mdl$sigma
svm_mean_gamma <- 1/(2*sigma^2)
# SVM for mean
svm_mean <- svm(x = x, y = y, type = "eps-regression", kernel = "radial",
gamma = svm_mean_gamma,
cost = svm_mean_cost,
epsilon = svm_mean_eps)
# Get fitted values and residual (format as xts for lagging in variance fitting)
mean <- xts(x = svm_mean$fitted, order.by = index(y))
eps <- xts(x = svm_mean$residuals, order.by = index(y))
# Prediction of next periods unseen return
mean_pred <- predict(svm_mean, newdata = y[nrow(y)])
return(mean_pred)
}
###############################################################################
# Mean model parallelized
svm_kde_mean_dopar <- function(data, block, test, mean_mdl){
if(nrow(data) < block + test) stop("Number of rows in 'data' is less than block + test")
source("C:/Users/Marius/Desktop/Simulation/SVRGARCHKDE_Functions/Source_File/Source_SVRGARCHKDE.R")
library(doParallel)
library(quantmod)
allData <- data
test_n <- test
block_size <- block
loop_start <- nrow(allData) - test_n
loop_end <- nrow(allData) - 1
results <- data.frame(Mean = numeric(),
Upper = numeric(),
Lower = numeric(),
Vola = numeric())
cl <- makeCluster(4)
registerDoParallel(cl)
results <- foreach(i = loop_start:loop_end, .combine = "rbind") %dopar% {
source("C:/Users/Marius/Desktop/Simulation/SVRGARCHKDE_Functions/Source_File/Source_SVRGARCHKDE.R")
library(quantmod)
library(e1071)
library(zoo)
x <- allData[(i-block_size+1):i,-1]
y <- allData[(i-block_size+1):i,1]
mean_mdl <- mean_mdl
svm_kde_mean(x = x, y = y, mean_mdl = mean_mdl)
}
stopCluster(cl)
real <- data[(nrow(data) - test + 1):nrow(data),1]
pred <- xts(results, order.by = index(real))
mse <- sum((coredata(real) - coredata(pred))^2)/nrow(real)
results <- mse
return(results)
}
###############################################################################
# Function for plotting results and analysis
plotResults <- function(results, allData, test_n, q){
results$True <- allData[(nrow(allData) - test_n + 1):nrow(allData),1]
#Analyze Results
results$FCast_Upper <- results$Mean + results$Upper*results$Vola
results$FCast_Lower <- results$Mean + results$Lower*results$Vola
prop_upper <- sum(results$FCast_Upper < results$True)/nrow(results) #
prop_lower <- sum(results$FCast_Lower > results$True)/nrow(results) #Downside risk: if greater 5% -> BAD
#Plot in-sample results
org <- as.numeric(results$True)
fcast_upper <- results$FCast_Upper
fcast_lower <- results$FCast_Lower
ylim_max <- max(abs(c(org, fcast_upper, fcast_lower)))
ylim_min <- -ylim_max
head <- paste0(q*100, "% and ", (1-q)*100, "% VaR-Forecast")
plot(results$True, type = "p", ylim = c(ylim_min, ylim_max),
ylab = "Return in Percent", main = head)
points(results$True, col = "green")
lines(xts(x = fcast_upper, order.by = index(results$True)), col = "red", lwd = 2)
lines(xts(x = fcast_lower, order.by = index(results$True)), col = "red", lwd = 2)
# plot(org, type = "p", col = "green", lwd = 1, ylim = c(ylim_min, ylim_max), ylab = "Value")
# lines(fcast_upper, col = "red", lwd = 2)
# lines(fcast_lower, col = "red", lwd = 2)
errors <- data.frame(Index = 1:length(org), Real = org)
out <- errors$Real > fcast_upper | errors$Real < fcast_lower
points(errors$Index[out], errors$Real[out], col = "blue", pch = 16)
#print(prop_upper)
#print(prop_lower)
prop <- data.frame(prop_upper, prop_lower)
results <- list(Data = results,
Empirical_Coverage = prop)
return(results)
}
###############################################################################
# VaR using kernel density estimation
KDE_VaR <- function(x, q, kernel){
#############################################################################
# 1. Estimate quantiles of data
#############################################################################
q_upper <- QKDE(q, c(0, max(x)*1.5), data = x, kernel = kernel)
q_lower <- -QKDE(q, c(0, max(-x)*1.5), data = -x, kernel = kernel)
#############################################################################
# 2. Collect results
#############################################################################
# Specify data frame for storing results
results <- data.frame(matrix(NA, nrow = 1, ncol = 4))
names(results) <- c("Mean", "Upper", "Lower", "Vola")
# Save results in data frame
results$Mean <- 0
results$Upper <- q_upper
results$Lower <- q_lower
results$Vola <- 1
return(results)
}
| /SVRGARCHKDE_Functions/Dev/Archive/SVM_KDE_Functions_V5.R | no_license | Marius239/SVR_GARCH_KDE | R | false | false | 11,972 | r | svm_kde_dopar <- function(data, q, block, test, mean_mdl, variance_mdl){
if(nrow(data) < block + test) stop("Number of rows in 'data' is less than block + test")
source("C:/Users/Marius/Desktop/Simulation/SVRGARCHKDE_Functions/Source_File/Source_SVRGARCHKDE.R")
library(doParallel)
library(quantmod)
allData <- data
test_n <- test
block_size <- block
loop_start <- nrow(allData) - test_n
loop_end <- nrow(allData) - 1
results <- data.frame(Mean = numeric(),
Upper = numeric(),
Lower = numeric(),
Vola = numeric())
cl <- makeCluster(4)
registerDoParallel(cl)
results <- foreach(i = loop_start:loop_end, .combine = "rbind") %dopar% {
source("C:/Users/Marius/Desktop/Simulation/SVRGARCHKDE_Functions/Source_File/Source_SVRGARCHKDE.R")
library(quantmod)
library(e1071)
library(zoo)
x <- allData[(i-block_size+1):i,-1]
y <- allData[(i-block_size+1):i,1]
if(mean_mdl == "KDE" | variance_mdl == "KDE"){
KDE_VaR(y, q, kernel = "gaussian")
}else{
svm_kde(x = x, y = y, q = q, mean_mdl = mean_mdl, variance.mdl = variance_mdl, kernel = "gaussian")
}
}
stopCluster(cl)
results$Vola <- na.locf(results$Vola)
results <- plotResults(results, allData, test_n, q)
return(results)
}
svm_kde <- function(x, y, q, mean_mdl, variance.mdl, kernel){
#############################################################################
# 1. Fit mean model
#############################################################################
# Set parameters
svm_mean_eps <- mean_mdl$eps
svm_mean_cost <- mean_mdl$cost
sigma <- mean_mdl$sigma
svm_mean_gamma <- 1/(2*sigma^2)
# SVM for mean
svm_mean <- svm(x = x, y = y, type = "eps-regression", kernel = "radial",
gamma = svm_mean_gamma,
cost = svm_mean_cost,
epsilon = svm_mean_eps)
# Get fitted values and residual (format as xts for lagging in variance fitting)
mean <- xts(x = svm_mean$fitted, order.by = index(y))
eps <- xts(x = svm_mean$residuals, order.by = index(y))
# Prediction of next periods unseen return
mean_pred <- predict(svm_mean, newdata = y[nrow(y)])
#############################################################################
# 2. Fit variance model
#############################################################################
# Set paramters
svm_var_eps <- quantile(scale(eps)^2, variance.mdl$eps_quantile)
svm_var_cost <- variance.mdl$cost
sigma <- variance.mdl$sigma
svm_var_gamma <- 1/(2*sigma^2)
# Get data
u <- na.omit(cbind(eps, lag(eps)))^2
# Estimate model
svm_var <- svm_variance(x = u[,-1], y = u[,1], m = variance.mdl,
gamma = svm_var_gamma,
cost = svm_var_cost,
epsilon = svm_var_eps)
# Get fitted variances to standardize residuals
if(variance.mdl$model == "AR") fcast_vola <- svm_var$fitted
if(variance.mdl$model == "ARMA") fcast_vola <- svm_var$model$fitted
# Replace negativ variances by last positiv value
fcast_vola[fcast_vola<=0] <- NA
fcast_vola <- na.locf(fcast_vola)
fcast_vola[1] <- ifelse(is.na(fcast_vola[1]), u[1,2], fcast_vola[1])
# Prediction of next periods unseen variance
if(variance.mdl$model == "AR") vola_new_dat <- u[nrow(u),1]
if(variance.mdl$model == "ARMA") vola_new_dat <- cbind(u[nrow(u),1], svm_var$lagRes[length(svm_var$lagRes)])
if(variance.mdl$model == "AR") vola_pred <- predict(svm_var, newdata = vola_new_dat)
if(variance.mdl$model == "ARMA") vola_pred <- predict(svm_var$model, newdata = vola_new_dat)
#############################################################################
# 3. Compute quantiles of scaled standardized residuals
#############################################################################
# Standardize and scale residuals
if(variance.mdl$model == "AR") u_sc <- eps[-1]/sqrt(fcast_vola)
if(variance.mdl$model == "ARMA") u_sc <- eps[-(1:2)]/sqrt(fcast_vola)
u_sc <- scale(u_sc)
# Compute quantiles of scaled standardized residuals
q_upper <- QKDE(q, c(0, max(u_sc)*1.5), data = u_sc, kernel = kernel)
q_lower <- -QKDE(q, c(0, max(-u_sc)*1.5), data = -u_sc, kernel = kernel)
#############################################################################
# 4. Collect results
#############################################################################
# Specify data frame for storing results
results <- data.frame(matrix(NA, nrow = 1, ncol = 4))
names(results) <- c("Mean", "Upper", "Lower", "Vola")
# Save results in data frame
results$Mean <- mean_pred
results$Upper <- q_upper
results$Lower <- q_lower
results$Vola <- ifelse(vola_pred <= 0, u[nrow(u),2], sqrt(vola_pred))
return(results)
}
###############################################################################
# Function for variance estimation
svm_variance <- function(x, y, m, gamma, cost, epsilon){
if(m == "AR"){
model <- svm(x = x, y = y, scale = TRUE,
type = "eps-regression", kernel = "radial",
gamma = gamma, cost = cost, epsilon = epsilon)
result <- model
}
if(m == "ARMA"){
rnn_v1 <- svm(x = x, y = y, scale = TRUE,
type = "eps-regression", kernel = "radial",
gamma = gamma, cost = cost, epsilon = epsilon)
w <- xts(x = rnn_v1$residuals, order.by = index(y))
garch_input <- na.omit(cbind(y, x, lag(w)))
model <- svm(x = garch_input[,2:3], y = garch_input[,1], scale = TRUE,
type = "eps-regression", kernel = "radial",
gamma = gamma, cost = cost, epsilon = epsilon)
result <- list(model = model, lagRes = w)
}
return(result)
}
###############################################################################
# Mean model
svm_kde_mean <- function(x, y, mean_mdl){
#############################################################################
# 1. Fit mean model
#############################################################################
# Set parameters
svm_mean_eps <- mean_mdl$eps
svm_mean_cost <- mean_mdl$cost
sigma <- mean_mdl$sigma
svm_mean_gamma <- 1/(2*sigma^2)
# SVM for mean
svm_mean <- svm(x = x, y = y, type = "eps-regression", kernel = "radial",
gamma = svm_mean_gamma,
cost = svm_mean_cost,
epsilon = svm_mean_eps)
# Get fitted values and residual (format as xts for lagging in variance fitting)
mean <- xts(x = svm_mean$fitted, order.by = index(y))
eps <- xts(x = svm_mean$residuals, order.by = index(y))
# Prediction of next periods unseen return
mean_pred <- predict(svm_mean, newdata = y[nrow(y)])
return(mean_pred)
}
###############################################################################
# Mean model parallelized
svm_kde_mean_dopar <- function(data, block, test, mean_mdl){
if(nrow(data) < block + test) stop("Number of rows in 'data' is less than block + test")
source("C:/Users/Marius/Desktop/Simulation/SVRGARCHKDE_Functions/Source_File/Source_SVRGARCHKDE.R")
library(doParallel)
library(quantmod)
allData <- data
test_n <- test
block_size <- block
loop_start <- nrow(allData) - test_n
loop_end <- nrow(allData) - 1
results <- data.frame(Mean = numeric(),
Upper = numeric(),
Lower = numeric(),
Vola = numeric())
cl <- makeCluster(4)
registerDoParallel(cl)
results <- foreach(i = loop_start:loop_end, .combine = "rbind") %dopar% {
source("C:/Users/Marius/Desktop/Simulation/SVRGARCHKDE_Functions/Source_File/Source_SVRGARCHKDE.R")
library(quantmod)
library(e1071)
library(zoo)
x <- allData[(i-block_size+1):i,-1]
y <- allData[(i-block_size+1):i,1]
mean_mdl <- mean_mdl
svm_kde_mean(x = x, y = y, mean_mdl = mean_mdl)
}
stopCluster(cl)
real <- data[(nrow(data) - test + 1):nrow(data),1]
pred <- xts(results, order.by = index(real))
mse <- sum((coredata(real) - coredata(pred))^2)/nrow(real)
results <- mse
return(results)
}
###############################################################################
# Function for plotting results and analysis
plotResults <- function(results, allData, test_n, q){
results$True <- allData[(nrow(allData) - test_n + 1):nrow(allData),1]
#Analyze Results
results$FCast_Upper <- results$Mean + results$Upper*results$Vola
results$FCast_Lower <- results$Mean + results$Lower*results$Vola
prop_upper <- sum(results$FCast_Upper < results$True)/nrow(results) #
prop_lower <- sum(results$FCast_Lower > results$True)/nrow(results) #Downside risk: if greater 5% -> BAD
#Plot in-sample results
org <- as.numeric(results$True)
fcast_upper <- results$FCast_Upper
fcast_lower <- results$FCast_Lower
ylim_max <- max(abs(c(org, fcast_upper, fcast_lower)))
ylim_min <- -ylim_max
head <- paste0(q*100, "% and ", (1-q)*100, "% VaR-Forecast")
plot(results$True, type = "p", ylim = c(ylim_min, ylim_max),
ylab = "Return in Percent", main = head)
points(results$True, col = "green")
lines(xts(x = fcast_upper, order.by = index(results$True)), col = "red", lwd = 2)
lines(xts(x = fcast_lower, order.by = index(results$True)), col = "red", lwd = 2)
# plot(org, type = "p", col = "green", lwd = 1, ylim = c(ylim_min, ylim_max), ylab = "Value")
# lines(fcast_upper, col = "red", lwd = 2)
# lines(fcast_lower, col = "red", lwd = 2)
errors <- data.frame(Index = 1:length(org), Real = org)
out <- errors$Real > fcast_upper | errors$Real < fcast_lower
points(errors$Index[out], errors$Real[out], col = "blue", pch = 16)
#print(prop_upper)
#print(prop_lower)
prop <- data.frame(prop_upper, prop_lower)
results <- list(Data = results,
Empirical_Coverage = prop)
return(results)
}
###############################################################################
# VaR using kernel density estimation
KDE_VaR <- function(x, q, kernel){
#############################################################################
# 1. Estimate quantiles of data
#############################################################################
q_upper <- QKDE(q, c(0, max(x)*1.5), data = x, kernel = kernel)
q_lower <- -QKDE(q, c(0, max(-x)*1.5), data = -x, kernel = kernel)
#############################################################################
# 2. Collect results
#############################################################################
# Specify data frame for storing results
results <- data.frame(matrix(NA, nrow = 1, ncol = 4))
names(results) <- c("Mean", "Upper", "Lower", "Vola")
# Save results in data frame
results$Mean <- 0
results$Upper <- q_upper
results$Lower <- q_lower
results$Vola <- 1
return(results)
}
|
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
# Load packages ----
library(shiny) # Shiny web app
library(shinydashboard) # Shiny Dashboards
library(shinydashboardPlus) # additionaly dashboard features
library(shinythemes) # additional themes for Shiny Apps
library(shinyWidgets) # additional functionality
library(dashboardthemes) # additional themes for Shiny Dashboards
library(DT) # alternative way of handling data tables
library(tidyverse) # data wrangling and exploration
library(ggplot2) # visualisation
# Source required files ----
source("functions/basic_functions.R")
source("functions/first_sims.R")
source("functions/methods_comparison.R")
# Load example_data
example_data <-
read.csv(file = "data/betas.csv",
header = TRUE,
sep = ",",
quote = "\"",
check.names = FALSE) %>%
.[, -1]
# Define comparison function
compare <- function(main, comparison) {
rows <- list(NA)
df1 <- main %>%
select(c1, c2, c3) %>%
mutate(content = NA)
df2 <- comparison %>%
select(c1, c2, c3) %>%
mutate(content = NA)
df1$content <- apply(df1[, 1:3], 1, paste0, sep = "", collapse = "")
df2$content <- apply(df2[, 1:3], 1, paste0, sep = "", collapse = "")
for (i in 1:nrow(df1)) {
if (df2$content %in% df1$content[i] %>% any()) {
# store row numbers of rows with same values
same_rows <- df2$content %in% df1$content[i] %>% which()
rows[[i]] <- same_rows
} else {
rows[[i]] <- NA
}
}
print(rows)
return(rows)
}
# Define UI for application ----
ui <- dashboardPage(
dashboardHeader(title = "Gini Anker",
titleWidth = 350),
dashboardSidebar(
# Remove the sidebar toggle element
tags$script(JS("document.getElementsByClassName('sidebar-toggle')[0].
style.visibility = 'hidden';")),
width = 350,
collapsed = TRUE,
minified = FALSE),
dashboardBody(
shinyDashboardThemes(
theme = "grey_light"
),
source("tabs/tab_main.R",
local = TRUE, encoding = "utf-8")[1]
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
# Original Coefficients Table ----
# create data frame with example .csv file
dat <- reactiveValues(df = example_data)
# create reactive set
df <- reactive({
dat$df %>%
mutate(Item = 1:nrow(dat$df)) %>%
select(Item, everything())
})
# table containing original beta coefficients
output$beta_table <- DT::renderDataTable({
#print(df())
DT::datatable(isolate(df()), rownames = FALSE,
selection = "none",
editable = TRUE,
options = list(dom = 't',
scrollX = TRUE,
pageLength = 100,
ordering = FALSE))
})
proxy <- dataTableProxy("beta_table")
observe({
proxy %>% replaceData(df(), rownames = FALSE)
})
# edit cells of df
observeEvent(input$beta_table_cell_edit, {
info <- input$beta_table_cell_edit
#str(info)
row <- info$row
col <- info$col
value <- info$value %>% as.numeric()
dat$df[row, col] <- value
})
# create data frame from uploaded .csv file
observeEvent(input$upload_button, {
# when reading semicolon separated files,
# having a comma separator causes `read.csv` to error
tryCatch(
{
tmp <- read.csv(input$file$datapath,
header = input$header,
sep = input$sep,
quote = input$quote,
check.names = FALSE)
# remove column containing row names
if (colnames(tmp)[1] == "") {
tmp <- tmp[, -1]
}
dat$df <- tmp
},
error = function(e) {
# return a safeError if a parsing error occurs
stop(safeError(e))
}
)
})
# add row
observeEvent(input$add_row, {
tmp <- data.frame(0, 0, 0)
colnames(tmp) <- colnames(dat$df)
dat$df <- rbind(dat$df,
tmp)
})
# remove row
observeEvent(input$remove_row, {
dat$df <- dat$df[-nrow(dat$df), ]
})
# gini_all with selecatble rows ----
# create reactive variable with selected row
selected_row <- reactiveVal(NULL)
observeEvent(input$all_rows_selected, {
selected_row(input$all_rows_selected)
}, ignoreNULL = FALSE)
# create reactive list with all_methods_maxima results
gini_all <- reactive({
temp <- all_methods_maxima(beta1 = df()[, 2],
beta2 = df()[, 3],
beta3 = df()[, 4])
temp$All <- temp$All %>%
as.data.frame() %>%
arrange(desc(Gini_Sum)) %>%
rename("Gini Sum" = Gini_Sum)
temp$All$"Gini Sum" <- round(temp$All$"Gini Sum", digits = 2)
temp$Reference <- temp$Reference %>%
as.data.frame() %>%
arrange(desc(Gini_Sum)) %>%
rename("Gini Sum" = Gini_Sum)
temp$Reference$"Gini Sum" <- round(temp$Reference$"Gini Sum", digits = 2)
temp$Sequential <- temp$Sequential %>%
as.data.frame() %>%
arrange(desc(Gini_Sum)) %>%
rename("Gini Sum" = Gini_Sum)
temp$Sequential$"Gini Sum" <- round(temp$Sequential$"Gini Sum", digits = 2)
temp$All <- temp$All %>%
mutate(same_reference = compare(temp$All, temp$Reference),
same_sequential = compare(temp$All, temp$Sequential))
return(temp)
})
# Gini Output ----
# plot of the beta coefficients
output$gini_plot <- renderPlot({
temp <- gini_all()$All %>% as.data.frame()
if (is.null(selected_row())) {
ggplot_betas(df()[, -1], shifts = c(0, 0, 0))
} else {
ggplot_betas(df()[, -1],
shifts = temp %>%
slice(selected_row()) %>%
select(starts_with("c")))
}
})
# tables showing output of all_methods_maxima() function
output$all <- DT::renderDataTable({
temp <- gini_all()$All %>%
select(-same_reference, -same_sequential) %>%
as.data.frame()
DT::datatable(temp, rownames = FALSE, selection = "single",
options = list(dom = 't',
scrollX = TRUE,
pageLength = 1000,
order = list(4, "desc"),
ordering = FALSE))
})
output$reference <- DT::renderDataTable({
temp <- gini_all()$Reference %>% as.data.frame()
if (is.null(selected_row())) {
highlight <- NA
} else {
highlight <- gini_all()$All$same_reference[[selected_row()]]
}
DT::datatable(temp, rownames = FALSE,
selection = list(mode = "multiple",
selected = highlight),
options = list(dom = 't',
scrollX = TRUE,
pageLength = 100,
order = list(5, "desc"),
ordering = FALSE))
})
output$sequential <- DT::renderDataTable({
temp <- gini_all()$Sequential %>% as.data.frame()
if (is.null(selected_row())) {
highlight <- NA
} else {
highlight <- gini_all()$All$same_sequential[[selected_row()]]
}
DT::datatable(temp, rownames = FALSE,
selection = list(mode = "multiple",
selected = highlight),
options = list(dom = 't',
scrollX = TRUE,
pageLength = 100,
order = list(6, "desc"),
ordering = FALSE))
})
}
# Run the application
shinyApp(ui = ui, server = server)
| /app.R | no_license | alstoc/gini_anker_shiny | R | false | false | 8,941 | r | #
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
# Load packages ----
library(shiny) # Shiny web app
library(shinydashboard) # Shiny Dashboards
library(shinydashboardPlus) # additionaly dashboard features
library(shinythemes) # additional themes for Shiny Apps
library(shinyWidgets) # additional functionality
library(dashboardthemes) # additional themes for Shiny Dashboards
library(DT) # alternative way of handling data tables
library(tidyverse) # data wrangling and exploration
library(ggplot2) # visualisation
# Source required files ----
source("functions/basic_functions.R")
source("functions/first_sims.R")
source("functions/methods_comparison.R")
# Load example_data
example_data <-
read.csv(file = "data/betas.csv",
header = TRUE,
sep = ",",
quote = "\"",
check.names = FALSE) %>%
.[, -1]
# Define comparison function
compare <- function(main, comparison) {
rows <- list(NA)
df1 <- main %>%
select(c1, c2, c3) %>%
mutate(content = NA)
df2 <- comparison %>%
select(c1, c2, c3) %>%
mutate(content = NA)
df1$content <- apply(df1[, 1:3], 1, paste0, sep = "", collapse = "")
df2$content <- apply(df2[, 1:3], 1, paste0, sep = "", collapse = "")
for (i in 1:nrow(df1)) {
if (df2$content %in% df1$content[i] %>% any()) {
# store row numbers of rows with same values
same_rows <- df2$content %in% df1$content[i] %>% which()
rows[[i]] <- same_rows
} else {
rows[[i]] <- NA
}
}
print(rows)
return(rows)
}
# Define UI for application ----
ui <- dashboardPage(
dashboardHeader(title = "Gini Anker",
titleWidth = 350),
dashboardSidebar(
# Remove the sidebar toggle element
tags$script(JS("document.getElementsByClassName('sidebar-toggle')[0].
style.visibility = 'hidden';")),
width = 350,
collapsed = TRUE,
minified = FALSE),
dashboardBody(
shinyDashboardThemes(
theme = "grey_light"
),
source("tabs/tab_main.R",
local = TRUE, encoding = "utf-8")[1]
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
# Original Coefficients Table ----
# create data frame with example .csv file
dat <- reactiveValues(df = example_data)
# create reactive set
df <- reactive({
dat$df %>%
mutate(Item = 1:nrow(dat$df)) %>%
select(Item, everything())
})
# table containing original beta coefficients
output$beta_table <- DT::renderDataTable({
#print(df())
DT::datatable(isolate(df()), rownames = FALSE,
selection = "none",
editable = TRUE,
options = list(dom = 't',
scrollX = TRUE,
pageLength = 100,
ordering = FALSE))
})
proxy <- dataTableProxy("beta_table")
observe({
proxy %>% replaceData(df(), rownames = FALSE)
})
# edit cells of df
observeEvent(input$beta_table_cell_edit, {
info <- input$beta_table_cell_edit
#str(info)
row <- info$row
col <- info$col
value <- info$value %>% as.numeric()
dat$df[row, col] <- value
})
# create data frame from uploaded .csv file
observeEvent(input$upload_button, {
# when reading semicolon separated files,
# having a comma separator causes `read.csv` to error
tryCatch(
{
tmp <- read.csv(input$file$datapath,
header = input$header,
sep = input$sep,
quote = input$quote,
check.names = FALSE)
# remove column containing row names
if (colnames(tmp)[1] == "") {
tmp <- tmp[, -1]
}
dat$df <- tmp
},
error = function(e) {
# return a safeError if a parsing error occurs
stop(safeError(e))
}
)
})
# add row
observeEvent(input$add_row, {
tmp <- data.frame(0, 0, 0)
colnames(tmp) <- colnames(dat$df)
dat$df <- rbind(dat$df,
tmp)
})
# remove row
observeEvent(input$remove_row, {
dat$df <- dat$df[-nrow(dat$df), ]
})
# gini_all with selecatble rows ----
# create reactive variable with selected row
selected_row <- reactiveVal(NULL)
observeEvent(input$all_rows_selected, {
selected_row(input$all_rows_selected)
}, ignoreNULL = FALSE)
# create reactive list with all_methods_maxima results
gini_all <- reactive({
temp <- all_methods_maxima(beta1 = df()[, 2],
beta2 = df()[, 3],
beta3 = df()[, 4])
temp$All <- temp$All %>%
as.data.frame() %>%
arrange(desc(Gini_Sum)) %>%
rename("Gini Sum" = Gini_Sum)
temp$All$"Gini Sum" <- round(temp$All$"Gini Sum", digits = 2)
temp$Reference <- temp$Reference %>%
as.data.frame() %>%
arrange(desc(Gini_Sum)) %>%
rename("Gini Sum" = Gini_Sum)
temp$Reference$"Gini Sum" <- round(temp$Reference$"Gini Sum", digits = 2)
temp$Sequential <- temp$Sequential %>%
as.data.frame() %>%
arrange(desc(Gini_Sum)) %>%
rename("Gini Sum" = Gini_Sum)
temp$Sequential$"Gini Sum" <- round(temp$Sequential$"Gini Sum", digits = 2)
temp$All <- temp$All %>%
mutate(same_reference = compare(temp$All, temp$Reference),
same_sequential = compare(temp$All, temp$Sequential))
return(temp)
})
# Gini Output ----
# plot of the beta coefficients
output$gini_plot <- renderPlot({
temp <- gini_all()$All %>% as.data.frame()
if (is.null(selected_row())) {
ggplot_betas(df()[, -1], shifts = c(0, 0, 0))
} else {
ggplot_betas(df()[, -1],
shifts = temp %>%
slice(selected_row()) %>%
select(starts_with("c")))
}
})
# tables showing output of all_methods_maxima() function
output$all <- DT::renderDataTable({
temp <- gini_all()$All %>%
select(-same_reference, -same_sequential) %>%
as.data.frame()
DT::datatable(temp, rownames = FALSE, selection = "single",
options = list(dom = 't',
scrollX = TRUE,
pageLength = 1000,
order = list(4, "desc"),
ordering = FALSE))
})
output$reference <- DT::renderDataTable({
temp <- gini_all()$Reference %>% as.data.frame()
if (is.null(selected_row())) {
highlight <- NA
} else {
highlight <- gini_all()$All$same_reference[[selected_row()]]
}
DT::datatable(temp, rownames = FALSE,
selection = list(mode = "multiple",
selected = highlight),
options = list(dom = 't',
scrollX = TRUE,
pageLength = 100,
order = list(5, "desc"),
ordering = FALSE))
})
output$sequential <- DT::renderDataTable({
temp <- gini_all()$Sequential %>% as.data.frame()
if (is.null(selected_row())) {
highlight <- NA
} else {
highlight <- gini_all()$All$same_sequential[[selected_row()]]
}
DT::datatable(temp, rownames = FALSE,
selection = list(mode = "multiple",
selected = highlight),
options = list(dom = 't',
scrollX = TRUE,
pageLength = 100,
order = list(6, "desc"),
ordering = FALSE))
})
}
# Run the application
shinyApp(ui = ui, server = server)
|
#' <Add Title>
#'
#' <Add Description>
#'
#' @import htmlwidgets
#'
#' @export
lamplighter <- function(nx = 20, ny = 20, t = 50, width = NULL, height = NULL) {
x = list(nx = nx, ny = ny, t = t)
# create widget
htmlwidgets::createWidget(
name = 'lamplighter',
x,
width = width,
height = height,
package = 'probArt'
)
}
#' Widget output function for use in Shiny
#'
#' @export
lamplighterOutput <- function(outputId, width = '100%', height = '400px'){
shinyWidgetOutput(outputId, 'lamplighter', width, height, package = 'probArt')
}
#' Widget render function for use in Shiny
#'
#' @export
renderLamplighter <- function(expr, env = parent.frame(), quoted = FALSE) {
if (!quoted) { expr <- substitute(expr) } # force quoted
shinyRenderWidget(expr, lamplighterOutput, env, quoted = TRUE)
}
| /R/lamplighter.R | no_license | krisrs1128/probArt | R | false | false | 822 | r | #' <Add Title>
#'
#' <Add Description>
#'
#' @import htmlwidgets
#'
#' @export
lamplighter <- function(nx = 20, ny = 20, t = 50, width = NULL, height = NULL) {
x = list(nx = nx, ny = ny, t = t)
# create widget
htmlwidgets::createWidget(
name = 'lamplighter',
x,
width = width,
height = height,
package = 'probArt'
)
}
#' Widget output function for use in Shiny
#'
#' @export
lamplighterOutput <- function(outputId, width = '100%', height = '400px'){
shinyWidgetOutput(outputId, 'lamplighter', width, height, package = 'probArt')
}
#' Widget render function for use in Shiny
#'
#' @export
renderLamplighter <- function(expr, env = parent.frame(), quoted = FALSE) {
if (!quoted) { expr <- substitute(expr) } # force quoted
shinyRenderWidget(expr, lamplighterOutput, env, quoted = TRUE)
}
|
\name{exner}
\alias{exner}
\title{Exner function}
\usage{
exner(pres)
}
\arguments{
\item{pres}{air pressure (Bar)}
}
\description{
estimated exner function
}
\author{
Mike Dietze
}
| /modules/data.atmosphere/man/exner.Rd | permissive | rgknox/pecan | R | false | false | 191 | rd | \name{exner}
\alias{exner}
\title{Exner function}
\usage{
exner(pres)
}
\arguments{
\item{pres}{air pressure (Bar)}
}
\description{
estimated exner function
}
\author{
Mike Dietze
}
|
subroutine tabalc(ifd)
implicit integer*4 (i-n)
#ccc version date: 06/01/83
#ccc author(s): Roger Clark & Jeff Hoover
#ccc language: Ratfor
#ccc
#ccc short description:
#ccc This subroutine checks for open error on tablet.
#ccc algorithm description: none
#ccc system requirements: none
#ccc subroutines called: none
#ccc argument list description:
#ccc arguments: ifd
#ccc parameter description:
#ccc common description:
#ccc message files referenced:
#ccc internal variables:
#ccc file description:
#ccc user command lines:
#ccc update information:
#ccc NOTES:
#ccc
include "../common/lundefs"
include "../common/filenames"
ifd = iopen(TAB,0)
if (ifd < 0) {
write(ttyout,10)
}
10 format(1x,'OPEN ERROR ON TABLET....')
return
end
| /src-local/specpr/src.specpr/fcn20-25/tabalc.r | no_license | ns-bak/tetracorder-tutorial | R | false | false | 783 | r | subroutine tabalc(ifd)
implicit integer*4 (i-n)
#ccc version date: 06/01/83
#ccc author(s): Roger Clark & Jeff Hoover
#ccc language: Ratfor
#ccc
#ccc short description:
#ccc This subroutine checks for open error on tablet.
#ccc algorithm description: none
#ccc system requirements: none
#ccc subroutines called: none
#ccc argument list description:
#ccc arguments: ifd
#ccc parameter description:
#ccc common description:
#ccc message files referenced:
#ccc internal variables:
#ccc file description:
#ccc user command lines:
#ccc update information:
#ccc NOTES:
#ccc
include "../common/lundefs"
include "../common/filenames"
ifd = iopen(TAB,0)
if (ifd < 0) {
write(ttyout,10)
}
10 format(1x,'OPEN ERROR ON TABLET....')
return
end
|
setwd('/home/john/Kaggle/West_Nile_Virus_Prediction/Data')
library(Metrics) #to calculate AUC of ROC curve
library(dplyr)
library(ggplot2)
library(randomForest) #for classification tree
training_final <- read.csv("training_final.csv", stringsAsFactors = FALSE, header = TRUE)
cv_final <- read.csv("cv_final.csv", stringsAsFactors = FALSE, header = TRUE)
training_final <- training_final %>%
select(cut,
species2,
c10,
avg_may_temp,
num_may_rain,
avg_may_dew,
avg_may_wet,
avg_avg,
avg_min,
avg_max,
avg_dew,
avg_wet,
wet_con,
temp_range,
temp30,
rain14,
dew30,
wet30,
range1,
wnvpresent)
str(training_final)
training_final$species2 <- as.factor(training_final$species2)
training_final$cut <- as.factor(training_final$cut)
training_final$c10 <- as.factor(training_final$c10)
cv_final <- cv_final %>%
select(cut,
species2,
c10,
avg_may_temp,
num_may_rain,
avg_may_dew,
avg_may_wet,
avg_avg,
avg_min,
avg_max,
avg_dew,
avg_wet,
wet_con,
temp_range,
temp30,
rain14,
dew30,
wet30,
range1,
wnvpresent)
cv_final$species2 <- as.factor(cv_final$species2)
cv_final$cut <- as.factor(cv_final$cut)
cv_final$c10 <- as.factor(cv_final$c10)
set.seed(22)
rf <- randomForest(as.factor(wnvpresent) ~.,
data = training_final,
importance = TRUE )
importance(rf)
rf_predict <- predict(object = rf,
newdata = cv_final,
type = 'prob')
head(rf_predict)
auc(cv_final$wnvpresent,rf_predict[,2])
# 0.6677036
## Let's try it on the test data
test_final <- read.csv("test_final.csv", stringsAsFactors = FALSE, header = TRUE)
test_final$c10 <- as.factor(test_final$c10)
test_final$cut <- as.factor(test_final$cut)
test_final$species2 <- as.factor(test_final$species2)
predict_test <- predict(object = rf,
newdata = test_final,
type = 'prob')
rf_submission <- data.frame(test_final$id, predict_test[,2])
head(rf_submission)
colnames(rf_submission) <- c("Id","WnvPresent")
hist(rf_submission$WnvPresent)
write.csv(rf_submission, 'rf_submission.csv',row.names = FALSE)
### Now a random forest using lat/lon rather than region
training_final <- read.csv("training_final.csv", stringsAsFactors = FALSE, header = TRUE)
cv_final <- read.csv("cv_final.csv", stringsAsFactors = FALSE, header = TRUE)
training_final <- training_final %>%
select(cut,
species2,
latitude,
longitude,
avg_may_temp,
num_may_rain,
avg_may_dew,
avg_may_wet,
avg_avg,
avg_min,
avg_max,
avg_dew,
avg_wet,
wet_con,
temp_range,
temp30,
rain14,
dew30,
wet30,
range1,
wnvpresent)
str(training_final)
training_final$species2 <- as.factor(training_final$species2)
training_final$cut <- as.factor(training_final$cut)
cv_final <- cv_final %>%
select(cut,
species2,
latitude,
longitude,
avg_may_temp,
num_may_rain,
avg_may_dew,
avg_may_wet,
avg_avg,
avg_min,
avg_max,
avg_dew,
avg_wet,
wet_con,
temp_range,
temp30,
rain14,
dew30,
wet30,
range1,
wnvpresent)
cv_final$species2 <- as.factor(cv_final$species2)
cv_final$cut <- as.factor(cv_final$cut)
set.seed(28)
rf2 <- randomForest(as.factor(wnvpresent) ~.,
data = training_final,
importance = TRUE )
rf_predict2 <- predict(object = rf2,
newdata = cv_final,
type = 'prob')
head(rf_predict2)
auc(cv_final$wnvpresent,rf_predict2[,2])
# 0.76
## Let's try it on the test data
test_final <- read.csv("test_final.csv", stringsAsFactors = FALSE, header = TRUE)
test_final$cut <- as.factor(test_final$cut)
test_final$species2 <- as.factor(test_final$species2)
predict_test <- predict(object = rf2,
newdata = test_final,
type = 'prob')
rf_submission2 <- data.frame(test_final$id, predict_test[,2])
head(rf_submission2)
colnames(rf_submission2) <- c("Id","WnvPresent")
hist(rf_submission2$WnvPresent)
write.csv(rf_submission2, 'rf_submission2.csv',row.names = FALSE)
| /West_Nile_Virus_Prediction/R code/3_42_random_forest.R | no_license | johnckane/kaggle | R | false | false | 4,799 | r | setwd('/home/john/Kaggle/West_Nile_Virus_Prediction/Data')
library(Metrics) #to calculate AUC of ROC curve
library(dplyr)
library(ggplot2)
library(randomForest) #for classification tree
training_final <- read.csv("training_final.csv", stringsAsFactors = FALSE, header = TRUE)
cv_final <- read.csv("cv_final.csv", stringsAsFactors = FALSE, header = TRUE)
training_final <- training_final %>%
select(cut,
species2,
c10,
avg_may_temp,
num_may_rain,
avg_may_dew,
avg_may_wet,
avg_avg,
avg_min,
avg_max,
avg_dew,
avg_wet,
wet_con,
temp_range,
temp30,
rain14,
dew30,
wet30,
range1,
wnvpresent)
str(training_final)
training_final$species2 <- as.factor(training_final$species2)
training_final$cut <- as.factor(training_final$cut)
training_final$c10 <- as.factor(training_final$c10)
cv_final <- cv_final %>%
select(cut,
species2,
c10,
avg_may_temp,
num_may_rain,
avg_may_dew,
avg_may_wet,
avg_avg,
avg_min,
avg_max,
avg_dew,
avg_wet,
wet_con,
temp_range,
temp30,
rain14,
dew30,
wet30,
range1,
wnvpresent)
cv_final$species2 <- as.factor(cv_final$species2)
cv_final$cut <- as.factor(cv_final$cut)
cv_final$c10 <- as.factor(cv_final$c10)
set.seed(22)
rf <- randomForest(as.factor(wnvpresent) ~.,
data = training_final,
importance = TRUE )
importance(rf)
rf_predict <- predict(object = rf,
newdata = cv_final,
type = 'prob')
head(rf_predict)
auc(cv_final$wnvpresent,rf_predict[,2])
# 0.6677036
## Let's try it on the test data
test_final <- read.csv("test_final.csv", stringsAsFactors = FALSE, header = TRUE)
test_final$c10 <- as.factor(test_final$c10)
test_final$cut <- as.factor(test_final$cut)
test_final$species2 <- as.factor(test_final$species2)
predict_test <- predict(object = rf,
newdata = test_final,
type = 'prob')
rf_submission <- data.frame(test_final$id, predict_test[,2])
head(rf_submission)
colnames(rf_submission) <- c("Id","WnvPresent")
hist(rf_submission$WnvPresent)
write.csv(rf_submission, 'rf_submission.csv',row.names = FALSE)
### Now a random forest using lat/lon rather than region
training_final <- read.csv("training_final.csv", stringsAsFactors = FALSE, header = TRUE)
cv_final <- read.csv("cv_final.csv", stringsAsFactors = FALSE, header = TRUE)
training_final <- training_final %>%
select(cut,
species2,
latitude,
longitude,
avg_may_temp,
num_may_rain,
avg_may_dew,
avg_may_wet,
avg_avg,
avg_min,
avg_max,
avg_dew,
avg_wet,
wet_con,
temp_range,
temp30,
rain14,
dew30,
wet30,
range1,
wnvpresent)
str(training_final)
training_final$species2 <- as.factor(training_final$species2)
training_final$cut <- as.factor(training_final$cut)
cv_final <- cv_final %>%
select(cut,
species2,
latitude,
longitude,
avg_may_temp,
num_may_rain,
avg_may_dew,
avg_may_wet,
avg_avg,
avg_min,
avg_max,
avg_dew,
avg_wet,
wet_con,
temp_range,
temp30,
rain14,
dew30,
wet30,
range1,
wnvpresent)
cv_final$species2 <- as.factor(cv_final$species2)
cv_final$cut <- as.factor(cv_final$cut)
set.seed(28)
rf2 <- randomForest(as.factor(wnvpresent) ~.,
data = training_final,
importance = TRUE )
rf_predict2 <- predict(object = rf2,
newdata = cv_final,
type = 'prob')
head(rf_predict2)
auc(cv_final$wnvpresent,rf_predict2[,2])
# 0.76
## Let's try it on the test data
test_final <- read.csv("test_final.csv", stringsAsFactors = FALSE, header = TRUE)
test_final$cut <- as.factor(test_final$cut)
test_final$species2 <- as.factor(test_final$species2)
predict_test <- predict(object = rf2,
newdata = test_final,
type = 'prob')
rf_submission2 <- data.frame(test_final$id, predict_test[,2])
head(rf_submission2)
colnames(rf_submission2) <- c("Id","WnvPresent")
hist(rf_submission2$WnvPresent)
write.csv(rf_submission2, 'rf_submission2.csv',row.names = FALSE)
|
testlist <- list(a = 960051513L, b = 960051513L, x = c(960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 520093695L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, NA, -1L, -1L, -15007745L, -63998L, -1L, -49153L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051711L, -1L, -63998L, -1L, -49153L, 960051513L, 960051513L, 960051513L))
result <- do.call(grattan:::anyOutside,testlist)
str(result) | /grattan/inst/testfiles/anyOutside/libFuzzer_anyOutside/anyOutside_valgrind_files/1610130414-test.R | no_license | akhikolla/updated-only-Issues | R | false | false | 613 | r | testlist <- list(a = 960051513L, b = 960051513L, x = c(960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 520093695L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, NA, -1L, -1L, -15007745L, -63998L, -1L, -49153L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051513L, 960051711L, -1L, -63998L, -1L, -49153L, 960051513L, 960051513L, 960051513L))
result <- do.call(grattan:::anyOutside,testlist)
str(result) |
epsilon <- 10e-4
data100.org <- read.csv('square100_initialtest01.csv')
data1000.org <- read.csv('square1000_initialtest01.csv')
data5000.org <- read.csv('square5000_initialtest01.csv')
data100.converge <- subset(data100.org,!is.na(data100.org$logL.1))
data1000.converge <- subset(data1000.org,!is.na(data1000.org$logL.1))
data5000.converge <- subset(data5000.org,!is.na(data5000.org$logL.1))
data100.converge.num <- nrow(data100.converge)
data1000.converge.num <- nrow(data1000.converge)
data5000.converge.num <- nrow(data5000.converge)
data100.global <- subset(data100.converge,data100.converge$logL.1 + epsilon >= max(data100.converge$logL.1,na.rm=T))
data1000.global <- subset(data1000.converge,data1000.converge$logL.1 + epsilon >= max(data1000.converge$logL.1,na.rm=T))
data5000.global <- subset(data5000.converge,data5000.converge$logL.1 + epsilon >= max(data5000.converge$logL.1,na.rm=T))
data100.global.num <- nrow(data100.global)
data1000.global.num <- nrow(data1000.global)
data5000.global.num <- nrow(data5000.global)
data100.converge.formelt <- data.frame(!is.na(data100.org$logL.1))
colnames(data100.converge.formelt) <- c('converge')
data100.converge.formelt$from <- rep('100',nrow(data100.org))
data1000.converge.formelt <- data.frame(!is.na(data1000.org$logL.1))
colnames(data1000.converge.formelt) <- c('converge')
data1000.converge.formelt$from <- rep('1000',nrow(data1000.org))
data5000.converge.formelt <- data.frame(!is.na(data5000.org$logL.1))
colnames(data5000.converge.formelt) <- c('converge')
data5000.converge.formelt$from <- rep('5000',nrow(data5000.org))
data.converge.formelt <- rbind(data100.converge.formelt, data1000.converge.formelt, data5000.converge.formelt)
data.converge.formelt$converge <- factor(data.converge.formelt$converge)
data.converge.formelt$from <- factor(data.converge.formelt$from)
summary(table(data.converge.formelt$from, data.converge.formelt$converge))
data100.global.formelt <- data.frame(data100.converge$logL.1 + epsilon >= max(data100.converge$logL.1,na.rm=T))
colnames(data100.global.formelt) <- c('global')
data100.global.formelt$from <- rep('100',nrow(data100.converge))
data1000.global.formelt <- data.frame(data1000.converge$logL.1 + epsilon >= max(data1000.converge$logL.1,na.rm=T))
colnames(data1000.global.formelt) <- c('global')
data1000.global.formelt$from <- rep('1000',nrow(data1000.converge))
data5000.global.formelt <- data.frame(data5000.converge$logL.1 + epsilon >= max(data5000.converge$logL.1,na.rm=T))
colnames(data5000.global.formelt) <- c('global')
data5000.global.formelt$from <- rep('5000',nrow(data5000.converge))
data.global.formelt <- rbind(data100.global.formelt, data1000.global.formelt, data5000.global.formelt)
data.global.formelt$global <- factor(data.global.formelt$global)
data.global.formelt$from <- factor(data.global.formelt$from)
summary(table(data.global.formelt$from, data.global.formelt$global)) | /EM_algorithm/data04/chi.R | no_license | templateaholic10/testrepo | R | false | false | 2,902 | r | epsilon <- 10e-4
data100.org <- read.csv('square100_initialtest01.csv')
data1000.org <- read.csv('square1000_initialtest01.csv')
data5000.org <- read.csv('square5000_initialtest01.csv')
data100.converge <- subset(data100.org,!is.na(data100.org$logL.1))
data1000.converge <- subset(data1000.org,!is.na(data1000.org$logL.1))
data5000.converge <- subset(data5000.org,!is.na(data5000.org$logL.1))
data100.converge.num <- nrow(data100.converge)
data1000.converge.num <- nrow(data1000.converge)
data5000.converge.num <- nrow(data5000.converge)
data100.global <- subset(data100.converge,data100.converge$logL.1 + epsilon >= max(data100.converge$logL.1,na.rm=T))
data1000.global <- subset(data1000.converge,data1000.converge$logL.1 + epsilon >= max(data1000.converge$logL.1,na.rm=T))
data5000.global <- subset(data5000.converge,data5000.converge$logL.1 + epsilon >= max(data5000.converge$logL.1,na.rm=T))
data100.global.num <- nrow(data100.global)
data1000.global.num <- nrow(data1000.global)
data5000.global.num <- nrow(data5000.global)
data100.converge.formelt <- data.frame(!is.na(data100.org$logL.1))
colnames(data100.converge.formelt) <- c('converge')
data100.converge.formelt$from <- rep('100',nrow(data100.org))
data1000.converge.formelt <- data.frame(!is.na(data1000.org$logL.1))
colnames(data1000.converge.formelt) <- c('converge')
data1000.converge.formelt$from <- rep('1000',nrow(data1000.org))
data5000.converge.formelt <- data.frame(!is.na(data5000.org$logL.1))
colnames(data5000.converge.formelt) <- c('converge')
data5000.converge.formelt$from <- rep('5000',nrow(data5000.org))
data.converge.formelt <- rbind(data100.converge.formelt, data1000.converge.formelt, data5000.converge.formelt)
data.converge.formelt$converge <- factor(data.converge.formelt$converge)
data.converge.formelt$from <- factor(data.converge.formelt$from)
summary(table(data.converge.formelt$from, data.converge.formelt$converge))
data100.global.formelt <- data.frame(data100.converge$logL.1 + epsilon >= max(data100.converge$logL.1,na.rm=T))
colnames(data100.global.formelt) <- c('global')
data100.global.formelt$from <- rep('100',nrow(data100.converge))
data1000.global.formelt <- data.frame(data1000.converge$logL.1 + epsilon >= max(data1000.converge$logL.1,na.rm=T))
colnames(data1000.global.formelt) <- c('global')
data1000.global.formelt$from <- rep('1000',nrow(data1000.converge))
data5000.global.formelt <- data.frame(data5000.converge$logL.1 + epsilon >= max(data5000.converge$logL.1,na.rm=T))
colnames(data5000.global.formelt) <- c('global')
data5000.global.formelt$from <- rep('5000',nrow(data5000.converge))
data.global.formelt <- rbind(data100.global.formelt, data1000.global.formelt, data5000.global.formelt)
data.global.formelt$global <- factor(data.global.formelt$global)
data.global.formelt$from <- factor(data.global.formelt$from)
summary(table(data.global.formelt$from, data.global.formelt$global)) |
\name{loclin}
\alias{loclin}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
Multivariate local linear regression estimator at one point
}
\description{
Computes the value of a multivariate local linear regression estimator
at one point.
}
\usage{
loclin(arg, x, y, h=1, kernel="gauss", type=0)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{arg}{d-vector; the point where the estimate is evaluated}
\item{x}{n*d data matrix; the matrix of the values of the explanatory variables}
\item{y}{n vector; the values of the response variable}
\item{h}{a positive real number; the smoothing parameter of the kernel estimate}
\item{kernel}{a character; determines the kernel function;
either "gauss" or "uniform"; in the univariate case can also be "exp"}
\item{type}{integer 0,...,d; if type=0, then the regression function is
estimated, otherwise the first partial derivative of the variable indicated
by type is estimated}
}
%\details{}
\value{a real number}
%\references{}
\author{Jussi Klemela}
%\note{ ~~further notes~~ }
\seealso{
\code{\link{pcf.loclin}},
}
\examples{
set.seed(1)
n<-100
d<-2
x<-8*matrix(runif(n*d),n,d)-3
C<-(2*pi)^(-d/2)
phi<-function(x){ return( C*exp(-sum(x^2)/2) ) }
D<-3; c1<-c(0,0); c2<-D*c(1,0); c3<-D*c(1/2,sqrt(3)/2)
func<-function(x){phi(x-c1)+phi(x-c2)+phi(x-c3)}
y<-matrix(0,n,1)
for (i in 1:n) y[i]<-func(x[i,])+0.01*rnorm(1)
arg<-c(0,0)
loclin(arg,x,y,h=0.5)
}
\keyword{multivariate}% at least one, from doc/KEYWORDS
\keyword{smooth}
| /man/loclin.Rd | no_license | cran/regpro | R | false | false | 1,547 | rd | \name{loclin}
\alias{loclin}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
Multivariate local linear regression estimator at one point
}
\description{
Computes the value of a multivariate local linear regression estimator
at one point.
}
\usage{
loclin(arg, x, y, h=1, kernel="gauss", type=0)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{arg}{d-vector; the point where the estimate is evaluated}
\item{x}{n*d data matrix; the matrix of the values of the explanatory variables}
\item{y}{n vector; the values of the response variable}
\item{h}{a positive real number; the smoothing parameter of the kernel estimate}
\item{kernel}{a character; determines the kernel function;
either "gauss" or "uniform"; in the univariate case can also be "exp"}
\item{type}{integer 0,...,d; if type=0, then the regression function is
estimated, otherwise the first partial derivative of the variable indicated
by type is estimated}
}
%\details{}
\value{a real number}
%\references{}
\author{Jussi Klemela}
%\note{ ~~further notes~~ }
\seealso{
\code{\link{pcf.loclin}},
}
\examples{
set.seed(1)
n<-100
d<-2
x<-8*matrix(runif(n*d),n,d)-3
C<-(2*pi)^(-d/2)
phi<-function(x){ return( C*exp(-sum(x^2)/2) ) }
D<-3; c1<-c(0,0); c2<-D*c(1,0); c3<-D*c(1/2,sqrt(3)/2)
func<-function(x){phi(x-c1)+phi(x-c2)+phi(x-c3)}
y<-matrix(0,n,1)
for (i in 1:n) y[i]<-func(x[i,])+0.01*rnorm(1)
arg<-c(0,0)
loclin(arg,x,y,h=0.5)
}
\keyword{multivariate}% at least one, from doc/KEYWORDS
\keyword{smooth}
|
# step 1
rm(swiss)
swiss = data.frame(swiss)
fit_full = lm(Fertility ~ ., data = swiss)
summary(fit_full)
fit_reduced1 = lm(Fertility ~ Examination + Education + Catholic
+ Infant.Mortality, data = swiss)
summary(fit_reduced1)
anova(fit_full,fit_reduced1)
fit_reduced2 = lm(Fertility ~ Agriculture + Education + Catholic
+ Infant.Mortality, data = swiss)
summary(fit_reduced2)
anova(fit_full, fit_reduced2)
# model selection
optimal_fit = step(fit_full, direction = 'backward')
# Problem 1
model_full <- lm(rating ~ ., data = attitude)
summary(model_full)
model_null <- lm(rating ~ 1, data = attitude)
summary(model_null)
scope = list(lower = model_null, upper = model_full)
ideal_model = step(model_null,scope, direction = "forward")
# Problem 2
anova(model_full,ideal_model)
# Problem 3
model <- lm(sr ~ .*., data = LifeCycleSavings)
summary(model)
| /Анализ данных в R/Статистика в R. Часть 2/3.3 Множественная линейная регрессия. Отбор моделей.R | no_license | IsmailovKamil/Stepik | R | false | false | 904 | r | # step 1
rm(swiss)
swiss = data.frame(swiss)
fit_full = lm(Fertility ~ ., data = swiss)
summary(fit_full)
fit_reduced1 = lm(Fertility ~ Examination + Education + Catholic
+ Infant.Mortality, data = swiss)
summary(fit_reduced1)
anova(fit_full,fit_reduced1)
fit_reduced2 = lm(Fertility ~ Agriculture + Education + Catholic
+ Infant.Mortality, data = swiss)
summary(fit_reduced2)
anova(fit_full, fit_reduced2)
# model selection
optimal_fit = step(fit_full, direction = 'backward')
# Problem 1
model_full <- lm(rating ~ ., data = attitude)
summary(model_full)
model_null <- lm(rating ~ 1, data = attitude)
summary(model_null)
scope = list(lower = model_null, upper = model_full)
ideal_model = step(model_null,scope, direction = "forward")
# Problem 2
anova(model_full,ideal_model)
# Problem 3
model <- lm(sr ~ .*., data = LifeCycleSavings)
summary(model)
|
library(C50)
hotel_bookings_data <- read.csv('/Users/ashutoshshanker/Desktop/Dataset_BI_Project/hotel_bookings_dataset.csv', na.strings=' NA')
summary(hotel_bookings_data)
sample_size = floor(0.8 * nrow(hotel_bookings_data))
training_adult = sample(nrow(hotel_bookings_data), size = sample_size)
train <- hotel_bookings_data[training_adult,]
test <- hotel_bookings_data[-training_adult,]
predictors <- c('lead_time', 'arrival_date_month','total_of_special_requests', 'required_car_parking_spaces', 'booking_changes','market_segment','previous_cancellations','adr','deposit_type','arrival_date_week_number')
train$is_canceled = as.factor(train$is_canceled)
str(train$is_canceled)
model <- C5.0.default(x = train[,predictors], y = train$is_canceled)
summary(model)
random_hotel_booking_pred <- predict(model, newdata = test)
hotel_booking_evaluation <- cbind(test, random_hotel_booking_pred)
head(hotel_booking_evaluation)
hotel_booking_evaluation$correct <- ifelse(hotel_booking_evaluation$is_canceled == hotel_booking_evaluation$random_hotel_booking_pred,1,0)
sum(hotel_booking_evaluation$correct)/nrow(hotel_booking_evaluation)
| /Hotel_Booking_Prediction.R | no_license | Abhilasha13/Hotel_Booking_Data | R | false | false | 1,135 | r | library(C50)
hotel_bookings_data <- read.csv('/Users/ashutoshshanker/Desktop/Dataset_BI_Project/hotel_bookings_dataset.csv', na.strings=' NA')
summary(hotel_bookings_data)
sample_size = floor(0.8 * nrow(hotel_bookings_data))
training_adult = sample(nrow(hotel_bookings_data), size = sample_size)
train <- hotel_bookings_data[training_adult,]
test <- hotel_bookings_data[-training_adult,]
predictors <- c('lead_time', 'arrival_date_month','total_of_special_requests', 'required_car_parking_spaces', 'booking_changes','market_segment','previous_cancellations','adr','deposit_type','arrival_date_week_number')
train$is_canceled = as.factor(train$is_canceled)
str(train$is_canceled)
model <- C5.0.default(x = train[,predictors], y = train$is_canceled)
summary(model)
random_hotel_booking_pred <- predict(model, newdata = test)
hotel_booking_evaluation <- cbind(test, random_hotel_booking_pred)
head(hotel_booking_evaluation)
hotel_booking_evaluation$correct <- ifelse(hotel_booking_evaluation$is_canceled == hotel_booking_evaluation$random_hotel_booking_pred,1,0)
sum(hotel_booking_evaluation$correct)/nrow(hotel_booking_evaluation)
|
#############################################################################################################
#### this function is to remove the lines for those with "" in either tess_err or ground_truth_err column ###
#############################################################################################################
remove_empty_line <- function(current_detect_output){
empty_index <- which(current_detect_output[,1] == "" | current_detect_output[,2] == "")
if (length(empty_index)>0){
current_detect_output <- current_detect_output[-empty_index,]
}
return(current_detect_output)
} | /lib/remove_empty_line.R | no_license | dreamiter/Fall2018-Project4-sec1-grp8 | R | false | false | 616 | r |
#############################################################################################################
#### this function is to remove the lines for those with "" in either tess_err or ground_truth_err column ###
#############################################################################################################
remove_empty_line <- function(current_detect_output){
empty_index <- which(current_detect_output[,1] == "" | current_detect_output[,2] == "")
if (length(empty_index)>0){
current_detect_output <- current_detect_output[-empty_index,]
}
return(current_detect_output)
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/PrometheeS4.R
\docType{methods}
\name{UpdateRPrometheeAlternatives,RPrometheeII-method}
\alias{UpdateRPrometheeAlternatives,RPrometheeII-method}
\title{UpdateRPrometheeAlternatives}
\usage{
\S4method{UpdateRPrometheeAlternatives}{RPrometheeII}(object, alternatives)
}
\arguments{
\item{object}{An object from a RPromethee class.}
\item{alternatives}{A character vector with the alternatives new names.}
}
\description{
Updates alternatives names from RPromethee objects.
}
| /man/UpdateRPrometheeAlternatives-RPrometheeII-method.Rd | no_license | lamfo-unb/RMCriteria | R | false | true | 552 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/PrometheeS4.R
\docType{methods}
\name{UpdateRPrometheeAlternatives,RPrometheeII-method}
\alias{UpdateRPrometheeAlternatives,RPrometheeII-method}
\title{UpdateRPrometheeAlternatives}
\usage{
\S4method{UpdateRPrometheeAlternatives}{RPrometheeII}(object, alternatives)
}
\arguments{
\item{object}{An object from a RPromethee class.}
\item{alternatives}{A character vector with the alternatives new names.}
}
\description{
Updates alternatives names from RPromethee objects.
}
|
% Generated by roxygen2 (4.0.2.9000): do not edit by hand
% Please edit documentation in R/get_source_expressions.R
\name{get_source_expressions}
\alias{get_source_expressions}
\title{Parsed sourced file from a filename}
\usage{
get_source_expressions(filename)
}
\arguments{
\item{filename}{the file to be parsed.}
}
\description{
This object is given as input to each linter
}
| /man/get_source_expressions.Rd | no_license | jjallaire/lintr | R | false | false | 380 | rd | % Generated by roxygen2 (4.0.2.9000): do not edit by hand
% Please edit documentation in R/get_source_expressions.R
\name{get_source_expressions}
\alias{get_source_expressions}
\title{Parsed sourced file from a filename}
\usage{
get_source_expressions(filename)
}
\arguments{
\item{filename}{the file to be parsed.}
}
\description{
This object is given as input to each linter
}
|
#Just an R file to automagically make the names of the audio files for Annelot :)
setwd("~/Dropbox/_Projects/PrimingMannerPath/MannerPathPriming")
items = read.csv("Experiment_Items_final.csv", header = TRUE, stringsAsFactors = FALSE)
#Add columns with the object for each critical video: original and train 1-3
items$ambigV <- as.character(items$ambigV)
items$trainV1 <- as.character(items$trainV1)
items$trainV2 <- as.character(items$trainV2)
items$trainV3 <- as.character(items$trainV3)
getObj <- function(mystring){
wordz = strsplit(mystring,'.',fixed = TRUE)
return(unlist(wordz)[3])
}
items$wordamb <- sapply(items$ambigV,getObj)
items$word1 <- sapply(items$trainV1,getObj)
items$word2 <- sapply(items$trainV2,getObj)
items$word3 <- sapply(items$trainV3,getObj)
#Now build the filenames!
items$cond <- 'manner'
items[items$Condition == 'Path',]$cond <- 'path'
items[items$Condition == 'Effect',]$cond <- 'path'
items$ambigAudioFuture <- paste(items$verbName, items$cond, 'future', items$wordamb, sep='_' )
items$ambigAudioPast <- paste(items$verbName, items$cond, 'past', items$wordamb, sep='_' )
items$trainAudioFuture1 <- paste(items$verbName, items$cond, 'future', items$word1, sep='_' )
items$trainAudioPast1 <- paste(items$verbName, items$cond, 'past', items$word1, sep='_' )
items$trainAudioFuture2 <- paste(items$verbName, items$cond, 'future', items$word2, sep='_' )
items$trainAudioPast2 <- paste(items$verbName, items$cond, 'past', items$word2, sep='_' )
items$trainAudioFuture3 <- paste(items$verbName, items$cond, 'future', items$word3, sep='_' )
items$trainAudioPast3 <- paste(items$verbName, items$cond, 'past', items$word3, sep='_' )
items$ambigAudioFuture <- paste(items$ambigAudioFuture, 'wav', sep='.' )
items$ambigAudioPast <- paste(items$ambigAudioPast, 'wav', sep='.' )
items$trainAudioFuture1 <- paste(items$trainAudioFuture1, 'wav', sep='.' )
items$trainAudioPast1 <- paste(items$trainAudioPast1, 'wav', sep='.' )
items$trainAudioFuture2 <- paste(items$trainAudioFuture2, 'wav', sep='.' )
items$trainAudioPast2 <- paste(items$trainAudioPast2, 'wav', sep='.' )
items$trainAudioFuture3 <- paste(items$trainAudioFuture3, 'wav', sep='.' )
items$trainAudioPast3 <- paste(items$trainAudioPast3, 'wav', sep='.' )
#Clean up the file a bit before saving it
items <- subset(items, select=-c(wordamb, word1, word2, word3, cond))
write.csv(items, "Experiment_Items_final_withaudio.csv")
#IMPORTANT NOTE: After export, we have to change/check one item: Birking-manner. In this item, there
#are 2 training trials with a spaceship object (around and into), so we'll manually rename those
#objects spaceship and spaceship2 and make sure audio files are named accordingly.
| /Old presentation versions/Old presentation versions, info from MP-NoExtend/EXTENSION/Audio_stimuli_creation/add_audio_filenames.R | no_license | mekline/MannerPathPriming | R | false | false | 2,699 | r | #Just an R file to automagically make the names of the audio files for Annelot :)
setwd("~/Dropbox/_Projects/PrimingMannerPath/MannerPathPriming")
items = read.csv("Experiment_Items_final.csv", header = TRUE, stringsAsFactors = FALSE)
#Add columns with the object for each critical video: original and train 1-3
items$ambigV <- as.character(items$ambigV)
items$trainV1 <- as.character(items$trainV1)
items$trainV2 <- as.character(items$trainV2)
items$trainV3 <- as.character(items$trainV3)
getObj <- function(mystring){
wordz = strsplit(mystring,'.',fixed = TRUE)
return(unlist(wordz)[3])
}
items$wordamb <- sapply(items$ambigV,getObj)
items$word1 <- sapply(items$trainV1,getObj)
items$word2 <- sapply(items$trainV2,getObj)
items$word3 <- sapply(items$trainV3,getObj)
#Now build the filenames!
items$cond <- 'manner'
items[items$Condition == 'Path',]$cond <- 'path'
items[items$Condition == 'Effect',]$cond <- 'path'
items$ambigAudioFuture <- paste(items$verbName, items$cond, 'future', items$wordamb, sep='_' )
items$ambigAudioPast <- paste(items$verbName, items$cond, 'past', items$wordamb, sep='_' )
items$trainAudioFuture1 <- paste(items$verbName, items$cond, 'future', items$word1, sep='_' )
items$trainAudioPast1 <- paste(items$verbName, items$cond, 'past', items$word1, sep='_' )
items$trainAudioFuture2 <- paste(items$verbName, items$cond, 'future', items$word2, sep='_' )
items$trainAudioPast2 <- paste(items$verbName, items$cond, 'past', items$word2, sep='_' )
items$trainAudioFuture3 <- paste(items$verbName, items$cond, 'future', items$word3, sep='_' )
items$trainAudioPast3 <- paste(items$verbName, items$cond, 'past', items$word3, sep='_' )
items$ambigAudioFuture <- paste(items$ambigAudioFuture, 'wav', sep='.' )
items$ambigAudioPast <- paste(items$ambigAudioPast, 'wav', sep='.' )
items$trainAudioFuture1 <- paste(items$trainAudioFuture1, 'wav', sep='.' )
items$trainAudioPast1 <- paste(items$trainAudioPast1, 'wav', sep='.' )
items$trainAudioFuture2 <- paste(items$trainAudioFuture2, 'wav', sep='.' )
items$trainAudioPast2 <- paste(items$trainAudioPast2, 'wav', sep='.' )
items$trainAudioFuture3 <- paste(items$trainAudioFuture3, 'wav', sep='.' )
items$trainAudioPast3 <- paste(items$trainAudioPast3, 'wav', sep='.' )
#Clean up the file a bit before saving it
items <- subset(items, select=-c(wordamb, word1, word2, word3, cond))
write.csv(items, "Experiment_Items_final_withaudio.csv")
#IMPORTANT NOTE: After export, we have to change/check one item: Birking-manner. In this item, there
#are 2 training trials with a spaceship object (around and into), so we'll manually rename those
#objects spaceship and spaceship2 and make sure audio files are named accordingly.
|
## run_analysis.R
setwd("C:/Users/allq2d/Coursera-Getting-and-Cleaning-Data")
## get and download the file
if(!dir.exists("./data")){dir.create("./data")}
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(fileUrl, destfile = "./data/Dataset.zip")
## unzip the file into the current directory
unzip("./data/Dataset.zip", exdir = ".")
## Merges the training and the test sets to create one data set.
## 1) load the library that have the needed functions
library(plyr)
library(dplyr)git
library(reshape2)
library(data.table)
## Read the labels and features data into data frames
## Fetures holds the column names
## ActivityLabels holds the activity names
activityLabels <- read.table("./UCI HAR Dataset/activity_labels.txt", quote = "\"")
features <- read.table("./UCI HAR Dataset/features.txt", quote = "\"")
## make sure these columns are character fields
activityLabels[,2] <- as.character(activityLabels[,2])
features[,2] <- as.character(features[,2])
## grab only the rows with titles for mean and standard deviation
subFeatures <- grep(".*mean.*|.*std.*", features[,2])
## get the values from the rows to be used as column names
FeatureLAbels <- features[subFeatures,2]
## Read the training and test data into data frames - X has the results,
## grab only the data where the columns are for mean and Standard deviation
XTrain <- read.table("UCI HAR Dataset/train/X_train.txt")[subFeatures]
XTest <- read.table("UCI HAR Dataset/test/X_test.txt")[subFeatures]
## Read the training and test data into data frames
## Y has the labels, Subject has the subjects
YTrain <- read.table("./UCI HAR Dataset/train/y_train.txt", quote = "\"")
YTest <- read.table("./UCI HAR Dataset/test/y_test.txt", quote = "\"")
SbjtTrain <- read.table("./UCI HAR Dataset/train/subject_train.txt", quote = "\"")
SbjtTest <- read.table("./UCI HAR Dataset/test/subject_test.txt", quote = "\"")
## Joing the results, labels, and subjects into a single data frame for training data
Train <- cbind(SbjtTrain, YTrain, XTrain)
colnames(Train) <- c("Subject","Activity",FeatureLAbels)
## Joing the results, labels, and subjects into a single data frame for test data
Test <- cbind(SbjtTest, YTest, XTest)
colnames(Test) <- c("Subject","Activity",FeatureLAbels)
## merge both tables
TrainTest <- rbind(Train, Test)
## Change the Subject and Activity values to Charater values to be used in the melt function
TrainTest$Activity <- factor(TrainTest$Activity, levels = activityLabels[,1], labels = activityLabels[,2])
TrainTest$Subject <- as.factor(TrainTest$Subject)
TrainTestMelt <- melt(TrainTest, id=c("Subject","Activity"))
dcast(TrainTestMelt, Subject + Activity ~ variable, fun=mean)
## Create a second independent tidy data set with the average of each
## variable for each activity and each subject.
write.table(TrainTestMean, "tidy.txt", row.names = FALSE, quote = FALSE)
| /run_analysis.R | no_license | jjnella08/Coursera-Getting-and-Cleaning-Data | R | false | false | 2,929 | r | ## run_analysis.R
setwd("C:/Users/allq2d/Coursera-Getting-and-Cleaning-Data")
## get and download the file
if(!dir.exists("./data")){dir.create("./data")}
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(fileUrl, destfile = "./data/Dataset.zip")
## unzip the file into the current directory
unzip("./data/Dataset.zip", exdir = ".")
## Merges the training and the test sets to create one data set.
## 1) load the library that have the needed functions
library(plyr)
library(dplyr)git
library(reshape2)
library(data.table)
## Read the labels and features data into data frames
## Fetures holds the column names
## ActivityLabels holds the activity names
activityLabels <- read.table("./UCI HAR Dataset/activity_labels.txt", quote = "\"")
features <- read.table("./UCI HAR Dataset/features.txt", quote = "\"")
## make sure these columns are character fields
activityLabels[,2] <- as.character(activityLabels[,2])
features[,2] <- as.character(features[,2])
## grab only the rows with titles for mean and standard deviation
subFeatures <- grep(".*mean.*|.*std.*", features[,2])
## get the values from the rows to be used as column names
FeatureLAbels <- features[subFeatures,2]
## Read the training and test data into data frames - X has the results,
## grab only the data where the columns are for mean and Standard deviation
XTrain <- read.table("UCI HAR Dataset/train/X_train.txt")[subFeatures]
XTest <- read.table("UCI HAR Dataset/test/X_test.txt")[subFeatures]
## Read the training and test data into data frames
## Y has the labels, Subject has the subjects
YTrain <- read.table("./UCI HAR Dataset/train/y_train.txt", quote = "\"")
YTest <- read.table("./UCI HAR Dataset/test/y_test.txt", quote = "\"")
SbjtTrain <- read.table("./UCI HAR Dataset/train/subject_train.txt", quote = "\"")
SbjtTest <- read.table("./UCI HAR Dataset/test/subject_test.txt", quote = "\"")
## Joing the results, labels, and subjects into a single data frame for training data
Train <- cbind(SbjtTrain, YTrain, XTrain)
colnames(Train) <- c("Subject","Activity",FeatureLAbels)
## Joing the results, labels, and subjects into a single data frame for test data
Test <- cbind(SbjtTest, YTest, XTest)
colnames(Test) <- c("Subject","Activity",FeatureLAbels)
## merge both tables
TrainTest <- rbind(Train, Test)
## Change the Subject and Activity values to Charater values to be used in the melt function
TrainTest$Activity <- factor(TrainTest$Activity, levels = activityLabels[,1], labels = activityLabels[,2])
TrainTest$Subject <- as.factor(TrainTest$Subject)
TrainTestMelt <- melt(TrainTest, id=c("Subject","Activity"))
dcast(TrainTestMelt, Subject + Activity ~ variable, fun=mean)
## Create a second independent tidy data set with the average of each
## variable for each activity and each subject.
write.table(TrainTestMean, "tidy.txt", row.names = FALSE, quote = FALSE)
|
#' create.dt - convert a Seurat or SingleCellExperiment to a data.table
#'
#' This function converts a Seurat or SingleCellExperiment object into a list containing a data.table, with vectors of gene and dimensionality reduction
#'
#' @param dat NO DEFAULT. A Seurat or SingleCellExperiment object.
#' @param from DEFAULT = NULL. By default, the class of object will be detected automatically, but this can be overwritten using from. Can be from = 'Seurat' or 'SingleCellExperiment'.
#'
#' @usage create.dt(dat, from)
#'
#' @author
#' Thomas M Ashhurst, \email{thomas.ashhurst@@sydney.edu.au}
#'
#' @references \url{https://github.com/ImmuneDynamics/Spectre}.
#'
#' @import data.table
#'
#' @export
create.dt <- function(dat,
from = NULL)
{
######################################################################################################
### Setup
######################################################################################################
### Packages
require('Spectre')
require('data.table')
### Demo data
# dat <- pbmc
# dat <- pbmc.sce
# from <- NULL
# dat <- Spectre::demo.asinh
# from <- NULL
#
# metadata <- data.frame(name=dimnames(dat)[[2]], desc=paste('column',dimnames(dat)[[2]],'from dataset'))
# dat.ff <- new("flowFrame",
# exprs=as.matrix(dat), # in order to create a flow frame, data needs to be read as matrix
# parameters=Biobase::AnnotatedDataFrame(metadata))
#
# head(flowCore::exprs(dat.ff))
# dat <- dat.ff
#
# rm(dat.ff)
# rm(metadata)
### Determine class of object
if(class(dat)[1] == 'Seurat'){
object.type <- "Seurat"
}
if(class(dat)[1] == 'SingleCellExperiment'){
object.type <- "SingleCellExperiment"
}
if(class(dat)[1] == 'flowFrame'){
object.type <- "flowFrame"
}
### Optional overview Overwrite
if(!is.null(from)){
object.type <- from
}
### Warning
if(!exists('object.type')){
stop("Could not determine the object type. Currently only Seurat objects are supported. You can also try manually specifying the object type using the 'from' argument (e.g. from = 'Seurat'")
}
######################################################################################################
### OPTION: Seurat objects
######################################################################################################
if(object.type == "Seurat"){
message(object.type, ' detected')
### Packages
require('dplyr')
require('Seurat')
require('patchwork')
### Extract
a <- GetAssayData(object = dat)
assays <- names(dat@assays)
dim.reds <- names(dat@reductions)
var.features <- VariableFeatures(dat)
if(length(var.features) > 0){
var.features.top10 <- head(VariableFeatures(dat), 10)
}
### Genes and cells
geneNames <- a@Dimnames[[1]]
cellNames <- a@Dimnames[[2]]
### Start data.table
res <- as.data.table(cellNames)
names(res) <- 'cellNames'
### Add metadata
if(!is.null(dat@meta.data)){
col.meta <- dat@meta.data
col.meta <- as.data.table(col.meta)
meta.cols <- names(col.meta)
res <- cbind(res, col.meta)
}
### Add data from slots
for(i in assays){
# i <- assays[[1]]
types <- vector()
if(ncol(dat@assays[[i]]@counts) > 0){
types <- c(types, 'counts')
x1 <- GetAssayData(object = dat, assay = i, slot = 'counts')
x1 <- as.data.table(x1)
x1 <- data.table::transpose(x1)
names(x1) <- geneNames
names(x1) <- paste0(names(x1), "_", i, "_", 'counts')
res <- cbind(res, x1)
}
if(ncol(dat@assays[[i]]@data) > 0){
types <- c(types, 'data')
x2 <- GetAssayData(object = dat, assay = i, slot = 'data')
x2 <- as.data.table(x2)
x2 <- data.table::transpose(x2)
names(x2) <- geneNames
names(x2) <- paste0(names(x2), "_", i, "_", 'data')
res <- cbind(res, x2)
}
if(ncol(dat@assays[[i]]@scale.data) > 0){
types <- c(types, 'scale.data')
x3 <- GetAssayData(object = dat, assay = i, slot = 'scale.data')
x3 <- as.data.table(x3)
x3 <- data.table::transpose(x3)
names(x3) <- geneNames
names(x3) <- paste0(names(x3), "_", i, "_", 'scale.data')
res <- cbind(res, x3)
}
rm(i)
rm(x1)
rm(x2)
rm(x3)
}
### Add dim reductions
for(i in dim.reds){
# i <- dim.reds[[2]]
tmp <- dat@reductions[[i]]@cell.embeddings
tmp <- as.data.table(tmp)
names(tmp) <- paste0(i, '_', names(tmp))
res <- cbind(res, tmp)
}
### Wrap up and return
final.res <- list()
final.res$data.table <- res
final.res$geneNames <- geneNames
final.res$cellNames <- cellNames
final.res$meta.data <- meta.cols
if(length(var.features) > 0){
final.res$var.features <- var.features
final.res$var.features.top10 <- var.features.top10
}
final.res$assays <- paste0('_', assays)
final.res$slots <- paste0('_', types)
final.res$dim.reds <- paste0(dim.reds, '_')
message(paste0("Converted a ", object.type, " object into a data.table stored in a list"))
return(final.res)
}
######################################################################################################
### OPTION: SingleCellExperiment
######################################################################################################
if(object.type == "SingleCellExperiment"){
message(object.type, ' detected')
### Packages
require('SingleCellExperiment')
###
geneNames <- rownames(dat) # genes
geneNames
cellNames <- colnames(dat) # cells
cellNames
###
assays <- names(dat@assays@data)
assays
dim.reds <- names(reducedDims(dat))
dim.reds
###
res <- as.data.table(cellNames)
names(res) <- 'cellNames'
### Add metadata
message('-- Adding metadata')
if(!is.null(dat@colData)){
col.meta <- dat@colData
col.meta <- as.data.table(col.meta)
meta.cols <- names(col.meta)
res <- cbind(res, col.meta)
res
}
### Assay data
message('-- Adding assay data')
for(i in assays){
# i <- assays[[1]]
tmp <- dat@assays@data[[i]]
tmp <- as.matrix(tmp)
# dim(tmp)
# colnames(tmp) # columns = cells
tmp <- as.data.table(tmp)
tmp <- data.table::transpose(tmp)
names(tmp) <- geneNames
names(tmp) <- paste0(names(tmp), "_", i)
res <- cbind(res, tmp)
rm(i)
rm(tmp)
}
### DimRed data
message('-- Adding DimRed data')
for(i in dim.reds){
# i <- dim.reds[[2]]
tmp <- reducedDims(dat)[[i]]
# dim(tmp)
# colnames(tmp) # columns = DRs
tmp <- as.data.table(tmp) # Dont transpose
new.names <- paste0(i, "_", c(1:length(names(tmp))))
names(tmp) <- new.names
res <- cbind(res, tmp)
rm(i)
rm(tmp)
}
### Wrap up and return
message('-- Finalising')
final.res <- list()
final.res$data.table <- res
final.res$geneNames <- geneNames
final.res$cellNames <- cellNames
final.res$meta.data <- meta.cols
final.res$assays <- paste0('_', assays)
final.res$dim.reds <- paste0(dim.reds, '_')
message(paste0("Converted a ", object.type, " object into a data.table stored in a list"))
return(final.res)
}
######################################################################################################
### OPTION: flowFrames
######################################################################################################
if(object.type == "flowFrame"){
message(object.type, ' detected')
### Packages
require('flowCore')
require('data.table')
### Extract 'exprs'
res <- exprs(dat)
res <- res[1:nrow(res),1:ncol(res)]
res <- as.data.table(res)
for(i in names(res)){
# i <- names(res)[1]
if(!any(is.na(as.numeric(as.character(res[[i]]))))){
res[[i]] <- as.numeric(res[[i]])
}
}
### Setup list
final.res <- list()
final.res$data.table <- res
final.res$parameters <- dat@parameters
final.res$description <- dat@description
### Return
message(paste0("Converted a ", object.type, " object into a data.table stored in a list"))
return(final.res)
}
}
| /R/create.dt.R | permissive | tyl868/Spectre | R | false | false | 10,839 | r | #' create.dt - convert a Seurat or SingleCellExperiment to a data.table
#'
#' This function converts a Seurat or SingleCellExperiment object into a list containing a data.table, with vectors of gene and dimensionality reduction
#'
#' @param dat NO DEFAULT. A Seurat or SingleCellExperiment object.
#' @param from DEFAULT = NULL. By default, the class of object will be detected automatically, but this can be overwritten using from. Can be from = 'Seurat' or 'SingleCellExperiment'.
#'
#' @usage create.dt(dat, from)
#'
#' @author
#' Thomas M Ashhurst, \email{thomas.ashhurst@@sydney.edu.au}
#'
#' @references \url{https://github.com/ImmuneDynamics/Spectre}.
#'
#' @import data.table
#'
#' @export
create.dt <- function(dat,
from = NULL)
{
######################################################################################################
### Setup
######################################################################################################
### Packages
require('Spectre')
require('data.table')
### Demo data
# dat <- pbmc
# dat <- pbmc.sce
# from <- NULL
# dat <- Spectre::demo.asinh
# from <- NULL
#
# metadata <- data.frame(name=dimnames(dat)[[2]], desc=paste('column',dimnames(dat)[[2]],'from dataset'))
# dat.ff <- new("flowFrame",
# exprs=as.matrix(dat), # in order to create a flow frame, data needs to be read as matrix
# parameters=Biobase::AnnotatedDataFrame(metadata))
#
# head(flowCore::exprs(dat.ff))
# dat <- dat.ff
#
# rm(dat.ff)
# rm(metadata)
### Determine class of object
if(class(dat)[1] == 'Seurat'){
object.type <- "Seurat"
}
if(class(dat)[1] == 'SingleCellExperiment'){
object.type <- "SingleCellExperiment"
}
if(class(dat)[1] == 'flowFrame'){
object.type <- "flowFrame"
}
### Optional overview Overwrite
if(!is.null(from)){
object.type <- from
}
### Warning
if(!exists('object.type')){
stop("Could not determine the object type. Currently only Seurat objects are supported. You can also try manually specifying the object type using the 'from' argument (e.g. from = 'Seurat'")
}
######################################################################################################
### OPTION: Seurat objects
######################################################################################################
if(object.type == "Seurat"){
message(object.type, ' detected')
### Packages
require('dplyr')
require('Seurat')
require('patchwork')
### Extract
a <- GetAssayData(object = dat)
assays <- names(dat@assays)
dim.reds <- names(dat@reductions)
var.features <- VariableFeatures(dat)
if(length(var.features) > 0){
var.features.top10 <- head(VariableFeatures(dat), 10)
}
### Genes and cells
geneNames <- a@Dimnames[[1]]
cellNames <- a@Dimnames[[2]]
### Start data.table
res <- as.data.table(cellNames)
names(res) <- 'cellNames'
### Add metadata
if(!is.null(dat@meta.data)){
col.meta <- dat@meta.data
col.meta <- as.data.table(col.meta)
meta.cols <- names(col.meta)
res <- cbind(res, col.meta)
}
### Add data from slots
for(i in assays){
# i <- assays[[1]]
types <- vector()
if(ncol(dat@assays[[i]]@counts) > 0){
types <- c(types, 'counts')
x1 <- GetAssayData(object = dat, assay = i, slot = 'counts')
x1 <- as.data.table(x1)
x1 <- data.table::transpose(x1)
names(x1) <- geneNames
names(x1) <- paste0(names(x1), "_", i, "_", 'counts')
res <- cbind(res, x1)
}
if(ncol(dat@assays[[i]]@data) > 0){
types <- c(types, 'data')
x2 <- GetAssayData(object = dat, assay = i, slot = 'data')
x2 <- as.data.table(x2)
x2 <- data.table::transpose(x2)
names(x2) <- geneNames
names(x2) <- paste0(names(x2), "_", i, "_", 'data')
res <- cbind(res, x2)
}
if(ncol(dat@assays[[i]]@scale.data) > 0){
types <- c(types, 'scale.data')
x3 <- GetAssayData(object = dat, assay = i, slot = 'scale.data')
x3 <- as.data.table(x3)
x3 <- data.table::transpose(x3)
names(x3) <- geneNames
names(x3) <- paste0(names(x3), "_", i, "_", 'scale.data')
res <- cbind(res, x3)
}
rm(i)
rm(x1)
rm(x2)
rm(x3)
}
### Add dim reductions
for(i in dim.reds){
# i <- dim.reds[[2]]
tmp <- dat@reductions[[i]]@cell.embeddings
tmp <- as.data.table(tmp)
names(tmp) <- paste0(i, '_', names(tmp))
res <- cbind(res, tmp)
}
### Wrap up and return
final.res <- list()
final.res$data.table <- res
final.res$geneNames <- geneNames
final.res$cellNames <- cellNames
final.res$meta.data <- meta.cols
if(length(var.features) > 0){
final.res$var.features <- var.features
final.res$var.features.top10 <- var.features.top10
}
final.res$assays <- paste0('_', assays)
final.res$slots <- paste0('_', types)
final.res$dim.reds <- paste0(dim.reds, '_')
message(paste0("Converted a ", object.type, " object into a data.table stored in a list"))
return(final.res)
}
######################################################################################################
### OPTION: SingleCellExperiment
######################################################################################################
if(object.type == "SingleCellExperiment"){
message(object.type, ' detected')
### Packages
require('SingleCellExperiment')
###
geneNames <- rownames(dat) # genes
geneNames
cellNames <- colnames(dat) # cells
cellNames
###
assays <- names(dat@assays@data)
assays
dim.reds <- names(reducedDims(dat))
dim.reds
###
res <- as.data.table(cellNames)
names(res) <- 'cellNames'
### Add metadata
message('-- Adding metadata')
if(!is.null(dat@colData)){
col.meta <- dat@colData
col.meta <- as.data.table(col.meta)
meta.cols <- names(col.meta)
res <- cbind(res, col.meta)
res
}
### Assay data
message('-- Adding assay data')
for(i in assays){
# i <- assays[[1]]
tmp <- dat@assays@data[[i]]
tmp <- as.matrix(tmp)
# dim(tmp)
# colnames(tmp) # columns = cells
tmp <- as.data.table(tmp)
tmp <- data.table::transpose(tmp)
names(tmp) <- geneNames
names(tmp) <- paste0(names(tmp), "_", i)
res <- cbind(res, tmp)
rm(i)
rm(tmp)
}
### DimRed data
message('-- Adding DimRed data')
for(i in dim.reds){
# i <- dim.reds[[2]]
tmp <- reducedDims(dat)[[i]]
# dim(tmp)
# colnames(tmp) # columns = DRs
tmp <- as.data.table(tmp) # Dont transpose
new.names <- paste0(i, "_", c(1:length(names(tmp))))
names(tmp) <- new.names
res <- cbind(res, tmp)
rm(i)
rm(tmp)
}
### Wrap up and return
message('-- Finalising')
final.res <- list()
final.res$data.table <- res
final.res$geneNames <- geneNames
final.res$cellNames <- cellNames
final.res$meta.data <- meta.cols
final.res$assays <- paste0('_', assays)
final.res$dim.reds <- paste0(dim.reds, '_')
message(paste0("Converted a ", object.type, " object into a data.table stored in a list"))
return(final.res)
}
######################################################################################################
### OPTION: flowFrames
######################################################################################################
if(object.type == "flowFrame"){
message(object.type, ' detected')
### Packages
require('flowCore')
require('data.table')
### Extract 'exprs'
res <- exprs(dat)
res <- res[1:nrow(res),1:ncol(res)]
res <- as.data.table(res)
for(i in names(res)){
# i <- names(res)[1]
if(!any(is.na(as.numeric(as.character(res[[i]]))))){
res[[i]] <- as.numeric(res[[i]])
}
}
### Setup list
final.res <- list()
final.res$data.table <- res
final.res$parameters <- dat@parameters
final.res$description <- dat@description
### Return
message(paste0("Converted a ", object.type, " object into a data.table stored in a list"))
return(final.res)
}
}
|
# making table data sets
library(dplyr)
library(tidyr)
library(MorpheusData)
#############benchmark 43
student <- read.table(text=
"S_key level age
S1 JR 18
S2 SR 24
S3 JR 21
S4 SR 22
S5 JR 18
S6 SO 20
S7 SO 22", header=T)
# write.csv(student, "sql/student.csv", row.names=FALSE)
# student <- read.csv("sql/student.csv", check.names = FALSE)
# fctr.cols <- sapply(student, is.factor)
# int.cols <- sapply(student, is.integer)
# student[, fctr.cols] <- sapply(student[, fctr.cols], as.character)
# student[, int.cols] <- sapply(student[, int.cols], as.numeric)
# save(student, file = "sql/student.rdata")
input=student
write.csv(input, "data-raw/s7_input1.csv", row.names=FALSE)
s7_input1 <- read.csv("data-raw/s7_input1.csv", check.names = FALSE)
fctr.cols <- sapply(s7_input1, is.factor)
int.cols <- sapply(s7_input1, is.integer)
s7_input1[, fctr.cols] <- sapply(s7_input1[, fctr.cols], as.character)
s7_input1[, int.cols] <- sapply(s7_input1[, int.cols], as.numeric)
save(s7_input1, file = "data/s7_input1.rdata")
output=input %>% group_by(level) %>% summarize(average=mean(age))
write.csv(output, "data-raw/s7_output1.csv", row.names=FALSE)
s7_output1 <- read.csv("data-raw/s7_output1.csv", check.names = FALSE)
fctr.cols <- sapply(s7_output1, is.factor)
int.cols <- sapply(s7_output1, is.integer)
s7_output1[, fctr.cols] <- sapply(s7_output1[, fctr.cols], as.character)
s7_output1[, int.cols] <- sapply(s7_output1[, int.cols], as.numeric)
save(s7_output1, file = "data/s7_output1.rdata")
# 5.1.7
student %>% group_by(level) %>% summarize(average=mean(age)) | /S7.R | permissive | boyland-pf/MorpheusData | R | false | false | 1,568 | r | # making table data sets
library(dplyr)
library(tidyr)
library(MorpheusData)
#############benchmark 43
student <- read.table(text=
"S_key level age
S1 JR 18
S2 SR 24
S3 JR 21
S4 SR 22
S5 JR 18
S6 SO 20
S7 SO 22", header=T)
# write.csv(student, "sql/student.csv", row.names=FALSE)
# student <- read.csv("sql/student.csv", check.names = FALSE)
# fctr.cols <- sapply(student, is.factor)
# int.cols <- sapply(student, is.integer)
# student[, fctr.cols] <- sapply(student[, fctr.cols], as.character)
# student[, int.cols] <- sapply(student[, int.cols], as.numeric)
# save(student, file = "sql/student.rdata")
input=student
write.csv(input, "data-raw/s7_input1.csv", row.names=FALSE)
s7_input1 <- read.csv("data-raw/s7_input1.csv", check.names = FALSE)
fctr.cols <- sapply(s7_input1, is.factor)
int.cols <- sapply(s7_input1, is.integer)
s7_input1[, fctr.cols] <- sapply(s7_input1[, fctr.cols], as.character)
s7_input1[, int.cols] <- sapply(s7_input1[, int.cols], as.numeric)
save(s7_input1, file = "data/s7_input1.rdata")
output=input %>% group_by(level) %>% summarize(average=mean(age))
write.csv(output, "data-raw/s7_output1.csv", row.names=FALSE)
s7_output1 <- read.csv("data-raw/s7_output1.csv", check.names = FALSE)
fctr.cols <- sapply(s7_output1, is.factor)
int.cols <- sapply(s7_output1, is.integer)
s7_output1[, fctr.cols] <- sapply(s7_output1[, fctr.cols], as.character)
s7_output1[, int.cols] <- sapply(s7_output1[, int.cols], as.numeric)
save(s7_output1, file = "data/s7_output1.rdata")
# 5.1.7
student %>% group_by(level) %>% summarize(average=mean(age)) |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/themes.R
\name{themes_rop}
\alias{theme_rop_traj}
\alias{theme_rop_polarplot}
\alias{theme_rop_radar}
\alias{theme_rop_windrose}
\alias{theme_rop_diuarnal}
\title{themes for rOstluft plots}
\usage{
theme_rop_traj(base = ggplot2::theme_minimal())
theme_rop_polarplot(base = ggplot2::theme_minimal())
theme_rop_radar(base = ggplot2::theme_minimal())
theme_rop_windrose(base = ggplot2::theme_minimal())
theme_rop_diuarnal(base = ggplot2::theme_classic())
}
\arguments{
\item{base}{a ggplot2 theme. see \link[ggplot2:ggtheme]{ggplot2::ggtheme}}
}
\description{
this themes are used in the respective gg wrapper to apply some
basic theming.
}
\examples{
library(ggplot2)
fn <- rOstluft.data::f("Zch_Stampfenbachstrasse_2010-2014.csv")
data <- rOstluft::read_airmo_csv(fn)
data <- rOstluft::rolf_to_openair(data)
data <- dplyr::mutate(data, year = lubridate::year(date))
data_summarized <- summary_wind(data, ws, wd, ws,
ws_cutfun = cut_ws.fun(ws_max = 4, reverse = TRUE)
)
p <- ggplot(data_summarized, aes(x = wd, y = freq, fill = ws)) +
geom_bar(stat = "identity") +
coord_polar2(start = - 22.5 / 180 * pi ) +
scale_y_continuous(
limits = c(0, NA),
expand = c(0,0, 0, 0),
labels = scales::percent
) +
scale_fill_viridis_d()
# default appearance
p
# with rOstluft theming for a windrose
p + theme_rop_windrose()
# prefer bw as base and a bigger font for a presentation
p + theme_rop_windrose(
theme_bw(base_size = 14)
)
}
| /man/themes_rop.Rd | permissive | Ostluft/rOstluft.plot | R | false | true | 1,531 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/themes.R
\name{themes_rop}
\alias{theme_rop_traj}
\alias{theme_rop_polarplot}
\alias{theme_rop_radar}
\alias{theme_rop_windrose}
\alias{theme_rop_diuarnal}
\title{themes for rOstluft plots}
\usage{
theme_rop_traj(base = ggplot2::theme_minimal())
theme_rop_polarplot(base = ggplot2::theme_minimal())
theme_rop_radar(base = ggplot2::theme_minimal())
theme_rop_windrose(base = ggplot2::theme_minimal())
theme_rop_diuarnal(base = ggplot2::theme_classic())
}
\arguments{
\item{base}{a ggplot2 theme. see \link[ggplot2:ggtheme]{ggplot2::ggtheme}}
}
\description{
this themes are used in the respective gg wrapper to apply some
basic theming.
}
\examples{
library(ggplot2)
fn <- rOstluft.data::f("Zch_Stampfenbachstrasse_2010-2014.csv")
data <- rOstluft::read_airmo_csv(fn)
data <- rOstluft::rolf_to_openair(data)
data <- dplyr::mutate(data, year = lubridate::year(date))
data_summarized <- summary_wind(data, ws, wd, ws,
ws_cutfun = cut_ws.fun(ws_max = 4, reverse = TRUE)
)
p <- ggplot(data_summarized, aes(x = wd, y = freq, fill = ws)) +
geom_bar(stat = "identity") +
coord_polar2(start = - 22.5 / 180 * pi ) +
scale_y_continuous(
limits = c(0, NA),
expand = c(0,0, 0, 0),
labels = scales::percent
) +
scale_fill_viridis_d()
# default appearance
p
# with rOstluft theming for a windrose
p + theme_rop_windrose()
# prefer bw as base and a bigger font for a presentation
p + theme_rop_windrose(
theme_bw(base_size = 14)
)
}
|
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(ggplot2)
data<- read.csv("http://cs.newpaltz.edu/~easwaran/DA/Data/sample.csv")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Exploring Different Numbers of Bins in Histograms"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 10,
max = 300,
value = 20)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
ggplot(data, aes(v))+geom_histogram(bins=input$bins, col="white", fill="red")
})
}
# Run the application
shinyApp(ui = ui, server = server)
| /app.R | no_license | cveaswaran/shinyapps | R | false | false | 1,170 | r | #
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(ggplot2)
data<- read.csv("http://cs.newpaltz.edu/~easwaran/DA/Data/sample.csv")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Exploring Different Numbers of Bins in Histograms"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 10,
max = 300,
value = 20)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
ggplot(data, aes(v))+geom_histogram(bins=input$bins, col="white", fill="red")
})
}
# Run the application
shinyApp(ui = ui, server = server)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ForecastService.R
\name{dfp_getAvailabilityForecast}
\alias{dfp_getAvailabilityForecast}
\title{ForecastService}
\usage{
dfp_getAvailabilityForecast(request_data, as_df = TRUE,
verbose = FALSE)
}
\arguments{
\item{request_data}{a \code{list} or \code{data.frame} of data elements
to be formatted for a SOAP
request (XML format, but passed as character string)}
\item{as_df}{a boolean indicating whether to attempt to parse the result into
a \code{data.frame}}
\item{verbose}{a boolean indicating whether to print the service URL and POSTed XML}
}
\value{
a \code{data.frame} or \code{list} containing all the elements of a getAvailabilityForecastResponse
}
\description{
Provides methods for estimating traffic (clicks/impressions) for line
items. Forecasts can be provided for LineItem objects that exist in the
system or which have not had an ID set yet.
}
\details{
Test Network Behavior
Test networks are unable to provide forecasts that would be comparable
to the production environment because forecasts require traffic history.
Visit the See Also section below to proceed to Google and review the details.'
getAvailabilityForecast
Gets the availability forecast for a ProspectiveLineItem.
An availability forecast reports the maximum number of available
units that the line item can book, and the total number of units
matching the line item's targeting.
}
\examples{
\dontrun{
filter <- "WHERE Status='DELIVERING' LIMIT 1"
one_li <- dfp_getLineItemsByStatement(list(filterStatement=list(query=filter)))[[1]]
hypothetical_line_item <- list(lineItem=
list(id=one_li$id,
startDateTime=one_li$startDateTime,
endDateTime=dfp_date_to_list(Sys.Date()+100),
lineItemType=one_li$lineItemType,
costType=one_li$costType,
primaryGoal=one_li$primaryGoal,
targeting=one_li$targeting))
request_data <- list(lineItem=hypothetical_line_item,
forecastOptions=list(includeTargetingCriteriaBreakdown='true',
includeContendingLineItems='true'))
dfp_getAvailabilityForecast_result <- dfp_getAvailabilityForecast(request_data)
}
}
\seealso{
\href{https://developers.google.com/ad-manager/api/reference/v201905/ForecastService#getAvailabilityForecast}{Google Documentation for getAvailabilityForecast}
}
| /man/dfp_getAvailabilityForecast.Rd | no_license | StevenMMortimer/rdfp | R | false | true | 2,591 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ForecastService.R
\name{dfp_getAvailabilityForecast}
\alias{dfp_getAvailabilityForecast}
\title{ForecastService}
\usage{
dfp_getAvailabilityForecast(request_data, as_df = TRUE,
verbose = FALSE)
}
\arguments{
\item{request_data}{a \code{list} or \code{data.frame} of data elements
to be formatted for a SOAP
request (XML format, but passed as character string)}
\item{as_df}{a boolean indicating whether to attempt to parse the result into
a \code{data.frame}}
\item{verbose}{a boolean indicating whether to print the service URL and POSTed XML}
}
\value{
a \code{data.frame} or \code{list} containing all the elements of a getAvailabilityForecastResponse
}
\description{
Provides methods for estimating traffic (clicks/impressions) for line
items. Forecasts can be provided for LineItem objects that exist in the
system or which have not had an ID set yet.
}
\details{
Test Network Behavior
Test networks are unable to provide forecasts that would be comparable
to the production environment because forecasts require traffic history.
Visit the See Also section below to proceed to Google and review the details.'
getAvailabilityForecast
Gets the availability forecast for a ProspectiveLineItem.
An availability forecast reports the maximum number of available
units that the line item can book, and the total number of units
matching the line item's targeting.
}
\examples{
\dontrun{
filter <- "WHERE Status='DELIVERING' LIMIT 1"
one_li <- dfp_getLineItemsByStatement(list(filterStatement=list(query=filter)))[[1]]
hypothetical_line_item <- list(lineItem=
list(id=one_li$id,
startDateTime=one_li$startDateTime,
endDateTime=dfp_date_to_list(Sys.Date()+100),
lineItemType=one_li$lineItemType,
costType=one_li$costType,
primaryGoal=one_li$primaryGoal,
targeting=one_li$targeting))
request_data <- list(lineItem=hypothetical_line_item,
forecastOptions=list(includeTargetingCriteriaBreakdown='true',
includeContendingLineItems='true'))
dfp_getAvailabilityForecast_result <- dfp_getAvailabilityForecast(request_data)
}
}
\seealso{
\href{https://developers.google.com/ad-manager/api/reference/v201905/ForecastService#getAvailabilityForecast}{Google Documentation for getAvailabilityForecast}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.