{"text": "\r\n#Suppose the food label on a cookie bag states that there is at most 2 grams\r\n#of saturated fat in a single cookie. In a sample of 35 cookies, it is\r\n#found that the mean amount of saturated fat per cookie is 2.1 grams. \r\n#Assume that the sample standard deviation is 0.3 gram. At .05 significance\r\n#level, can we reject the claim on food label?\r\n\r\n\r\nxbar = 2.1\r\nmu0 = 2\r\n\r\ns = 0.3\r\n\r\nn = 35\r\n\r\nt = (xbar-mu0)/(s/(sqrt(n)))\r\n\r\nt #1.9720\r\n\r\nalpha = 0.05\r\n\r\n#Valores criticos\r\nt.alpha = qt(1-alpha,df = n-1)\r\n\r\n#rechazamos la hipotesis\r\nt.alpha #1.6991\r\n\r\n\r\npval = pt(t,df=n-1,lower.tail = FALSE)", "meta": {"hexsha": "bee09783a726a915392775ef4b58787d7c822a2e", "size": 596, "ext": "r", "lang": "R", "max_stars_repo_path": "Parcial/1. Prueba de hipotesis/UpperTailMeanUnknownVariance.r", "max_stars_repo_name": "jchudb93/Exp-Numerica", "max_stars_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Parcial/1. Prueba de hipotesis/UpperTailMeanUnknownVariance.r", "max_issues_repo_name": "jchudb93/Exp-Numerica", "max_issues_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Parcial/1. Prueba de hipotesis/UpperTailMeanUnknownVariance.r", "max_forks_repo_name": "jchudb93/Exp-Numerica", "max_forks_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5517241379, "max_line_length": 77, "alphanum_fraction": 0.6644295302, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885302, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7499895461593258}} {"text": "# Declaration of variables with raw data\nrawData <- c(33, 24, 17, 26)\navoidanceRawData <- c(\"Avoidance behaviour\", \"No avoidance behaviour\")\nparasitedRawData <- c(\"Unparasitised\", \"Parasitised\")\n\n# Creation of 2*2 matrix using rownames() and colnames()\nmatrixAvoidanceBehaviourRates <- matrix(rawData, ncol=2, nrow=2, byrow=\"TRUE\")\nrownames(matrixAvoidanceBehaviourRates) <- avoidanceRawData\ncolnames(matrixAvoidanceBehaviourRates) <- parasitedRawData\n\n# Draw a barplot using barplot() include a legend with legend()\nbarplot(matrixAvoidanceBehaviourRates,\nmain = \"Fish Parasitism and Predator Avoidance\",\nxlab = \"Fish Parasitism\",\nylab = \"Number of fish\",\ncol = c(\"red\",\"blue\")\n)\n\nlegend('topleft',\nlegend = avoidanceRawData,\ntitle = \"Predator Avoidance\",\nfill = c(\"red\",\"blue\"),\nbg = c(\"white\")\n)\n\n# Carry out a chi square test for independence of data using chisq.test()\nchisq <- chisq.test(matrixAvoidanceBehaviourRates)\n\nchisq\n# Pearson's Chi-squared test with Yates' continuity correction executed\n# RESULT => X-squared = 2.6112, df = 1, p-value = 0.1061\n# What is a null hypothesis? \n# What are the assumptions behind a chi square test? Do your data meet them?\n# What does the statistical test tell you?", "meta": {"hexsha": "bfcb1f492d84d8b03acdbc688ec671d3b8edb1c3", "size": 1209, "ext": "r", "lang": "R", "max_stars_repo_path": "fishParasitismandPredatorAvoidance/fishParasitismandPredatorAvoidance.r", "max_stars_repo_name": "cortesana/ABitOfR", "max_stars_repo_head_hexsha": "7752cb645b53168356b446b7147af23fbfede4fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-08T17:37:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-08T17:37:59.000Z", "max_issues_repo_path": "fishParasitismandPredatorAvoidance/fishParasitismandPredatorAvoidance.r", "max_issues_repo_name": "cortesana/aBitOfR", "max_issues_repo_head_hexsha": "7752cb645b53168356b446b7147af23fbfede4fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fishParasitismandPredatorAvoidance/fishParasitismandPredatorAvoidance.r", "max_forks_repo_name": "cortesana/aBitOfR", "max_forks_repo_head_hexsha": "7752cb645b53168356b446b7147af23fbfede4fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5588235294, "max_line_length": 78, "alphanum_fraction": 0.7510339123, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679977, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.749963253082841}} {"text": "M <- 1E6\ntheta.samp.1 <- rnorm(M, mean = 0, sd = sqrt(2.19))\ntheta.samp.2 <- rcauchy(M)\n\npredictive.X1 <- rnorm(M, mean = theta.samp.1, sd = 1)\npredictive.X2 <- rnorm(M, mean = theta.samp.2, sd = 1)\n\n\nlibrary(ggplot2)\n\nforplot <- data.frame(x_pred = c(predictive.X1, predictive.X2),\n prior = rep(c(\"Normal\", \"Cauchy\"), each = M))\n\np0 <- ggplot(forplot,\n aes(x = x_pred, colour = prior, fill = prior)) +\n geom_density(alpha = .4) +\n scale_x_continuous(expression(x[pred]), limits = c(-10, 10)) +\n scale_y_continuous(\"Density\", expand = c(0, 0)) +\n theme_bw(base_size = 16) + \n geom_vline(xintercept = c(-4, 4), linetype = \"longdash\") + \n theme(legend.position = \"bottom\",\n legend.justification = \"centre\",\n legend.title = element_blank(),\n strip.background = element_blank(),\n strip.text.y = element_blank(),\n legend.margin = margin(0, 0, 0, 0),\n legend.box.margin = margin(0, 0, 0, 0))\n\np0\n\nggsave(plot = p0, filename = \"../slides/figures/BC_example_326.pdf\")\n\n#### Second part: inference\n## First let's generate some data\n\nN <- 3\ntrue_theta <- -20\nX <- rnorm(n = N, mean = true_theta, sd = 1)\n\n## Now let's fit the model under both priors\nlibrary(cmdstanr)\nlibrary(rstan)\nstanfit <- function(fit) rstan::read_stan_csv(fit$output_files())\n\nexample_326 <- cmdstanr::cmdstan_model(\"stan/BC_example_326.stan\")\n\nstan.data <- list(N = N, x = X, prior = 1)\nfit.normal <- stanfit(example_326$sample(data = stan.data, refresh = 0))\nstan.data$prior <- 2\nfit.cauchy <- stanfit(example_326$sample(data = stan.data, refresh = 0))\n \ntheta.df <- data.frame(\n theta = c(extract(fit.normal, 'theta')$theta,\n extract(fit.cauchy, 'theta')$theta)\n)\ntheta.df$prior <- rep(c(\"Normal\", \"Cauchy\"), each = nrow(theta.df)/2)\n\n## Compare posteriors\np1 <- ggplot(theta.df,\n aes(x = theta, colour = prior, fill = prior)) +\n geom_density(alpha = .4) +\n scale_x_continuous(expression(theta)) +\n scale_y_continuous(\"Density\", expand = c(0, 0)) +\n theme_bw(base_size = 16) + \n theme(legend.position = \"bottom\",\n legend.justification = \"centre\",\n legend.title = element_blank(),\n strip.background = element_blank(),\n strip.text.y = element_blank(),\n legend.margin = margin(0, 0, 0, 0),\n legend.box.margin = margin(0, 0, 0, 0))\np1\n\n## Compare posterior predictives\npred.df <- data.frame(\n x_pred = c(as.vector(extract(fit.normal, 'x_pred')$x_pred),\n as.vector(extract(fit.cauchy, 'x_pred')$x_pred))\n)\npred.df$prior <- rep(c(\"Normal\", \"Cauchy\"), each = nrow(pred.df)/2)\n\n\np2 <- ggplot(pred.df,\n aes(x = x_pred, colour = prior, fill = prior)) +\n geom_density(alpha = .4) +\n scale_x_continuous(expression(x[pred])) +\n scale_y_continuous(\"Density\", expand = c(0, 0)) +\n theme_bw(base_size = 16) + \n # geom_vline(xintercept = c(-4, 4), linetype = \"longdash\") + \n theme(legend.position = \"bottom\",\n legend.justification = \"centre\",\n legend.title = element_blank(),\n strip.background = element_blank(),\n strip.text.y = element_blank(),\n legend.margin = margin(0, 0, 0, 0),\n legend.box.margin = margin(0, 0, 0, 0))\n\np2\n", "meta": {"hexsha": "a5bccffd36c4d7180fda7d61aaf400c6e8124eef", "size": 3218, "ext": "r", "lang": "R", "max_stars_repo_path": "code/normal_vs_cauchy_BC_ex326.r", "max_stars_repo_name": "lucasmoschen/BayesianStatisticsCourse", "max_stars_repo_head_hexsha": "79fe17dd71fa9638ae4865c8e75eeb0f814d2ccb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-03-17T17:39:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T23:40:56.000Z", "max_issues_repo_path": "code/normal_vs_cauchy_BC_ex326.r", "max_issues_repo_name": "anhnguyendepocen/BayesianStatisticsCourse", "max_issues_repo_head_hexsha": "79fe17dd71fa9638ae4865c8e75eeb0f814d2ccb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-03-24T01:28:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T20:49:10.000Z", "max_forks_repo_path": "code/normal_vs_cauchy_BC_ex326.r", "max_forks_repo_name": "anhnguyendepocen/BayesianStatisticsCourse", "max_forks_repo_head_hexsha": "79fe17dd71fa9638ae4865c8e75eeb0f814d2ccb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-05-26T16:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:33:26.000Z", "avg_line_length": 32.8367346939, "max_line_length": 72, "alphanum_fraction": 0.6224362958, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.7499632458798101}} {"text": "# variable y with normal distribution N(??, ??), where ??=70 and ?? = 13\r\n# the probability that a measurement will be less than 60 is given by \r\npnorm(60,mean =70,sd=13)\r\n# probability that a randomly selected vehicle will have emission levels greater than 90 ppb\r\npnorm(90,mean =70,sd=13,lower.tail = FALSE)\r\n# the probability that a randomly selected vehicle will have emission levels between 60 and 90 ppb\r\npnorm(90,mean =70,sd=13)-pnorm(60,mean =70,sd=13)\r\n\r\n", "meta": {"hexsha": "427cc63f00a7384c9f399e0ae1874e2377a5ac37", "size": 467, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.17/Ex4_17.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.17/Ex4_17.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.17/Ex4_17.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 51.8888888889, "max_line_length": 99, "alphanum_fraction": 0.7259100642, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7497219897274611}} {"text": "#!/usr/bin/Rscript\n# Copyright © 2016 Martin Ueding \n# Licensed under the MIT license.\n\npdf = function(x) {\n 1 / (pi * (1 + x^2))\n}\n\ninverse_cdf = function(u) {\n tan(pi * (u - 1/2))\n}\n\nbin_count = 50\nsamples_count = 100000\n\n###############################################################################\n# Inverse Function Method #\n###############################################################################\n\n# Plot the original function.\nx_orig = seq(-5, 5, length.out=200)\ny_orig = pdf(x_orig)\nplot(x_orig, y_orig, type='l', main='Original PDF', xlab='x', ylab='y')\n\n# Plot the inverse function.\nu_inv_cdf = seq(0.02, 0.98, length.out=100)\nx_inv_cdf = inverse_cdf(u_inv_cdf)\nplot(u_inv_cdf, x_inv_cdf, type='l', main='Inverse CDF', xlab='u', ylab='x')\n\n# Sample from uniform and transform it.\nstart = proc.time()\nu = runif(samples_count)\nx = inverse_cdf(u)\nend = proc.time()\nduration_inverse_cdf = end - start\ncat('Time for Inverse Function:', duration_inverse_cdf, '\\n')\n\n# There is a complication that the resulting values span the whole real\n# numbers. We cannot sensibly display that in a histogram. Therefore we need to\n# limit the histogram. Just using `xlim` here does not suffice; it would just\n# adjust the plotting window. We want to have the bins focussed in a sensible\n# interval. R would complain if the bins do not cover all the values, so we\n# need to select the interesting values as well.\nselection = -5 < x & x < 5\nhist(x[selection], breaks=seq(-5, 5, length.out=bin_count), freq=FALSE,\n main='Sampling with Inverse Function Method')\n\n# By not using all data points, we effectively have sampled a different pdf.\n# This means that the normalization is off, we need to correct for that.\nfactor = samples_count / sum(selection)\nlines(x_orig, y_orig * factor, col='red')\n\n###############################################################################\n# Ratio Method #\n###############################################################################\n\nstart = proc.time()\nx = rnorm(samples_count)\ny = rnorm(samples_count)\nz = x / y\nend = proc.time()\nduration_inverse_cdf = end - start\ncat('Time for Ratio:', duration_inverse_cdf, '\\n')\n\nselection = -5 < z & z < 5\nhist(z[selection], breaks=seq(-5, 5, length.out=bin_count), freq=FALSE,\n main='Sampling with Ratio Method')\n\nfactor = samples_count / sum(selection)\nlines(x_orig, y_orig * factor, col='red')\n", "meta": {"hexsha": "3df221c8454bf7fdb9096bf246b2615e63f3e082", "size": 2524, "ext": "r", "lang": "R", "max_stars_repo_path": "03/R/2-cauchy.r", "max_stars_repo_name": "martin-ueding/exercides-2016", "max_stars_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03/R/2-cauchy.r", "max_issues_repo_name": "martin-ueding/exercides-2016", "max_issues_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03/R/2-cauchy.r", "max_forks_repo_name": "martin-ueding/exercides-2016", "max_forks_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5492957746, "max_line_length": 79, "alphanum_fraction": 0.587955626, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7496368055559859}} {"text": "##### Chapter 5: Classification using Decision Trees and Rules -------------------\n\n#### Part 1: Decision Trees -------------------\n\n## Understanding Decision Trees ----\n# calculate entropy of a two-class segment\n-0.60 * log2(0.60) - 0.40 * log2(0.40)\n\ncurve(-x * log2(x) - (1 - x) * log2(1 - x),\n col = \"red\", xlab = \"x\", ylab = \"Entropy\", lwd = 4)\n\n## Example: Identifying Risky Bank Loans ----\n## Step 2: Exploring and preparing the data ----\ncredit <- read.csv(\"credit.csv\")\nstr(credit)\n\n# look at two characteristics of the applicant\ntable(credit$checking_balance)\ntable(credit$savings_balance)\n\n# look at two characteristics of the loan\nsummary(credit$months_loan_duration)\nsummary(credit$amount)\n\n# look at the class variable\ntable(credit$default)\n\n# create a random sample for training and test data\n# use set.seed to use the same random number sequence as the tutorial\nset.seed(123)\ntrain_sample <- sample(1000, 900)\n\nstr(train_sample)\n\n# split the data frames\ncredit_train <- credit[train_sample, ]\ncredit_test <- credit[-train_sample, ]\n\n# check the proportion of class variable\nprop.table(table(credit_train$default))\nprop.table(table(credit_test$default))\n\n## Step 3: Training a model on the data ----\n# build the simplest decision tree\nlibrary(C50)\ncredit_model <- C5.0(credit_train[-17], credit_train$default)\n\n# display simple facts about the tree\ncredit_model\n\n# display detailed information about the tree\nsummary(credit_model)\n\n## Step 4: Evaluating model performance ----\n# create a factor vector of predictions on test data\ncredit_pred <- predict(credit_model, credit_test)\n\n# cross tabulation of predicted versus actual classes\nlibrary(gmodels)\nCrossTable(credit_test$default, credit_pred,\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\n dnn = c('actual default', 'predicted default'))\n\n## Step 5: Improving model performance ----\n\n## Boosting the accuracy of decision trees\n# boosted decision tree with 10 trials\ncredit_boost10 <- C5.0(credit_train[-17], credit_train$default,\n trials = 10)\ncredit_boost10\nsummary(credit_boost10)\n\ncredit_boost_pred10 <- predict(credit_boost10, credit_test)\nCrossTable(credit_test$default, credit_boost_pred10,\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\n dnn = c('actual default', 'predicted default'))\n\n## Making some mistakes more costly than others\n\n# create dimensions for a cost matrix\nmatrix_dimensions <- list(c(\"no\", \"yes\"), c(\"no\", \"yes\"))\nnames(matrix_dimensions) <- c(\"predicted\", \"actual\")\nmatrix_dimensions\n\n# build the matrix\nerror_cost <- matrix(c(0, 1, 4, 0), nrow = 2, dimnames = matrix_dimensions)\nerror_cost\n\n# apply the cost matrix to the tree\ncredit_cost <- C5.0(credit_train[-17], credit_train$default,\n costs = error_cost)\ncredit_cost_pred <- predict(credit_cost, credit_test)\n\nCrossTable(credit_test$default, credit_cost_pred,\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\n dnn = c('actual default', 'predicted default'))\n\n#### Part 2: Rule Learners -------------------\n\n## Example: Identifying Poisonous Mushrooms ----\n## Step 2: Exploring and preparing the data ---- \nmushrooms <- read.csv(\"mushrooms.csv\", stringsAsFactors = TRUE)\n\n# examine the structure of the data frame\nstr(mushrooms)\n\n# drop the veil_type feature\nmushrooms$veil_type <- NULL\n\n# examine the class distribution\ntable(mushrooms$type)\n\n## Step 3: Training a model on the data ----\nlibrary(RWeka)\n\n# train OneR() on the data\nmushroom_1R <- OneR(type ~ ., data = mushrooms)\n\n## Step 4: Evaluating model performance ----\nmushroom_1R\nsummary(mushroom_1R)\n\n## Step 5: Improving model performance ----\nmushroom_JRip <- JRip(type ~ ., data = mushrooms)\nmushroom_JRip\nsummary(mushroom_JRip)\n\n# Rule Learner Using C5.0 Decision Trees (not in text)\nlibrary(C50)\nmushroom_c5rules <- C5.0(type ~ odor + gill_size, data = mushrooms, rules = TRUE)\nsummary(mushroom_c5rules)\n", "meta": {"hexsha": "3299688e8d5968583cf22221d272545c07efd533", "size": 3947, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 05/MLwR_v2_05.r", "max_stars_repo_name": "PacktPublishing/Machine-Learning-with-R---Second-Edition", "max_stars_repo_head_hexsha": "426864c2fc703962ae89ae6b437ac40d1b4104f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-17T21:35:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T04:28:52.000Z", "max_issues_repo_path": "Chapter 05/MLwR_v2_05.r", "max_issues_repo_name": "PacktPublishing/Machine-Learning-with-R---Second-Edition", "max_issues_repo_head_hexsha": "426864c2fc703962ae89ae6b437ac40d1b4104f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-05-28T09:52:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T10:13:11.000Z", "max_forks_repo_path": "Chapter 05/MLwR_v2_05.r", "max_forks_repo_name": "PacktPublishing/Machine-Learning-with-R---Second-Edition", "max_forks_repo_head_hexsha": "426864c2fc703962ae89ae6b437ac40d1b4104f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2019-10-06T00:57:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:18:58.000Z", "avg_line_length": 29.9015151515, "max_line_length": 82, "alphanum_fraction": 0.7076260451, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7496071211294498}} {"text": "# Load dataset\ndataset2 <- read.csv(\"dataset2.csv\", quote=\"\")\n# Print summary of dataset\nsummary(dataset2)\n\n# Perform MANOVA analysis\nmanova_results <- manova(cbind(time, error) ~ menu, data=dataset2)\nprint(\"Summary of Manova Analysis:\")\n# Print summary of MANOVA\nsummary(manova_results)\n# Get the p_value of the test\np_value <- summary(manova_results)$stats[[1,6]]\nprint(p_value)\n \nif (p_value < 0.05) { # If p_value < 0.05: reject the null hypothesis\n print(\"p_value is less than 0.05. Hence the results are not by chance variation and the null hypothesis is rejected. There is significant effect of independent variable menu type on dependent variable access time and error.\")\n} else { # Else accept the null hypothesis\n print(\"p_value is greater than or equal to 0.05. Hence the results could be by chance variation and we cannot reject the null hypothesis. There is no significant effect of independent variable menu type on dependent variable access time and error.\")\n}\n\n\n# Perform ANOVA analysis\nprint(\"Perform ANOVA analysis to find out which dependent variable (time or error) does the independent variable (menu) has a significant effect on.\")\nanova_results <- summary.aov(manova_results)\nprint(anova_results)\n\n# Analyze effect of menu on time\np_value_time <- anova_results$` Response time`$`Pr(>F)`[[1]]\nprint(paste(\"p_value time: \", p_value_time))\nif (p_value_time < 0.05) {\n print(\"p_value of time is less than 0.05. Hence independent variable menu has significant effect on dependent variable time.\")\n} else {\n print(\"p_value of time is not less than 0.05. Hence independent variable menu does not have a significant effect on dependent variable time.\")\n}\n\n# Analyze effect of menu on error\np_value_error <- anova_results$` Response error`$`Pr(>F)`[[1]]\nprint(paste(\"p_value error: \", p_value_error))\nif (p_value_error < 0.05) {\n print(\"p_value of error is less than 0.05. Hence independent variable menu has significant effect on dependent variable error\")\n} else {\n print(\"p_value of error is not less than 0.05. Hence independent variable menu does not have a significant effect on dependent variable error\")\n}\n\n# Perform pairwise t-test with dependent variable time\nt_test_results <- pairwise.t.test(dataset2$time, dataset2$menu, p.adjust.method = \"bonferroni\", paired = TRUE)\nprint(t_test_results)\n\n# One tailed t-test between toolpalette and controlmenu\ntoolpalette <- subset(dataset2, menu == \"toolpalette\")\ncontrolmenu <- subset(dataset2, menu == \"controlmenu\")\nt_test_result <- t.test(toolpalette$time, controlmenu$time, alternative = \"greater\", paired = TRUE)\np_value <- t_test_result$p.value\nprint(paste(\"p_value toolpalette-controlmenu: \", p_value))\n\n# One tailed t-test between toolpalette and flowmenu\ntoolpalette <- subset(dataset2, menu == \"toolpalette\")\nflowmenu <- subset(dataset2, menu == \"flowmenu\")\nt_test_result <- t.test(toolpalette$time, flowmenu$time, alternative = \"greater\", paired = TRUE)\np_value <- t_test_result$p.value\nprint(paste(\"p_value toolpalette-flowmenu: \", p_value))\n\n# One tailed t-test between toolpalette and toolglass\ntoolpalette <- subset(dataset2, menu == \"toolpalette\")\ntoolglass <- subset(dataset2, menu == \"toolglass\")\nt_test_result <- t.test(toolpalette$time, toolglass$time, alternative = \"greater\", paired = TRUE)\np_value <- t_test_result$p.value\nprint(paste(\"p_value toolpalette-toolglass: \", p_value))\n\n\n# Perform pairwise t-test with dependent variable error\nt_test_results <- pairwise.t.test(dataset2$error, dataset2$menu, p.adjust.method = \"bonferroni\", paired = TRUE)\nprint(t_test_results)\n\n# One tailed t-test between toolglass and controlmenu\ntoolglass <- subset(dataset2, menu == \"toolglass\")\ncontrolmenu <- subset(dataset2, menu == \"controlmenu\")\nt_test_result <- t.test(toolglass$error, controlmenu$error, alternative = \"less\", paired = TRUE)\np_value <- t_test_result$p.value\nprint(paste(\"p_value toolglass-controlmenu: \", p_value))\n\n# One tailed t-test between toolglass and flowmenu\ntoolglass <- subset(dataset2, menu == \"toolglass\")\nflowmenu <- subset(dataset2, menu == \"flowmenu\")\nt_test_result <- t.test(toolglass$error, flowmenu$error, alternative = \"less\", paired = TRUE)\np_value <- t_test_result$p.value\nprint(paste(\"p_value toolglass-flowmenu: \", p_value))\n\n# One tailed t-test between toolglass and toolpalette\ntoolglass <- subset(dataset2, menu == \"toolglass\")\ntoolpalette <- subset(dataset2, menu == \"toolpalette\")\nt_test_result <- t.test(toolglass$error, toolpalette$error, alternative = \"less\", paired = TRUE)\np_value <- t_test_result$p.value\nprint(paste(\"p_value toolglass-toolpalette: \", p_value))\n\n\n# Visualizations \nboxplot(time~menu,\n data=dataset2,\n main=\"Different boxplots for each menu\",\n xlab=\"Menu\",\n ylab=\"Time\",\n frame = FALSE,\n col = c(\"#DDEDAA\", \"#F4AC45\", \"#FFCAB1\", \"#92BFB1\"),\n border=\"black\"\n)\n\nboxplot(error~menu,\n data=dataset2,\n main=\"Different boxplots for each menu\",\n xlab=\"Menu\",\n ylab=\"Error\",\n frame = FALSE,\n col = c(\"#DDEDAA\", \"#F4AC45\", \"#FFCAB1\", \"#92BFB1\"),\n border=\"black\"\n)\n\n# between-within plot for time\nB <- anova(lm(time ~ menu, data = dataset2))$\"Mean Sq\"\nnames(B) <- c(\"between\", \"within\")\nbarplot(B, main = \"Between vs. within\", xlab = \"Group (Menu)\", ylab = \"Sum of Squares (Time)\", col = c(\"#DDEDAA\", \"#F4AC45\"))\n\n# between-within plot for error\nB <- anova(lm(error ~ menu, data = dataset2))$\"Mean Sq\"\nnames(B) <- c(\"between\", \"within\")\nbarplot(B, main = \"Between vs. within\", xlab = \"Group (Menu)\", ylab = \"Sum of Squares (Error)\", col = c(\"#DDEDAA\", \"#F4AC45\"))\n\n", "meta": {"hexsha": "c2adb8d560da229b16543a8768ea4558a047c213", "size": 5608, "ext": "r", "lang": "R", "max_stars_repo_path": "q2.r", "max_stars_repo_name": "rmodi6/statistical-analysis-using-R", "max_stars_repo_head_hexsha": "6d8bb688eb0fadae7c806166d600dd66d5aa1825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "q2.r", "max_issues_repo_name": "rmodi6/statistical-analysis-using-R", "max_issues_repo_head_hexsha": "6d8bb688eb0fadae7c806166d600dd66d5aa1825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "q2.r", "max_forks_repo_name": "rmodi6/statistical-analysis-using-R", "max_forks_repo_head_hexsha": "6d8bb688eb0fadae7c806166d600dd66d5aa1825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8125, "max_line_length": 251, "alphanum_fraction": 0.7259272468, "num_tokens": 1443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7494001214875478}} {"text": "# Poisson Distribution\r\n# Poisson probability of observing y events in a unit of time or space is given by the formula \r\n# probability_y<-((U^y)*(e^-U))/factorial(y)\r\n# U is the average value of y\r\nU<-2.3\r\n# The probability that a trap contains exactly four field mice is computed\r\ny<-4\r\nprobability_findingexactlyfour<-((U^y)*(exp(1)^-U))/factorial(y)\r\nprint(probability_findingexactlyfour)\r\n# The probability That a trap contains atmost four feild mice is computed as\r\nprobability_findingatmost_four=(((U^0)*(exp(1)^-U))/factorial(0))+(((U^1)*(exp(1)^-U))/factorial(1))+(((U^2)*(exp(1)^-U))/factorial(2))+(((U^3)*(exp(1)^-U))/factorial(3))+(((U^4)*(exp(1)^-U))/factorial(4))\r\nprint(probability_findingatmost_four)\r\n# The probability of finding more than four field mice\r\nprobability_findingmorethanfour=1-probability_findingatmost_four\r\nprint(probability_findingmorethanfour)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "64653ee5f655a99b3937c3a773c20f89e0b92598", "size": 885, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.12/Ex4_12.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.12/Ex4_12.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.12/Ex4_12.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 46.5789473684, "max_line_length": 206, "alphanum_fraction": 0.7276836158, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102589923635, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7493399122861698}} {"text": "library(deSolve)\nlibrary(ggplot2)\nlibrary(reshape2)\nlibrary(gridExtra)\nlibrary(Rcpp)\nlibrary(RColorBrewer)\n\nSIR <- function(Time, State, Pars) {\n \n with(as.list(c(State, Pars)), {\n \n B <- R0*r/N\n BSI <- B*S*I\n rI <- r*I\n \n dS = -BSI\n dI = BSI - rI\n dR = rI\n \n return(list(c(dS, dI, dR)))\n \n })\n \n}\n\nStocSIR <- function(y, pars, T, steps) {\n\n\tout <- matrix(NA, nrow = (T+1), ncol = 4)\n\n\tR0 <- pars[['R0']]\n\tr <- pars[['r']]\n\tN <- pars[['N']]\n\teta <- pars[['eta']]\n\tberr <- pars[['berr']]\n\n\tS <- y[['S']]\n\tI <- y[['I']]\n\tR <- y[['R']]\n\n\tB0 <- R0 * r / N\n\tB <- B0\n\n\tout[1,] <- c(S,I,R,B)\n\n\th <- 1 / steps\n\n\tfor ( i in 1:(T*steps) ) {\n\n\t\tB <- exp( log(B) + eta*(log(B0) - log(B)) + rnorm(1, 0, berr) )\n\n\t\tBSI <- B*S*I\n\t\trI <- r*I\n\n\t\tdS <- -BSI\n\t\tdI <- BSI - rI\n\t\tdR <- rI\n\n\t\tS <- S + h*dS #newInf\n\t\tI <- I + h*dI #newInf - h*dR\n\t\tR <- R + h*dR #h*dR\n\n\t\tif (i %% steps == 0)\n\t\t\tout[i/steps+1,] <- c(S,I,R,B)\n\n\t}\n\n\treturn(out)\n\n}\n\nset.seed(50721456)\n\nT \t\t<- 60\ni_infec <- 5\nsteps \t<- 7\nN \t\t<- 500\nsigma \t<- 10\nTlim \t<- T\n\n## Generate true trajecory and synthetic data\n##\n\npars_true <- c(R0 = 3.0, \t# new infected people per infected person\n r = 0.1, \t\t# recovery rate\n\t\t N = 500, \t\t# population size\n\t\t eta = 0.5, \t# geometric random walk\n\t\t berr = 0.3) \t# Beta geometric walk noise\n\ntrue_init_cond <- c(S = N - i_infec,\n\t\t\t\t\tI = i_infec,\n\t\t\t\t\tR = 0)\n\nsdeout_true <- StocSIR(true_init_cond, pars_true, T, steps)\ncolnames(sdeout_true) <- c('S','I','R','B')\n\n#quartz()\n#plot(1:(T+1), sdeout[,'B'])\n\ninfec_counts_raw <- sdeout_true[,'I'] + rnorm(T+1, 0, sigma)\ninfec_counts <- ifelse(infec_counts_raw < 0, 0, infec_counts_raw)\n\nplotdata <- data.frame(times = 0:T, true = sdeout_true[,'I'], data = infec_counts)\n\ng <- ggplot(plotdata, aes(times)) +\n geom_line(aes(y = true, colour = \"True\")) + \n geom_point(aes(y = data, colour = \"Data\")) +\n labs(x = \"Time\", y = \"Infection count\", color = \"\") +\n scale_color_brewer(palette=\"Paired\") +\n theme(panel.background = element_rect(fill = \"#F0F0F0\"))\n\nif ( Sys.info()['sysname'] == 'Darwin' )\n\tquartz()\nprint(g)\n\n#ggsave(g, filename=\"dataplot.pdf\", height=4, width=6.5)\n\n## Rcpp stuff\n##\n\nNP <- 30000\nnPasses <- 10\ncoolrate <- 0.9\n\nsourceCpp(paste(getwd(),\"if2.cpp\",sep=\"/\"))\n\nif2data <- if2(infec_counts[1:(Tlim+1)], Tlim+1, N, NP, nPasses, coolrate)\n\nparamdata <- data.frame( if2data$paramdata )\nnames(paramdata) <- c(\"R0\", \"r\", \"sigma\", \"eta\", \"berr\", \"Sinit\", \"Iinit\", \"Rinit\")\n\nconvergedata <- data.frame( if2data$means )\nnames(convergedata) <- c(\"R0\", \"r\", \"sigma\", \"eta\", \"berr\", \"Sinit\", \"Iinit\", \"Rinit\")\n\nstatedata <- data.frame( if2data$statemeans )\nnames(statedata) <- c(\"S\",\"I\",\"R\")\n\n## last particle filter means plot\nif ( Sys.info()['sysname'] == 'Darwin' )\n\tquartz()\nqplot(1:(T+1), sdeout_true[,'I'], geom = \"line\", xlab = \"Time\", ylab = \"Infection counts\") +\n\tgeom_point(aes(y = infec_counts)) +\n\tgeom_line(aes(y = statedata[,'I']), linetype = \"dashed\") +\n\ttheme_bw()\n\n## sample from parameter distributions\n##\n\nnTraj \t<- 100\ndatlen \t<- dim(paramdata)[1]\ninds \t<- sample.int(datlen,nTraj,replace = TRUE)\nparams \t<- paramdata[inds,]\n\nbootstrapdata <- matrix(NA, nrow = nTraj, ncol = T+1)\n\nfor (i in 1:nTraj) {\n\n\tinit_cond <- c(S = params$Sinit[i],\n\t I = params$Iinit[i],\n\t R = params$Rinit[i])\n\tpars <- c(R0 = params$R0[i],\n\t r = params$r[i],\n\t N = 500.0,\n\t eta = params$eta[i],\n\t berr = params$berr[i])\n\n\tsdeout <- StocSIR(init_cond, pars, T, steps)\n\tcolnames(sdeout) <- c('S','I','R','B')\n\n\tbootstrapdata[i,] <- sdeout[,'I']\n\n}\n\nmeanTraj \t<- colMeans(bootstrapdata)\nquantTraj \t<- t(apply(bootstrapdata, 2, quantile, probs = c(0.025,0.975)))\ncolnames(quantTraj) <- c(\"025\",\"975\")\n\ndatapart <- c(infec_counts[1:(Tlim+1)],rep(NA,T-Tlim))\n\ng <- qplot(1:(T+1), sdeout_true[,'I'], geom = \"line\", xlab = \"Time\", ylab = \"Infection count\") +\n geom_ribbon(aes(ymin = quantTraj[,'025'], ymax=quantTraj[,'975']), alpha=0.1) +\n geom_line(aes(y = meanTraj), linetype = \"dashed\") +\n geom_point(aes(y = datapart)) +\n theme_bw()\n\nif ( Sys.info()['sysname'] == 'Darwin' )\n\tquartz()\nprint(g)\n\n#ggsave(g, filename=\"if2plot.pdf\", height=4, width=6.5)\n\nf <- function(pal) brewer.pal(brewer.pal.info[pal, \"maxcolors\"], pal)\nkcolours <- f(\"Paired\")\n\n\ntrueval.R0 \t\t<- 3.0\ntrueval.r \t\t<- 0.1\ntrueval.sigma \t<- 10.0\ntrueval.Iinit \t<- 5\ntrueval.eta \t<- 0.5\ntrueval.berr \t<- 0.3\n\nmeanval.R0 \t\t<- mean(convergedata$R0)\nmeanval.r \t\t<- mean(convergedata$r)\nmeanval.sigma \t<- mean(convergedata$sigma)\nmeanval.Iinit \t<- mean(convergedata$Iinit)\nmeanval.eta \t<- mean(convergedata$eta)\nmeanval.berr \t<- mean(convergedata$berr)\n\n\nlinecolour <- \"grey50\"\nlineweight <- 0.5\n\n## Convergence 'kernels'\nif (FALSE) {\n\tR0kernel <- qplot(convergedata$R0, geom = \"density\", xlab = expression(R[0]), ylab = \"\") +\n\t \t\t\tgeom_vline(aes(xintercept=pars_true['R0']), linetype=\"solid\", size=lineweight, color=linecolour) +\n\t \t\t\tgeom_vline(aes(xintercept=meanval.R0), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\t\ttheme_bw()\n\n\trkernel <- qplot(convergedata$r, geom = \"density\", xlab = \"r\", ylab = \"\") +\n\t \t\t\tgeom_vline(aes(xintercept=pars_true['r']), linetype=\"solid\", size=lineweight, color=linecolour) +\n\t \t\t\tgeom_vline(aes(xintercept=meanval.r), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\t\ttheme_bw()\n\n\tsigmakernel <- qplot(convergedata$sigma, geom = \"density\", xlab = expression(sigma), ylab = \"\") +\n\t \t\t\tgeom_vline(aes(xintercept=sigma), linetype=\"solid\", size=lineweight, color=linecolour) +\n\t \t\t\tgeom_vline(aes(xintercept=meanval.sigma), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\t\ttheme_bw()\n\n\tinfeckernel <- qplot(convergedata$Iinit, geom = \"density\", xlab = \"Initial Infected\", ylab = \"\") +\n\t \t\t\tgeom_vline(aes(xintercept=i_infec), linetype=\"solid\", size=lineweight, color=linecolour) +\n\t \t\t\tgeom_vline(aes(xintercept=meanval.Iinit), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\t\ttheme_bw()\n\n\tetakernel <- qplot(convergedata$eta, geom = \"density\", xlab = expression(eta), ylab = \"\") +\n\t \t\t\tgeom_vline(aes(xintercept=pars_true['eta']), linetype=\"solid\", size=lineweight, color=linecolour) +\n\t \t\t\tgeom_vline(aes(xintercept=meanval.eta), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\t\ttheme_bw()\n\n\tberrkernel <- qplot(convergedata$berr, geom = \"density\", xlab = expression(epsilon[proc]), ylab = \"\") +\n\t \t\t\tgeom_vline(aes(xintercept=pars_true['berr']), linetype=\"solid\", size=lineweight, color=linecolour) +\n\t \t\t\tgeom_vline(aes(xintercept=meanval.berr), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\t\ttheme_bw()\n\n\t# show grid\n\tif ( Sys.info()['sysname'] == 'Darwin' )\n\t\tquartz()\n\tgrid.arrange(R0kernel, rkernel, sigmakernel, infeckernel, etakernel, berrkernel,\n\t ncol = 3, nrow = 2, top = \"Convergence kernels\")\n}\n\n# Convergence plots\n\nR0converge <- qplot(1:dim(convergedata)[1], convergedata$R0, geom = \"line\", xlab = expression(R[0]), ylab = \"frequency\") +\n \t\t\tgeom_hline(aes(yintercept=pars_true['R0']), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_hline(aes(yintercept=meanval.R0), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\nrconverge <- qplot(1:dim(convergedata)[1], convergedata$r, geom = \"line\", xlab = \"r\", ylab = \"\") +\n \t\t\tgeom_hline(aes(yintercept=pars_true['r']), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_hline(aes(yintercept=meanval.r), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\nsigmaconverge <- qplot(1:dim(convergedata)[1], convergedata$sigma, geom = \"line\", xlab = expression(sigma), ylab = \"\") +\n \t\t\tgeom_hline(aes(yintercept=sigma), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_hline(aes(yintercept=meanval.sigma), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\ninfecconverge <- qplot(1:dim(convergedata)[1], convergedata$Iinit, geom = \"line\", xlab = \"Initial Infected\", ylab = \"frequency\") +\n \t\t\tgeom_hline(aes(yintercept=i_infec), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_hline(aes(yintercept=meanval.Iinit), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\netaconverge <- qplot(1:dim(convergedata)[1], convergedata$eta, geom = \"line\", xlab = expression(eta), ylab = \"\") +\n \t\t\tgeom_hline(aes(yintercept=pars_true['eta']), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_hline(aes(yintercept=meanval.eta), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\nberrconverge <- qplot(1:dim(convergedata)[1], convergedata$berr, geom = \"line\", xlab = expression(epsilon[proc]), ylab = \"\") +\n \t\t\tgeom_hline(aes(yintercept=pars_true['berr']), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_hline(aes(yintercept=meanval.berr), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\n# show grid\nif ( Sys.info()['sysname'] == 'Darwin' )\n\tquartz()\ngrid.arrange(R0converge, rconverge, sigmaconverge, infecconverge, etaconverge, berrconverge,\n ncol = 3, nrow = 2, top = \"Convergence plots\")\n\n\n# Final swarm kernel densities\n\nmeanval.R0 \t\t<- mean(paramdata$R0)\nmeanval.r \t\t<- mean(paramdata$r)\nmeanval.sigma \t<- mean(paramdata$sigma)\nmeanval.Iinit \t<- mean(paramdata$Iinit)\nmeanval.eta \t<- mean(paramdata$eta)\nmeanval.berr \t<- mean(paramdata$berr)\n\nlinecolour <- \"grey50\"\nlineweight <- 0.5\n\nR0kernel <- qplot(paramdata$R0, geom = \"density\", xlab = expression(R[0]), ylab = \"frequency\") +\n \t\t\tgeom_vline(aes(xintercept=pars_true['R0']), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_vline(aes(xintercept=meanval.R0), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\nrkernel <- qplot(paramdata$r, geom = \"density\", xlab = \"r\") +\n \t\t\tgeom_vline(aes(xintercept=pars_true['r']), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_vline(aes(xintercept=meanval.r), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\nsigmakernel <- qplot(paramdata$sigma, geom = \"density\", xlab = expression(sigma)) +\n \t\t\tgeom_vline(aes(xintercept=sigma), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_vline(aes(xintercept=meanval.sigma), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\ninfeckernel <- qplot(paramdata$Iinit, geom = \"density\", xlab = \"Initial Infected\", ylab = \"frequency\") +\n \t\t\tgeom_vline(aes(xintercept=i_infec), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_vline(aes(xintercept=meanval.Iinit), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\netakernel <- qplot(paramdata$eta, geom = \"density\", xlab = expression(eta)) +\n \t\t\tgeom_vline(aes(xintercept=pars_true['eta']), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_vline(aes(xintercept=meanval.eta), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\nberrkernel <- qplot(paramdata$berr, geom = \"density\", xlab = expression(epsilon[proc])) +\n \t\t\tgeom_vline(aes(xintercept=pars_true['berr']), linetype=\"solid\", size=lineweight, color=linecolour) +\n \t\t\tgeom_vline(aes(xintercept=meanval.berr), linetype=\"dashed\", size=lineweight, color=linecolour) +\n\t\t\t\ttheme_bw()\n\n\n# show grid\ngrid.arrange(R0kernel, rkernel, sigmakernel, infeckernel, etakernel, berrkernel,\n ncol = 3, nrow = 2, top = \"Swarm final density kernels\")\n\n#pdf(\"if2kernels.pdf\", height = 6.5, width = 6.5)\n#grid.arrange(R0kernel, rkernel, sigmakernel, infeckernel, ncol = 2, nrow = 2)\n#dev.off()", "meta": {"hexsha": "08fb64d04f9068bea1c8aa2f4d344b2e56aa02bf", "size": 11740, "ext": "r", "lang": "R", "max_stars_repo_path": "code/if2/if2bootstrap.r", "max_stars_repo_name": "dbarrows/epidemic-forecasting", "max_stars_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/if2/if2bootstrap.r", "max_issues_repo_name": "dbarrows/epidemic-forecasting", "max_issues_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/if2/if2bootstrap.r", "max_forks_repo_name": "dbarrows/epidemic-forecasting", "max_forks_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5294117647, "max_line_length": 130, "alphanum_fraction": 0.6449744463, "num_tokens": 3992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7489974524471797}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Goodness of Fit - Exercise 01\n\nrm(list = ls())\n\n\nobserved <- c(967, 1008, 975, 1022, 1003, 989, 1001, 981, 1043, 1011)\n\n(n <- sum(observed))\n# 10000\n\n(k <- length(observed))\n# 10\n\n(expected <- 1 / k * n)\n# 1000\n\n(Q <- sum((observed - expected) ^ 2 / expected))\n# 4.724\n\n(pvalue <- 1 - pchisq(Q, k - 1))\n# 0.857673749486367\n", "meta": {"hexsha": "78536481473ee07a9d5bdaca7e4e6ac4ea04f024", "size": 388, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/goodness-of-fit/exercise-01.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/goodness-of-fit/exercise-01.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/goodness-of-fit/exercise-01.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8695652174, "max_line_length": 69, "alphanum_fraction": 0.6134020619, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7489334407228702}} {"text": "omedian <- function(v) {\n if ( length(v) < 1 )\n NA\n else {\n sv <- sort(v)\n l <- length(sv)\n if ( l %% 2 == 0 )\n (sv[floor(l/2)+1] + sv[floor(l/2)])/2\n else\n sv[floor(l/2)+1]\n }\n}\n\na <- c(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)\nb <- c(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)\n\nprint(median(a)) # 4.4\nprint(omedian(a))\nprint(median(b)) # 4.25\nprint(omedian(b))\n", "meta": {"hexsha": "92d590427b01a47213fae0b898ca228fc1508ab4", "size": 375, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Averages-Median/R/averages-median.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Averages-Median/R/averages-median.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Averages-Median/R/averages-median.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 17.8571428571, "max_line_length": 43, "alphanum_fraction": 0.4586666667, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.748832276136009}} {"text": "#' Computes the maximum likelihood estimator for the sample covariance matrix\n#' under the assumption of multivariate normality.\n#'\n#' For a sample matrix, `x`, we compute the sample covariance matrix of the\n#' data as the maximum likelihood estimator (MLE) of the population covariance\n#' matrix.\n#'\n#' If the `diag` option is set to `TRUE`, then we assume the population\n#' covariance matrix is diagonal, and the MLE is computed under this assumption.\n#' In this case, we return a vector of length `p` instead.\n#'\n#' @export\n#' @importFrom stats var cov\n#' @param x data matrix with `n` observations and `p` feature vectors\n#' @param diag logical value. If TRUE, assumes the population covariance matrix\n#' is diagonal. By default, we assume that `diag` is `FALSE`.\n#' @return sample covariance matrix of size \\eqn{p \\times p}. If `diag` is\n#' `TRUE`, then a vector of length `p` is returned instead.\ncov_mle <- function(x, diag = FALSE) {\n x <- as.matrix(x)\n n <- nrow(x)\n if (diag) {\n (n - 1) / n * apply(x, 2, var)\n } else {\n (n - 1) / n * cov(x)\n }\n}\n\n#' Computes the pooled maximum likelihood estimator (MLE) for the common\n#' covariance matrix\n#'\n#' For the matrix `x`, we compute the MLE for the population covariance\n#' matrix under the assumption that the data are sampled from \\eqn{K}\n#' multivariate normal populations having equal covariance matrices.\n#'\n#' @export\n#' @importFrom stats cov\n#' @param x data matrix with `n` observations and `p` feature vectors\n#' @param y class labels for observations (rows) in `x`\n#' @return pooled sample covariance matrix of size \\eqn{p \\times p}\n#' @examples\n#' cov_pool(iris[, -5], iris$Species)\ncov_pool <- function(x, y) {\n x <- as.matrix(x)\n y <- as.factor(y)\n n <- length(y)\n \n scatter_matrices <- tapply(seq_len(n), y, function(i) {\n (length(i) - 1) * cov(as.matrix(x[i, ]))\n })\n as.matrix(Reduce(\"+\", scatter_matrices) / n)\n}\n\n#' Computes the covariance-matrix maximum likelihood estimators for each class\n#' and returns a list.\n#'\n#' For a sample matrix, `x`, we compute the MLE for the covariance matrix\n#' for each class given in the vector, `y`.\n#' @export\n#' @param x data matrix with `n` observations and `p` feature vectors\n#' @param y class labels for observations (rows) in `x`\n#' @return list of the sample covariance matrices of size \\eqn{p \\times p} for\n#' each class given in `y`.\ncov_list <- function(x, y) {\n x <- as.matrix(x)\n y <- as.factor(y)\n tapply(seq_along(y), y, function(i) {\n cov_mle(x[i, ])\n })\n}\n\n#' Computes the eigenvalue decomposition of the maximum likelihood estimators\n#' (MLE) of the covariance matrices for the given data matrix\n#'\n#' For the classes given in the vector `y`, we compute the eigenvalue\n#' (spectral) decomposition of the class sample covariance matrices (MLEs) using\n#' the data matrix `x`.\n#'\n#' If the `fast` argument is selected, we utilize the so-called Fast\n#' Singular Value Decomposition (SVD) to quickly compute the eigenvalue\n#' decomposition. To compute the Fast SVD, we use the [corpcor::fast.svd()]\n#' function, which employs a well-known trick for tall data (large `n`,\n#' small `p`) and wide data (large `p`, small `n`) to compute the\n#' SVD corresponding to the nonzero singular values. For more information about\n#' the Fast SVD, see [corpcor::fast.svd()].\n#' \n#' @importFrom corpcor fast.svd\n#' @export\n#' @param x data matrix with `n` observations and `p` feature vectors\n#' @param y class labels for observations (rows) in `x`\n#' @param pool logical. Should the sample covariance matrices be pooled?\n#' @param fast logical. Should the Fast SVD be used? See details.\n#' @param tol tolerance value below which the singular values of `x` are\n#' considered zero.\n#' @return a list containing the eigendecomposition for each class. If\n#' `pool = TRUE`, then a single list is returned.\n#' @examples\n#' cov_eigen(x = iris[, -5], y = iris[, 5])\n#' cov_eigen(x = iris[, -5], y = iris[, 5], pool = TRUE)\n#' cov_eigen(x = iris[, -5], y = iris[, 5], pool = TRUE, fast = TRUE)\n#'\n#' # Generates a data set having fewer observations than features.\n#' # We apply the Fast SVD to compute the eigendecomposition corresponding to the\n#' # nonzero eigenvalues of the covariance matrices.\n#' set.seed(42)\n#' n <- 5\n#' p <- 20\n#' num_classes <- 3\n#' x <- lapply(seq_len(num_classes), function(k) {\n#' replicate(p, rnorm(n, mean = k))\n#' })\n#' x <- do.call(rbind, x)\n#' colnames(x) <- paste0(\"x\", 1:ncol(x))\n#' y <- gl(num_classes, n)\n#' cov_eigen(x = x, y = y, fast = TRUE)\n#' cov_eigen(x = x, y = y, pool = TRUE, fast = TRUE)\ncov_eigen <- function(x, y, pool = FALSE, fast = FALSE, tol = 1e-6) {\n x <- as.matrix(x)\n y <- as.factor(y)\n\n if (fast) {\n # First, we center each class.\n x_centered <- center_data(x = x, y = y)\n if (pool) {\n n <- nrow(x_centered)\n svd_out <- fast.svd(x_centered)\n eigenvals <- svd_out$d^2 / n\n # We retain only the 'q' eigenvalues greater than 'tol'. Effectively, 'q'\n # is our estimate for the rank of the covariance matrix.\n q <- sum(eigenvals > tol)\n seq_q <- seq_len(q)\n eigen_out <- list(vectors = svd_out$v[, seq_q], values = eigenvals[seq_q])\n }\n else {\n eigen_out <- tapply(seq_along(y), y, function(i) {\n n <- length(i)\n svd_out <- fast.svd(x_centered[i, ])\n eigenvals <- svd_out$d^2 / n\n # We retain only the 'q' eigenvalues greater than 'tol'. Effectively, 'q'\n # is our estimate for the rank of the covariance matrix.\n q <- sum(eigenvals > tol)\n seq_q <- seq_len(q)\n list(vectors = svd_out$v[, seq_q], values = eigenvals[seq_q])\n })\n }\n } else {\n if (pool) {\n eigen_out <- eigen(cov_pool(x = x, y = y), symmetric = TRUE)\n } else {\n eigen_out <- lapply(cov_list(x = x, y = y), eigen, symmetric = TRUE)\n }\n }\n eigen_out\n}\n\n#' Computes the observation weights for each class for the HDRDA classifier\n#'\n#' This function calculates the weight for each observation in the data matrix\n#' `x` in order to calculate the covariance matrices employed in the HDRDA\n#' classifier, implemented in [rda_high_dim()].\n#'\n#' @inheritParams lda_diag\n#' @param y vector of class labels for each training observation\n#' @param lambda the RDA pooling parameter. Must be between 0 and 1, inclusively.\n#' @return list containing the observations for each class given in `y`\n#'\n#' @references Ramey, J. A., Stein, C. K., and Young, D. M. (2013),\n#' \"High-Dimensional Regularized Discriminant Analysis.\"\nrda_weights <- function(x, y, lambda = 1) {\n x <- as.matrix(x)\n y <- as.factor(y)\n N <- length(y)\n tapply(seq_along(y), y, function(i) {\n n_k <- length(i)\n weights_k <- lambda / N + (1 - lambda) / n_k\n replace(rep(lambda / N, N), i, weights_k)\n })\n}\n\n#' Calculates the RDA covariance-matrix estimators for each class\n#'\n#' For the classes given in the vector `y`, this function calculates the\n#' class covariance-matrix estimators employed in the HDRDA classifier,\n#' implemented in [rda_high_dim()].\n#'\n#' @inheritParams lda_diag\n#' @param y vector of class labels for each training observation\n#' @param lambda the RDA pooling parameter. Must be between 0 and 1, inclusively.\n#' @return list containing the RDA covariance-matrix estimators for each class\n#' given in `y`\n#'\n#' @references Ramey, J. A., Stein, C. K., and Young, D. M. (2013),\n#' \"High-Dimensional Regularized Discriminant Analysis.\"\nrda_cov <- function(x, y, lambda = 1) {\n x_centered <- center_data(x = x, y = y)\n weights <- rda_weights(x = x, y = y, lambda = lambda)\n lapply(weights, function(weights_k) {\n x_scaled <- sqrt(weights_k) * x_centered\n crossprod(x_scaled)\n })\n}\n\n#' Computes a shrunken version of the maximum likelihood estimator for the\n#' sample covariance matrix under the assumption of multivariate normality.\n#'\n#' For a sample matrix, `x`, we compute the sample covariance matrix as the\n#' maximum likelihood estimator (MLE) of the population covariance matrix and\n#' shrink it towards its diagonal.\n#'\n#' Let \\eqn{\\widehat{\\Sigma}} be the MLE of the covariance matrix \\eqn{\\Sigma}.\n#' Then, we shrink the MLE towards its diagonal by computing\n#' \\deqn{\\widehat{\\Sigma}(\\gamma) = \\gamma \\widehat{\\Sigma} + (1 - \\gamma)\n#' \\widehat{\\Sigma} \\circ I_p,} where \\eqn{\\circ} denotes the Hadamard product\n#' and \\eqn{\\gamma \\in [0,1]}.\n#'\n#' For \\eqn{\\gamma < 1}, the resulting shrunken covariance matrix estimator is\n#' positive definite, and for \\eqn{\\gamma = 1}, we simply have the MLE, which can\n#' potentially be positive semidefinite (singular).\n#'\n#' The estimator given here is based on Section 18.3.1 of the Hastie et\n#' al. (2008) text.\n#'\n#' @export\n#' @param x data matrix with `n` observations and `p` feature vectors\n#' @param gamma the shrinkage parameter. Must be between 0 and 1, inclusively.\n#' By default, the shrinkage parameter is 1, which simply yields the MLE.\n#' @return shrunken sample covariance matrix of size \\eqn{p \\times p}\n#'\n#' @references Hastie, T., Tibshirani, R., and Friedman, J. (2008), \"The\n#' Elements of Statistical Learning: Data Mining, Inference, and Prediction,\"\n#' 2nd edition. \\url{http://web.stanford.edu/~hastie/ElemStatLearn/}\ncov_shrink_diag <- function(x, gamma = 1) {\n if (gamma < 0 || gamma > 1) {\n rlang::abort(\"The value of 'gamma' must be between 0 and 1, inclusively.\")\n }\n cov_x <- cov_mle(x)\n gamma * cov_x + (1 - gamma) * diag(diag(cov_x))\n}\n", "meta": {"hexsha": "7a87158e80ba04395f6785f0f1f5074373c47e5c", "size": 9423, "ext": "r", "lang": "R", "max_stars_repo_path": "R/helper-cov.r", "max_stars_repo_name": "topepo/sparsediscrim", "max_stars_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:13:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T21:44:00.000Z", "max_issues_repo_path": "R/helper-cov.r", "max_issues_repo_name": "topepo/sparsediscrim", "max_issues_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-26T12:02:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:00:06.000Z", "max_forks_repo_path": "R/helper-cov.r", "max_forks_repo_name": "topepo/sparsediscrim", "max_forks_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4267782427, "max_line_length": 81, "alphanum_fraction": 0.6751565319, "num_tokens": 2637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7487756175428408}} {"text": "# ************************************************\n### simon munzert\n### ols and multiple regression\n# ************************************************\n\nsource(\"packages.r\")\nsource(\"functions.r\")\n\n\n\n# ************************************************\n# Bivariate regression, OLS estimation -----------\n\n# load data\ndata(\"wage1\")\n\n# inspect relationship\nqplot(educ, wage, data = wage1)\nplot(wage1$educ, wage1$wage)\ncor(wage1$wage, wage1$educ)\nwith(wage1, cor(educ, wage))\n\n# run linear model\nwage_model <- lm(wage ~ educ, data = wage1)\nsummary(wage_model)\ncoef(wage_model)\n\n# export model\nstargazer(wage_model, single.row = TRUE, header = FALSE, style = \"apsr\", type = \"html\", out = \"../output/wage_model_ols.html\")\nbrowseURL(\"../output/wage_model_ols.html\")\n\n# manual computation\ncovariance_xy <- with(wage1, cov(wage, educ))\nvariance_x <- var(wage1$educ)\ncovariance_xy / variance_x # beta_1\nmean(wage1$wage) - (covariance_xy / variance_x)*mean(wage1$educ) # beta_0\n\n\n\n# ************************************************\n# Multiple regression, OLS estimation ------------\n\n# run linear model\nwage_model <- lm(wage ~ educ + female, data = wage1)\nsummary(wage_model)\ncoef(wage_model)\n\n# manual computation for beta_educ\n\n# step 1: isolate part of X that is linearly independent from Z\nwage_model_xz <- lm(educ ~ female, data = wage1)\nresid_xz <- residuals(wage_model_xz)\n\n# step 2: explain Y by part of X that is independent from Z\nwage_model_yx <- lm(wage1$wage ~ resid_xz)\ncoef(wage_model_yx)\n\n## continue in analogy to arrive at point estimate for beta_female.\n\n\n\n# ************************************************\n# How are coefficients from simple and -----------\n# multiple OLS estimates related? ----------------\n\nwage_model <- lm(wage ~ educ, data = wage1)\ncoef_simple <- coef(wage_model)[2] \n\nwage_model_mult <- lm(wage ~ educ + female, data = wage1)\ncoef_multiple <- coef(wage_model_mult)[2]\n\nwage_model_zx <- lm(female ~ educ, data = wage1)\ncoef_simple_zx <- coef(wage_model_zx)[2]\n\n# these two are the same:\ncoef_simple\ncoef_multiple + coef(wage_model_mult)[3]*coef(wage_model_zx)[2]\n\n\n\n# ***************************************************\n# Effects of controls on coefficients of interest ---\n\nwage_model_1 <- lm(wage ~ educ, data = wage1)\nwage_model_2 <- lm(wage ~ educ + female, data = wage1)\nwage_model_3 <- lm(wage ~ educ + female + nonwhite, data = wage1)\nwage_model_4 <- lm(wage ~ educ + female + nonwhite + profocc, data = wage1)\n\nstargazer(wage_model_1, wage_model_2, wage_model_3, wage_model_4, header = FALSE, style = \"apsr\", type = \"html\", out = \"../output/wage_model_multiple.html\")\nbrowseURL(\"../output/wage_model_multiple.html\")\nstargazer(wage_model_1, wage_model_2, wage_model_3, wage_model_4, header = FALSE, title = \"Regressing wage on...\", omit.table.layout = \"dln\", style = \"apsr\", font.size = \"scriptsize\", df = FALSE, report = \"vcs\", single.row = FALSE, no.space = TRUE, type = \"latex\", out = \"../output/wage_model_multiple.tex\")\n\ncor(select(wage1, wage, educ, female, nonwhite, profocc)) \n\n\n\n# ************************************************\n# Post-estimation bias: simulation ---------------\n\nset.seed(42)\nN <- 500\nx <- rnorm(N, 0, 1)\ned <- rnorm(N, 0, .5)\nd <- .8*x + ed # d is mediator\ney <- rnorm(N, 0, .5)\ny <- x + d + ey\n\ncor(cbind(y, x, d))\nplot(x, y)\n\n# complete \"true\" models\nsummary(lm(d ~ x))\nsummary(lm(y ~ x))\n\n# model with induced post-treatment bias\nsummary(lm(y ~ x + d))\n\n\n\n# ************************************************\n# Multicollinearity: detection -------------------\n\ndata(bwght2)\n?bwght2\nvars <- c(\"mage\", \"meduc\", \"monpre\", \"npvis\", \"fage\", \"feduc\", \"cigs\", \"drink\", \"male\")\nb <- paste(vars, collapse = \"+\")\nfrmla <- as.formula(paste(\"bwght ~ \", b, sep = \"\"))\n\n# example: perfect collinearity\nsummary(lm(bwght ~ fwhte + fblck + foth, data = bwght2))\n\n# full model\nmodel_out <- lm(frmla, data = bwght2)\nsummary(model_out)\n\n# inspect correlation matrix\ncor(bwght2[,vars], use = \"pairwise.complete.obs\")\n\n# inspect scatterplots\nplot(bwght2[,vars])\n\n# evaluate variance inflation factors\nvif(model_out) # function from car package\n\n\n\n# ************************************************\n# Anscombe's quartett ----------------------------\n\n?anscombe\nsummary(anscombe)\n\n# correlation\nsapply(1:4, function(x) cor(anscombe[, x], anscombe[, x+4]))\n\n# variance\nsapply(5:8, function(x) var(anscombe[, x]))\n\n# linear regression\nsummary(lm(y1 ~ x1, data = anscombe))\nsummary(lm(y2 ~ x2, data = anscombe))\nsummary(lm(y3 ~ x3, data = anscombe))\nsummary(lm(y4 ~ x4, data = anscombe))\n\n# plot\nff <- y ~ x\npar(mfrow = c(2, 2))\nfor(i in 1:4) {\n ff[2:3] <- lapply(paste0(c(\"y\",\"x\"), i), as.name)\n plot(ff, data = anscombe, col = \"red\", pch = 21, bg = \"orange\", cex = 1.2, xlim = c(3, 19), ylim = c(3, 13))\n model_out <- lm(ff, data = anscombe)\n abline(model_out, col = \"blue\")\n}\nmtext(\"Anscombe's 4 regression data sets\", outer = TRUE, cex = 1.5)\n\n\n\n# ************************************************\n# Functional form misspecification ---------------\n\nN <- 500\nx <- runif(N, 0, 1)\ny <- log(x) + rnorm(N, 0, .3)\n\n# look at model\nsummary(lm(y ~ x))\nsummary(lm(y ~ log(x)))\n\n# plot relationship\npar(mfrow = c(1, 3))\n# misspecified\nplot(x, y); abline(lm(y ~ x), col = \"red\")\n# correctly specified\ndat <- data.frame(x = sort(x), ypred = predict(lm(y ~ log(x)), newdata = data.frame(x = sort(x))))\nplot(x, y); lines(dat$x, dat$ypred, col = \"red\")\n# correctly specified\nplot(log(x), y); abline(lm(y ~ log(x)), col = \"red\")\n\n# RESET test\nresettest(lm(y ~ x))\nresettest(lm(y ~ log(x)))\n\n\n\n\n\n", "meta": {"hexsha": "14c258940dec374af6e19110a97dc09497104e6c", "size": 5527, "ext": "r", "lang": "R", "max_stars_repo_path": "code/02-ols.r", "max_stars_repo_name": "simonmunzert/stats-II-hertie-2017", "max_stars_repo_head_hexsha": "f577db8b0b5f2599e7896907233ef6871d793253", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/02-ols.r", "max_issues_repo_name": "simonmunzert/stats-II-hertie-2017", "max_issues_repo_head_hexsha": "f577db8b0b5f2599e7896907233ef6871d793253", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/02-ols.r", "max_forks_repo_name": "simonmunzert/stats-II-hertie-2017", "max_forks_repo_head_hexsha": "f577db8b0b5f2599e7896907233ef6871d793253", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-09-18T08:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-22T08:28:12.000Z", "avg_line_length": 26.7004830918, "max_line_length": 307, "alphanum_fraction": 0.6014112538, "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7487749357573623}} {"text": "## Created on Thursday, March 10, 2010 at 10:10pm EST by WeekendEditor on WeekendEditorMachine.\n## Copyright (c) 2020, SomeWeekendReading. All rights reserved. As if you care.\n\n##\n## Pretty pictures of fractal \"boundary\" of convergence in Newton's method for solving a cubic\n## in the complex plane. See Strogatz's NYT column:\n## http://opinionator.blogs.nytimes.com/2010/03/07/finding-your-roots/\n##\n## \"boundary\" in quotes: wherever you think 2 colors have a boundary, the 3rd interposes!\n##\n\ndoit <- function(xlim = c(-1, +1), ylim = c(-1, +1), npix = 500, doExact = FALSE, ask = TRUE) {\n ## Cyclotomic cubic z^3 - 1 has 3 roots in complex z plane, to which we assign colors.\n ## Other points are colored by the speed with which Newton's algorithm converges to a root.\n ## Plot a subset of the complex plane as described by xlim & ylim, npix per side.\n\n roots <- (function(angle) { complex(mod = 1, arg = angle) })(c(0, 2*pi/3, 4*pi/3))\n nearestRoot <- function(x, y) { which.min(abs(complex(real = x, imag = y) - roots)) }\n findRoot <- function(z, nIter = 0, eps = 1.0e-3) {# Which root by Newton & num iterations\n if (Re(z) == 0 && Im(z) == 0) # If at origin, then step away\n z <- complex(real = Re(z) + jitter(Re(z)), imag = Im(z) + jitter(Im(z)))\n flags <- abs(z - roots) < eps # Diffs from roots: only 1 can converge\n if (any(flags)) # If any root has converged (uniquely!)\n c(\"rootNum\" = which(flags), \"nIter\" = nIter) # then return root # and # iterations\n else # Else unconverged so far\n ## Newton's method in general for finding roots of f(z) = 0:\n ## z[i+1] = z[i] - f(z[i]) / f'(z[i])\n ## Here, f(z) = z^3 - 1, hence f'(z) = 3 z^2, so:\n ## z[i+1] = z[i] - (z[i]^3 - 1) / (3 z[i]^2) = 2/3 z[i] + 1/(3 z[i]^2)\n findRoot(2/3 * z + 1 / (3 * z^2), nIter + 1) # Take Newton step, bump iteration\n } # count, and try again\n\n plotRootFractal <- function(df, col, wrd) { # Plot expected/actual fractals\n oldParList <- NULL # Capture graphics param changes\n tryCatch({ # Guarantee restoring graphics params\n oldParList <- par(\"mgp\" = c(1.5, 0.5, 0), # Spacing of axis title, labels, & line\n \"mar\" = c(2.5, 2.5, 2.5, 1.0), # Margins: (bottom, left, top, right))\n \"ps\" = 10, # Point size type in labels\n \"las\" = 1, # Always horizontal labels\n \"ask\" = ask, # Ask before replotting\n \"pty\" = \"m\") # Maximal plotting area\n image(x = sort(unique(df$\"x\")), # Color by which root a point converges\n y = sort(unique(df$\"y\")), # to, and how fast\n z = t(matrix(df[, col], nrow = npix, ncol = npix, byrow = TRUE)),\n xlim = xlim, ylim = ylim, xlab = \"Re(z)\", ylab = \"Im(z)\",\n main = sprintf(\"%s Convergence of Newton's Algorithm on Cube Roots of Unity\", wrd),\n col = c(rgb(red = 0:255, green = 0, blue = 0, maxColorValue = 255),\n rgb(red = 0, green = 0:255, blue = 0, maxColorValue = 255),\n rgb(red = 0, green = 0, blue = 0:255, maxColorValue = 255)))\n box(which = \"plot\") # Put it in a box with a ribbon on it\n }, finally = par(oldParList)) # Restore graphics parameters\n } #\n\n ## (1) Start with skeleton of (x, y) pairs in the complex plane\n ## (2) Add on which root it converged to, and in how many iterations\n ## (3) Encode color in a funny way by root number and number of iterations\n df <- expand.grid(x = seq(from = xlim[[1]], to = xlim[[2]], length.out = npix),\n y = seq(from = ylim[[1]], to = ylim[[2]], length.out = npix))\n df <- cbind(df, # Adjoin onto skeleton 2 new columns:\n t(apply(df, 1, function(dfr) { findRoot(complex(real = dfr[[1]],\n imag = dfr[[2]])) })))\n maxN <- max(df$\"nIter\") # Scale color by max # of iterations\n df <- transform(df, color = rootNum - nIter/maxN) # Clunky color encoding\n plotRootFractal(df, \"color\", \"Actual\") # Plot the observed fractal\n\n if (doExact) { # If also plot expectations (exact root)\n df <- transform(transform(df, exactRootNum = Vectorize(nearestRoot)(x, y)),\n exactRootDist = abs(complex(real = x, imag = y) - roots[exactRootNum]))\n maxDist = max(df$\"exactRootDist\") # Color by distance from nearest root\n df <- transform(df, exactColor = exactRootNum - exactRootDist / maxDist)\n plotRootFractal(df, \"exactColor\", \"Expected\") # Plot the expected \"fractal\"\n } #\n\n invisible(df) # Return large dataframe, but invisibly\n} #\n\n##\n## Usage\n##\n\n## > system.time(foo <- doit(npix = 10), gcFirst = TRUE)\n## user system elapsed\n## 0.05 0.01 0.07\n## > system.time(foo <- doit(npix = 20), gcFirst = TRUE)\n## user system elapsed\n## 0.16 0.01 0.16\n## > system.time(foo <- doit(npix = 50), gcFirst = TRUE)\n## user system elapsed\n## 0.50 0.05 0.58\n## > system.time(foo <- doit(npix = 100), gcFirst = TRUE)\n## user system elapsed\n## 1.80 0.17 2.12\n## > system.time(foo <- doit(npix = 200), gcFirst = TRUE)\n## user system elapsed\n## 7.49 0.76 8.69\n## > system.time(foo <- doit(npix = 500), gcFirst = TRUE)\n## user system elapsed\n## 51.97 4.35 57.99\n## > system.time(foo <- doit(npix = 1000), gcFirst = TRUE)\n## user system elapsed\n## 225.70 19.19 255.33\n\n## > png(filename = \"root-fractal-2000.png\", width = 2200, height = 2200, bg = \"transparent\"); doit(npix = 2000, ask = FALSE); dev.off()\n\n## Test our hypothesis that time required scales quadratically with npix:\n##\n## > data <- data.frame(n = c(10, 20, 50, 100, 200, 500, 1000), t = c(0.07, 0.16, 0.58, 2.12, 8.69, 57.99, 255.33))\n##\n## > model <- lm(t ~ 1 + n + I(n^2), data = data); summary(model); transform(data.frame(data, tPred = predict(model, newdata = subset(data, select = \"n\"))), pctDiff = 100 * (t - tPred) / t)\n##\n## Coefficients:\n## Estimate Std. Error t value Pr(>|t|)\n## (Intercept) 9.410e-01 5.374e-01 1.751 0.15483\n## n -2.233e-02 4.068e-03 -5.490 0.00536 **\n## I(n^2) 2.765e-04 4.009e-06 68.984 2.65e-07 ***\n## ---\n## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1\n##\n## Residual standard error: 0.9065 on 4 degrees of freedom\n## Multiple R-squared: 0.9999, Adjusted R-squared: 0.9999\n## F-statistic: 3.258e+04 on 2 and 4 DF, p-value: 3.767e-09\n##\n## n t tPred pctDiff\n## 1 10 0.07 0.7453594 -964.79907826\n## 2 20 0.16 0.6050261 -278.14134139\n## 3 50 0.58 0.5158754 11.05597205\n## 4 100 2.12 1.4734535 30.49747513\n## 5 200 8.69 7.5367204 13.27134203\n## 6 500 57.99 58.9114051 -1.58890341\n## 7 1000 255.33 255.1521601 0.06965098\n##\n## Model p-value from F-statistic is 2 orders of magnitude better if we drop the constant term:\n##\n## > model2 <- lm(t ~ 0 + n + I(n^2), data = data); summary(model2); transform(data.frame(data, tPred = predict(model2, newdata = subset(data, select = \"n\"))), pctDiff = 100 * (t - tPred) / t)\n##\n## Coefficients:\n## Estimate Std. Error t value Pr(>|t|)\n## n -1.743e-02 3.508e-03 -4.968 0.00422 **\n## I(n^2) 2.725e-04 3.882e-06 70.185 1.11e-08 ***\n## ---\n## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1\n##\n## Residual standard error: 1.078 on 5 degrees of freedom\n## Multiple R-squared: 0.9999, Adjusted R-squared: 0.9999\n## F-statistic: 2.955e+04 on 2 and 5 DF, p-value: 6.582e-11\n##\n## n t tPred pctDiff\n## 1 10 0.07 -0.1470371 310.0530241\n## 2 20 0.16 -0.2395803 249.7376874\n## 3 50 0.58 -0.1902462 132.8010768\n## 4 100 2.12 0.9818559 53.6860445\n## 5 200 8.69 7.4131051 14.6938423\n## 6 500 57.99 59.4032132 -2.4369946\n## 7 1000 255.33 255.0412611 0.1130846\n##\n", "meta": {"hexsha": "08c8d89fbd58346ab6f769da44dc70758e093d92", "size": 8637, "ext": "r", "lang": "R", "max_stars_repo_path": "assets/2020-08-07-whats-that-stupid-avatar-root-fractal.r", "max_stars_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_stars_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/2020-08-07-whats-that-stupid-avatar-root-fractal.r", "max_issues_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_issues_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-10-14T16:09:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T21:01:06.000Z", "max_forks_repo_path": "assets/2020-08-07-whats-that-stupid-avatar-root-fractal.r", "max_forks_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_forks_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.3653846154, "max_line_length": 192, "alphanum_fraction": 0.5281926595, "num_tokens": 2827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7487076092760764}} {"text": "euclidean <- function(a, b) {\n return (sqrt(sum((a - b) ^ 2)))\n}\n\n# The oneNN function categorizes points based on the 1 nearest neighbour method.\n# Returns: a vector of class names for corresponding points.\n# Params:\n# dataset -- a data frame, must have exactly 2 columns.\n# points -- a list of points to categorize. Each point is a vector of length 2.\n# dist -- optional. A metric function to use in the 1-NN method. Defaults to the Euclidean distance.\noneNN <- function(dataset, points, dist = euclidean) {\n answer <- data.frame()\n \n for (i in 1:length(points[1,])) {\n currAns <- dataset[1,]\n \n \n for (j in 1:dim(dataset)[1]) {\n if (dist(currAns[3:4], points[,i]) > dist(dataset[j, 3:4], points[,i])) {\n currAns <- dataset[j,]\n }\n }\n answer <- rbind(answer, data.frame(currAns))\n }\n \n return (answer)\n}\n\ncolors <- c(\"setosa\" = \"blue\", \"virginica\" = \"red\", \"versicolor\" = \"green\")\nplot(iris[, 3:4], bg = colors[iris$Species], pch=23)\n\nz <- array(c(runif(5, 1, 7), runif(5, 0, 2.5)), dim = c(2, 5))\n\nprint(z[1,])\nprint(z[2,])\n\nresult <- oneNN(iris, z)\npoints(z[1,], z[2,], bg = colors[result$Species], pch = 22)", "meta": {"hexsha": "58cd2216841897da1ecbbad45ef354e5accadd64", "size": 1160, "ext": "r", "lang": "R", "max_stars_repo_path": "0 - 1-NN Algorithm/1-nn.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0 - 1-NN Algorithm/1-nn.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0 - 1-NN Algorithm/1-nn.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5263157895, "max_line_length": 102, "alphanum_fraction": 0.6146551724, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7485469916544047}} {"text": "### Author: Sergio García Prado\n### Title: 2017 Final Exam\n\nrm(list = ls())\n\n\n### Exercise 1\n\nP <- matrix(c(\n 0.0, 1/2, 0.0, 1/2, 0.0, 0.0, 0.0, 0.0, 0.0,\n 1/3, 0.0, 1/3, 0.0, 1/3, 0.0, 0.0, 0.0, 0.0,\n 0.0, 1/2, 0.0, 0.0, 0.0, 1/2, 0.0, 0.0, 0.0,\n 1/2, 0.0, 0.0, 0.0, 0.0, 0.0, 1/2, 0.0, 0.0,\n 0.0, 1/3, 0.0, 0.0, 0.0, 1/3, 0.0, 1/3, 0.0,\n 0.0, 0.0, 1/2, 0.0, 1/2, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0, 0.0, 1/2, 0.0, 0.0, 0.0, 1/2,\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0\n),9, 9, byrow = TRUE)\n\nR <- P[1:8, 1:8]\n\ng <- solve(diag(nrow(R)) - R) %*% rep(1, nrow(R))\n\n(doors <- g[1])\n# 44.5\n\n(visits.A <- solve(diag(nrow(R)) - R)[1, 1] - 1)\n# 6.5\n\n### Exercise 2\n\n(l.coche <- (5 / 60) ^ (-1))\n# 12\n\n(l.moto <- (10 / 60) ^ (-1))\n# 6\n\n(l.bus <- (30 / 60) ^ (-1))\n# 2\n\n### a) 2 cars and 1 motorcycle in 20 minutes.\ndpois(2, lambda = l.coche / 3) * dpois(1, lambda = l.moto / 3)\n# 0.0396600348266617\n\n### b) Non-change return in 10 minutes.\ndpois(0, lambda = 1 / 4 * (l.coche + l.moto + l.bus) / 6)\n# 0.434598208507078\n\n### c) 0 motorcycles from 20 vehicles.\ndbinom(0, size = 20, prob = l.moto / (l.coche + l.moto + l.bus))\n# 0.000797922662976119\n\n### d) 7th car before 2th motorcycle.\npbinom(7 - 1, size = 7 + 2 - 1, prob = l.coche / (l.coche + l.moto),\n lower.tail = FALSE)\n# 0.195092211553117\n\n\n### Exercise 3\n\nlambda <- 9\n# 9\n\n(mu <- 1 /(5 /60))\n# 12\n\n### a)\n##\n## L ~ Geometric((mu - lambda) / mu) = Geometric(1/4)\n\n## E[L]\nlambda / (mu - lambda)\n# 3\n\n### b)\n\n## Waiting Total.\n(1 / (mu - lambda))\n# 0.3333333\n\n## Waiting in queue.\n(lambda / mu * (1 / (mu - lambda)))\n# 0.25\n\n### c)\n\n## Busy period length.\n(1 / (mu - lambda))\n# 0.333333333333333\n\n### d)\n\nR <- matrix(c(\n -lambda, lambda,\n mu, -(mu + lambda)\n), 2, 2, byrow = TRUE)\n\n(g <- - solve(R) %*% rep(1, 2))\n# 0.3703704\n# 0.2592593\n\ng[1]\n# 0.37037037037037\n", "meta": {"hexsha": "63ec07af164b2df2f4ab9f9ecf80a9048883be0b", "size": 1878, "ext": "r", "lang": "R", "max_stars_repo_path": "stochastic-processes/exams/2017-final-exam.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "stochastic-processes/exams/2017-final-exam.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "stochastic-processes/exams/2017-final-exam.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8857142857, "max_line_length": 68, "alphanum_fraction": 0.5053248136, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.748515665028682}} {"text": "#### 13-1 기초 통계\n## 대표값과 산포(변동성)\nx <- runif(50, 1, 100)\nx\nhist(x)\ny <- c(x, 1000)\ny\n\n\nmean(x)\nmean(y)\nmedian(x)\nmedian(y)\nsd(x)\nsd(y)\nrange(x)\nrange(y)\nIQR(x)\nIQR(y)\n\nboxplot(x)\nboxplot(y)\n\ninstall.packages('fBasics')\nlibrary(fBasics)\nrequire(fBasics)\nskewness(x)\nskewness(y)\n# - 추가학습: skewness와 boxcox 변환\n\n\n## 2.0 다양한 분포함수\n# binorm : 이항분포\n# f: f분포\n# geom: 기하분포\n# hyper: 초기하분포\n# nbinorm: 음이항분포\n# pois: 프와송 분포\n# t: t분포\n# unif: 균등분포\n# chisq 카이제곱분포\nset.seed(123)\n\n## 분포함수 : norm에 대해\n# dnorm(x, mean = 0, sd = 1, log = FALSE): density\n# pnorm(q, mean = 0, sd = 1, lower.tail = TRUE, log.p = FALSE): probablilty 누적확률 \n## - lower.tail = T: return P(xq)\n## - log.p = F: return Prob | log.p = T: return log(Prob)\n# qnorm(p, mean = 0, sd = 1, lower.tail = TRUE, log.p = FALSE): quantile\n #누적확률이 p가 될때의 X값\nqnorm(pnorm(6)) #이렇게 하면 6(x값)이 나온다\n# rnorm(n, mean = 0, sd = 1): random generation n samples =randn\n\n# 평균이 0이고 표준편차가 10인 정규분포에서 100개의 난수 생성.\nx <- rnorm(100, 0, 1)\nhist(x, breaks=10)\n\nplot(density(rnorm(1000000, 9, 10)))\n\n# 평균이 0이고 표준편차가 1인 정규분포로부터:\npnorm(1)\npnorm(1, lower.tail = F)\npnorm(1, log.p = T)\nexp(pnorm(1, log.p = T))\n\npnorm(1) - pnorm(-1)\npnorm(1.67) - pnorm(-1.67)\npnorm(1.96) - pnorm(-1.96)\n\n\npnorm(2)\npnorm(2) - pnorm(-2)\n\npnorm(3) - pnorm(-3)\npnorm(6) - pnorm(-6)\n\n##- 소수점 k 자리까지의 정밀도를 1 ~ 22까지 표현가능하다. 기본값은 7.\nspecify_decimal <- function(x, k) trimws(format(round(x, k), nsmall=k))\nspecify_decimal(pnorm(6) - pnorm(-6), 10)\n\n\n# density로 부터 두 값에 대한 분포확률(우도) 예측하기.\ndnorm(1.1, 1.15, 1)*dnorm(1.2, 1.15, 1)\ndnorm(1.1, 0.9, 1)*dnorm(1.2, 0.9, 1)\n\n\n# 누적 확률이 0.9가 되는 x값을 찾아라.\nq = qnorm(.9, 9, 10)\npnorm(q, 9, 10)\nz = (qnorm(.9, 9, 10) - 9)/10\nz\nqnorm(.9, 0, 1)\n\n(cps <- 1:9 / 10)\nqs = qnorm(cps, 9, 10)\nzs = (qs - 9)/10\npnorm(zs, 0, 1)\n\n# N(9, 10) 분포에서 신뢰구간이 0.9가 되는 x를 찾아라.\ntmp <- qnorm(0.05, 9, 10)\npnorm(9+9-tmp, 9, 10)\nq = 18-tmp\nz = (q-9)/10\npnorm(z, 0, 1)\n\n\n## 프와송 분포: f(n, lambda)의 이해\n# - 단위시간(단위공간)당 사건 발생 건수가 lambda일 때,\n# - 단위시간 내, n번의 사건이 발생할 확률\ndpois(1, 1.5) + ppois(0, 1.5)\nppois(1, 1.5)\nppois(3, 1.5)\nqpois(0.9, 1.5)\n\ndpois(3, 3)\ndpois(3, 1)\n\n\n# 단위시간당 1건 발생확률에서 0 ~ 5건까지 발생확률에 대한 누적합\nsum = 0\nfor (i in 0:5){\n sum = sum + dpois(i, 1)\n}\nsum\n\n# - 누적분포함수로 구하면:\nppois(5, 1)\n\n\n## 이항분포\n# - tv리모콘 문제: 채널 50에서 6번 눌렀을 때 채널 50.\n# - 6C3 (1/2)^6\n6*5*4/(3*2)*(0.5^6)\ndbinom(3, 6, 0.5) #6C3 (1/2)^6\n\n#채널 50 이하일 경우\nsum= 0\nfor (i in 0:3){\n sum = sum +dbinom(i,6,0.5)\n}\nsum\npbinom(3,6,0.5) #for문 돌린것과 동일하다\n\n\n## 2.1 기초통계량\nmean(1:10)\nsd(1:10)\nvar(1:10)\n# - 분산의 정의로부터: Var(x) = 1/(N-1) * sum[(x - mean(x))^2]\nsum( (1:10 - mean(1:10))^2 ) / (10-1)\n\n\n## 2.2 summay\n# - 알고 보면 쉽게:\nx <- 1:10\nsummary(x)\n# - 알고 보면 쉽지 않다:\nstr(boxplot(x))\nboxplot(x)$stats # data로부터 \n\n# - 왜 다를까?\nc(min(x), quantile(x, 1/4), median(x), quantile(x, 3/4), max(x))\n\nIQR(x)\nquantile(x, c(1/4, 3/4))\nqt <- quantile(x, c(1/4, 3/4), names = F)\nqt[2] - qt[1]\n\n\n## 2.3 명목형 변수에 대한 최빈값(mode)\nx <- factor(c(\"a\", \"b\", \"c\", \"c\", \"c\", \"d\", \"d\"))\nx\nstr(x)\ntable(x) # named vector\nstr(table(x))\nwhich.max(table(x))\nstr(which.max(table(x))) # named vector: https://rpubs.com/sowmya21jan/338762\n\nnames(table(x))[which.max(table(x))]\n\nsummary(x)\nstr(summary(x))\n\n\n#### 13-2 t- 검정: 평균의 차 검정 ####\n\n## -------------------------------------------------------------------- ##\nmpg <- as.data.frame(ggplot2::mpg)\n\nlibrary(dplyr)\nmpg_diff <- mpg %>% \n select(class, cty) %>% \n filter(class %in% c(\"compact\", \"suv\"))\n\nhead(mpg_diff)\ntable(mpg_diff$class)\n\nt.test(data = mpg_diff, cty ~ class, var.equal = T)\n\ntest <- aov(cty ~ class, data = mpg)\nsummary(test)\n\n## -------------------------------------------------------------------- ##\nmpg_diff2 <- mpg %>% \n select(fl, cty) %>% \n filter(fl %in% c(\"r\", \"p\")) # r:regular, p:premium\n\ntable(mpg_diff2$fl)\n\nt.test(data = mpg_diff2, cty ~ fl, var.equal = T)\n\n\n#### 13-3 ####\n\n## -------------------------------------------------------------------- ##\neconomics <- as.data.frame(ggplot2::economics)\ncor.test(economics$unemploy, economics$pce)\n\n\n## -------------------------------------------------------------------- ##\nhead(mtcars)\ncar_cor <- cor(mtcars) # 상관행렬 생성\nround(car_cor, 2) # 소수점 셋째 자리에서 반올림해서 출력\n\ninstall.packages(\"corrplot\")\nlibrary(corrplot)\n\ncorrplot(car_cor)\n\ncorrplot(car_cor, method = \"number\")\n\ncol <- colorRampPalette(c(\"#BB4444\", \"#EE9988\", \"#FFFFFF\", \"#77AADD\", \"#4477AA\"))\n\ncorrplot(car_cor,\n method = \"color\", # 색깔로 표현\n col = col(200), # 색상 200개 선정\n type = \"lower\", # 왼쪽 아래 행렬만 표시\n order = \"hclust\", # 유사한 상관계수끼리 군집화\n addCoef.col = \"black\", # 상관계수 색깔\n tl.col = \"black\", # 변수명 색깔\n tl.srt = 45, # 변수명 45도 기울임\n diag = F) # 대각 행렬 제외\n\n", "meta": {"hexsha": "7500afd0a0b3603d4f5cfd8501aa005eadfbe1a5", "size": 4734, "ext": "r", "lang": "R", "max_stars_repo_path": "R/practice_Part13.r", "max_stars_repo_name": "dayoungMM/TIL", "max_stars_repo_head_hexsha": "b844ef5621657908d4c256cdfe233462dd075e8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/practice_Part13.r", "max_issues_repo_name": "dayoungMM/TIL", "max_issues_repo_head_hexsha": "b844ef5621657908d4c256cdfe233462dd075e8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/practice_Part13.r", "max_forks_repo_name": "dayoungMM/TIL", "max_forks_repo_head_hexsha": "b844ef5621657908d4c256cdfe233462dd075e8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4016393443, "max_line_length": 81, "alphanum_fraction": 0.5407689058, "num_tokens": 2388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7482537751857997}} {"text": "sample_size=6\r\nsw2=0.0153\r\ny1bar=1.175\r\ny2bar=1.293\r\ny3bar=1.328\r\ny4bar=1.415\r\ny5bar=1.500\r\nt=5\r\nalpha=0.05\r\nF_value=qf(1-alpha,t-1,25)\r\n\r\na=c(4,-1,-1,-1,-1)# for control vs agents\r\n# test statistic\r\nvl=sw2*((a[1]^2+a[2]^2+a[3]^2+a[4]^2+a[5]^2)/sample_size)\r\nprint(vl)\r\nS=sqrt(vl)*sqrt((t-1)*F_value)\r\nprint(S)\r\n# critcal value\r\nl=abs(4*y1bar-y2bar-y3bar-y4bar-y5bar)\r\nprint(l)\r\nif(S predicted.gender.ratio[1], TRUE, FALSE\r\n )\r\n\r\n if(is_female_ratio_increasing) { # becoming more female biased\r\n \r\n parity.year <- ifelse(\r\n gender.ratio.at.present < 0.5,\r\n # record first year it got within 5% of parity\r\n year.range[which(predicted.gender.ratio > 0.45)][1], \r\n \"Female-biased and becoming more so\"\r\n )\r\n\r\n } else { # becoming more male biased\r\n \r\n parity.year <- ifelse(\r\n gender.ratio.at.present > 0.5, \r\n # record first year it got within 5% of parity\r\n year.range[which(predicted.gender.ratio < 0.55)][1],\r\n \"Male-biased and becoming more so\"\r\n )\r\n\r\n }\r\n\r\n return(data.frame(\r\n gender.ratio.at.present = gender.ratio.at.present,\r\n current.rate.of.change = current.rate.of.change,\r\n parity.year = parity.year, r = r, c = c,\r\n stringsAsFactors = F)\r\n )\r\n}\r\n\r\n", "meta": {"hexsha": "4321eaa53b3c54ef50dc1785cbdedb60320f5672", "size": 3577, "ext": "r", "lang": "R", "max_stars_repo_path": "2020-08-31-jsa-type-v2-ch3-gender/analysis1/util.r", "max_stars_repo_name": "eunices/masters-thesis-code", "max_stars_repo_head_hexsha": "6eb3a5543880644fbd24305b0670bf7c1b350a3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020-08-31-jsa-type-v2-ch3-gender/analysis1/util.r", "max_issues_repo_name": "eunices/masters-thesis-code", "max_issues_repo_head_hexsha": "6eb3a5543880644fbd24305b0670bf7c1b350a3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020-08-31-jsa-type-v2-ch3-gender/analysis1/util.r", "max_forks_repo_name": "eunices/masters-thesis-code", "max_forks_repo_head_hexsha": "6eb3a5543880644fbd24305b0670bf7c1b350a3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9375, "max_line_length": 80, "alphanum_fraction": 0.6105675147, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7476479916569067}} {"text": "#' @title rmse\r\n#'\r\n#' @description Calculates the root mean square error (RMSE) from observed and\r\n#' predicted values.\r\n#'\r\n#' @inheritParams e\r\n#'\r\n#' @return The root mean square err or (RMSE) calculated from the observed and\r\n#' the predicted values.\r\n#'\r\n#' @details rmse = sqrt(mean((observed - predicted)^2))\r\n#'\r\n#' @examples\r\n#' o<-1:5\r\n#' p<-c(2,2,4,3,5)\r\n#' rmse(observed=o, predicted=p)\r\n#'\r\n#' @export\r\nrmse<-function(observed, predicted) return(sqrt(mean((observed - predicted)^2)))\r\n", "meta": {"hexsha": "94b05d48250e7015770b1b1c1a1c15cf3fe0c955", "size": 499, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rmse.r", "max_stars_repo_name": "cran/mapsRinteractive", "max_stars_repo_head_hexsha": "19f6f26deadabe89a334e605578a26284439f722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/rmse.r", "max_issues_repo_name": "cran/mapsRinteractive", "max_issues_repo_head_hexsha": "19f6f26deadabe89a334e605578a26284439f722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/rmse.r", "max_forks_repo_name": "cran/mapsRinteractive", "max_forks_repo_head_hexsha": "19f6f26deadabe89a334e605578a26284439f722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-20T01:54:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T23:22:20.000Z", "avg_line_length": 24.95, "max_line_length": 81, "alphanum_fraction": 0.6472945892, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7475473520228064}} {"text": "#!/usr/bin/R -q -f\n#\n# R script to calculate pearson distance \n#\n# Objective: To calculate the pearson distance for a mock-up dataset\n#\n# Input : a mock-up 6-row, 2-column data frame\n#\n# Output: STDOUT, a single value for the pearson distance\n#\n\n# load dplyr package\nlibrary(dplyr)\n\n# load the mockup data into a 2 column, 6 row data frame\ndata <- data_frame(c(3,4,7,6,8,2),c(5,3,10,8,12,5))\n\n# assign the column names so the data is more readable\ncolnames(data) <- c('x', 'y')\n\n# check the data\ndata\n\n# add STDEV, MEAN, and COUNT into the dataset\nmutate(data, xmean = mean(x), sdx = sd(x), ymean = mean(y), sdy = sd(y), n1 = nrow(data)-1) %>%\n# add the intermediate value into the dataset\nmutate(xx = ((x-xmean)/(n1*sdx))*((y-ymean)/(sdy))) %>%\n# only select the intermediate value column\nselect(xx) %>%\n# sum it to get the pearson distance\nsum()\n\n", "meta": {"hexsha": "f22b942484882d87a37d9144c0f66936cdb2312f", "size": 849, "ext": "r", "lang": "R", "max_stars_repo_path": "big-data-analytics/collaborative-filtering-ranking/qw476-pearson.r", "max_stars_repo_name": "robertwenquan/nyu-course-assignment", "max_stars_repo_head_hexsha": "c03a4fb157d385b650c38feb861f283f2e1928fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-22T21:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-22T21:35:42.000Z", "max_issues_repo_path": "big-data-analytics/collaborative-filtering-ranking/qw476-pearson.r", "max_issues_repo_name": "robertwenquan/nyu-course-assignment", "max_issues_repo_head_hexsha": "c03a4fb157d385b650c38feb861f283f2e1928fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "big-data-analytics/collaborative-filtering-ranking/qw476-pearson.r", "max_forks_repo_name": "robertwenquan/nyu-course-assignment", "max_forks_repo_head_hexsha": "c03a4fb157d385b650c38feb861f283f2e1928fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7272727273, "max_line_length": 95, "alphanum_fraction": 0.6772673734, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7475063588355892}} {"text": "#############################################\n# Data Preparation\n#############################################\n# Set the random number generator or seed\n# to make the results reproducible\nset.seed(314159)\n\n# set the number of items I and persons P\nI.items <- 30\nP.persons <- 2000\n\n# set the fixed item and population parameters\na.disc <- 1 + runif(I.items, -0.5, 0.5)\nb.diff <- seq(-3,3,length = I.items )\n\nmean.theta <- 0\nsig2.theta <- (1.25^2)\n\n# generate thetas and the I x P matrix of response probabilities\ntheta.abl <- rnorm(P.persons, mean = mean.theta, sd = sqrt(sig2.theta))\nterm.1 <- outer(theta.abl,a.disc)\nterm.2 <- matrix(rep(a.disc*b.diff, P.persons), nrow = P.persons, byrow = TRUE)\nP.prob <- plogis(term.1 - term.2) ### 1/(1+exp(term.2-term.1))\n\n# generate the 0/1 responses U as a matrix of Bernoulli draws\nU <- ifelse(runif(I.items * P.persons) < P.prob, 1, 0)", "meta": {"hexsha": "7c6b786a96dbaf4124d85b9beb9c709f95ed2696", "size": 878, "ext": "r", "lang": "R", "max_stars_repo_path": "2PL/functions/response_generate.r", "max_stars_repo_name": "jevanluo/BayesianIRT", "max_stars_repo_head_hexsha": "788b34e951968222493b7ad2c65f3086ddff84e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-23T03:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:45:25.000Z", "max_issues_repo_path": "2PL/functions/response_generate.r", "max_issues_repo_name": "jevanluo/BayesianIRT", "max_issues_repo_head_hexsha": "788b34e951968222493b7ad2c65f3086ddff84e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2PL/functions/response_generate.r", "max_forks_repo_name": "jevanluo/BayesianIRT", "max_forks_repo_head_hexsha": "788b34e951968222493b7ad2c65f3086ddff84e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7692307692, "max_line_length": 79, "alphanum_fraction": 0.6127562642, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7470805374255208}} {"text": "#the code for calculating EM must first be run for initializing the means!\n\n\n#use of stats library\n# mixtools library\nlibrary(\"mixtools\")\nlibrary(\"stats\")\nlibrary(\"mvtnorm\")\n\n#EM algorithm\n\npdf('standardized_em.pdf')\n\n#--------------(1)-------Initialize the means μk , covariances Σk and mixing coefficients πk-------- \n\n\n\t#in the following comment there are the means in case the k-means algorithm is not run.\n\n\tk=3;\n\t#construct the covariance matrices\n\t#add each covariance matrix to a node in the list S\n\t\n\ta = matrix(nrow=3,ncol=2)\n\tS = rep(list(a),3)\n\tfor(t in 1:k){\n\t\ta= which(rnk_matrix==t)\n\t\ttr1=matrix(nrow=length(a),ncol=2)\n\t\tcounter1=1;\n\t\tfor (i in a){\n\t\t\ttr1[counter1,1]=dataset[i,1]\n\t\t\ttr1[counter1,2]=dataset[i,2]\n\t\t\tcounter1= counter1+1\n\t\t}\n\t\tS[[t]]=cov(tr1)\n\t}\n\t\t\n\tN=length(dataset[,1])\n\t#array pk -> mixing coefficients \n\t\n\tpk = matrix(nrow=3,ncol=1)\n\tfor(t in 1:k){\n\t\tpk[t,] = length(which(rnk_matrix==t))/N\n\t}\n\n\t\n\n\n\npar(mfrow=c(2,2))\n \nplot(dataset[,1],dataset[,2],col=\"green\",xlim=c(-3.2,3.2),ylim=c(-3.2,3.2),panel.first = grid(),xlab=\"x\",ylab=\"y\",pch=20,main=\"Initialized data from kmeans\")\ncolor_=rgb(0,0,0,alpha=0.6) \npoints(mean_Ar[,1],mean_Ar[,2],col=color_,pch=4)\nellipse(mean_Ar[1,], S[[1]], alpha = 0.32, npoints = 250,col=color_, newplot = FALSE, draw = TRUE)\nellipse(mean_Ar[2,], S[[2]], alpha = 0.32, npoints = 250,col=color_, newplot = FALSE, draw = TRUE)\nellipse(mean_Ar[3,], S[[3]], alpha = 0.32, npoints = 250,col=color_, newplot = FALSE, draw = TRUE)\n\n\n\n#-----evaluate the initial value of the log likelihood-------\n\n\nlikelihood=0;\n\n\n\nNk =matrix(nrow=k,ncol=1)\nfor(t in 1:k){\n\tNk[t,1] = length(which(rnk_matrix==t));\t\n}\n\n#evaluate the likelihood using the formula\nlikelihood=0;\nfor(i in 1:N){\n\tsum1=0;\n\tfor(t in 1:k){\n\t\n\tb=S[t];\n \tb = matrix(unlist(b),ncol = 2, byrow = TRUE);\t\nsum1=sum1 +pk[t,]*( ((2*pi)^(-2/2)) )*( (det(b)) ^(-0.5) )*exp(-0.5*t(as.vector(dataset[i,]-mean_Ar[t,]))%*%(solve(b))%*%(as.vector(dataset[i,]-mean_Ar[t,])));\n\t}\n\tlikelihood = likelihood +log(sum1);\n}\n\nprint(likelihood)\n\n\n#----------------(2)----------------------------E step. Evaluate the responsibilities using the current parameter values-------\n\n\nflag=0;\n#rg is the responsibility gamma \nrg=matrix(nrow=N,ncol=k)\n\n\nlh<-c(likelihood)\nif(likelihood>0 ){\nnew_likelihood =likelihood-10000000;\n}else{\nnew_likelihood =likelihood+10000000000\n}\n\n\n\n\n\n\nwhile(abs(new_likelihood-likelihood)>1){\nif(flag==0){\nflag=1;\nnew_likelihood =likelihood;\n}\n\n\n\nlikelihood=new_likelihood;\n\n\n\t\n\t\nfor(i in 1:N){\t\nfor(t in 1:k){\t\n\t\tsum1=0;\t\t\t\t\n\n\t\tfor(j in 1:k){ \n\t\t\n\t\t\tb=S[[j]];\n \t\t\tb = matrix(unlist(b),ncol=2, byrow=TRUE);\n\t\t\ta=pk[j,1]*dmvnorm(dataset[i,], mean_Ar[j,],b);\n\t\t\tsum1 = sum1 + a;\n\t\t}\n\n\t\tb=S[[t]];\n \t\tb = matrix(unlist(b),ncol = 2, byrow = TRUE);\n\t a=pk[t,]*dmvnorm(dataset[i,], mean_Ar[t,],b);\n\trg[i,t]=a/sum1;\n\t}\n}\n\n\n#----------------(3)----------M step. Re-estimate the parameters using the current responsibilities------------------------------------\n\n\n#find new mean\nfor(t in 1:k){\t\n\tsum1=c(0,0);\n\tfor(i in 1:N){\n\t\tsum1= sum1+rg[i,t]*dataset[i,]\n\t}\n\tmean_Ar[t,]= sum1/Nk[t,1] \t\t\n}\n\n\n#find new Nk\nfor(j in 1:k){\nNk[j,1]=0;\nfor(i in 1:N){\n\tNk[j,1] = Nk[j,1] + rg[i,j]\n}\n}\n\n#find new covariance matrix\nfor(t in 1:k){\t\n\tsum1=matrix(c(0,0,0,0),nrow=2,ncol=2);\n\tfor(i in 1:N){\n\t\tsum1= sum1+rg[i,t]*(dataset[i,]- mean_Ar[t,])%*%t(dataset[i,]- mean_Ar[t,])\n\t}\n\tS[[t]]= sum1/Nk[t,1] \t\t\n}\n\n\n\n\n\n\n\n\n\n#find new mixture coefficient\nfor(t in 1:k){\t\npk[t,]=Nk[t,1]/N;\n}\n\n\n#(4)-------------------------Evaluate the log likelihood--------------\n\n\n#evaluate the likelihood using the formula\nnew_likelihood=0;\nfor(i in 1:N){\nsum1=0;\n\tfor(t in 1:k){\n\t\n\tb=S[t];\n \tb = matrix(unlist(b),ncol = 2, byrow = TRUE);\t\nsum1=sum1 +pk[t,]*( ( (2*pi)^(-2/2)))* ( (det(b)) ^(-0.5) )*exp(-0.5*t(as.vector(dataset[i,]-mean_Ar[t,]))%*%(solve(b))%*%(as.vector(dataset[i,]-mean_Ar[t,])));\n\t}\n\tnew_likelihood = new_likelihood +log(sum1);\n}\n\nprint(new_likelihood)\nlh= c(lh,new_likelihood)\n\n\n\n#-----------------plots--------------------------------------------\n\n#---------------------plot classes-----------------------------\n\nplot(0,0,col=\"white\",xlim=c(-3.2,3.2),ylim=c(-3.2,3.2),pch=20,panel.first = grid(),xlab=\"x\",ylab=\"y\",main=toString(likelihood))\nfor (i in 1:N){\n\n\ncolor_=rgb(0.9,0,0,alpha=rg[i,1]) \npoints(dataset[i,1],dataset[i,2],col=color_,pch=20)\n\ncolor_=rgb(0,0.9,0,alpha=rg[i,2]) \npoints(dataset[i,1],dataset[i,2],col=color_,pch=20)\n\ncolor_=rgb(0,0,0.9,alpha=rg[i,3]) \npoints(dataset[i,1],dataset[i,2],col=color_,pch=20)\n\n\n}\ncolor_=rgb(0,0,0,alpha=0.4) \npoints(mean_Ar[,1],mean_Ar[,2],col=color_,pch=4)\n\nellipse(mean_Ar[1,], S[[1]], alpha = 0.32, npoints = 250,col=color_, newplot = FALSE, draw = TRUE)\nellipse(mean_Ar[2,], S[[2]], alpha = 0.32, npoints = 250,col=color_, newplot = FALSE, draw = TRUE)\nellipse(mean_Ar[3,], S[[3]], alpha = 0.32, npoints = 250,col=color_, newplot = FALSE, draw = TRUE)\n}\n\n\n\n\n\n\n\n\n\n\n#plot one-standard deviation\n#---------------end of while------if there is convergence in likelihood stop\n\n\n\n\n\n\n\n\n\ndev.off()\n\nprint(mean_Ar)\nprint(S)\nprint(pk)\n\n", "meta": {"hexsha": "7e5599261a2bf484c7edefafd971efd527b37dde", "size": 5067, "ext": "r", "lang": "R", "max_stars_repo_path": "MachineLearning/Project3/task3/standardized_task3b_code.r", "max_stars_repo_name": "StylianosChatzichronis/R", "max_stars_repo_head_hexsha": "f13509fab53ff70f601a124f2965c2a4ff695bdc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MachineLearning/Project3/task3/standardized_task3b_code.r", "max_issues_repo_name": "StylianosChatzichronis/R", "max_issues_repo_head_hexsha": "f13509fab53ff70f601a124f2965c2a4ff695bdc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MachineLearning/Project3/task3/standardized_task3b_code.r", "max_forks_repo_name": "StylianosChatzichronis/R", "max_forks_repo_head_hexsha": "f13509fab53ff70f601a124f2965c2a4ff695bdc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5637065637, "max_line_length": 163, "alphanum_fraction": 0.5960134202, "num_tokens": 1760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7468423129589103}} {"text": "source(\"data_Poisson.r\")\n\nlibrary(npowerPrioR)\n\npo.data <- list(\n N0 = N_0,\n y0 = y_0,\n alpha0 = alpha_0,\n beta0 = beta_0,\n a_0 = NA\n)\n###\nget_l_a0_poisson <- function(y0, n0, alpha0, beta0, a_0){\n logPprime <- sum(lfactorial(y0))\n S <- sum(y0)\n ans <- -a_0 * logPprime + lgamma(a_0 * S + alpha0) - (a_0 * S + alpha0)* log(a_0 *n0 + beta0) + (alpha0*log(beta0) - lgamma(alpha0))\n return(ans)\n}\n############\nl_a0 <- function(x) {\n get_l_a0_poisson(\n y0 = po.data$y0,\n n0 = po.data$N0,\n alpha0 = po.data$alpha0,\n beta0 = po.data$beta0,\n a_0 = x\n )\n}\nl_a0 <- Vectorize(l_a0)\n###\nl_a0_p <- function(x) numDeriv::grad(l_a0, x)\nl_a0_p <- Vectorize(l_a0_p)\nl_a0_pp <- function(x) numDeriv::hessian(l_a0, x)\nl_a0_pp <- Vectorize(l_a0_pp)\n\nanalytical_l_p <- function(x){\n logPprime <- sum(lfactorial(y_0))\n S <- sum(y_0)\n tt <- alpha_0 + S*x\n gg <- beta_0 + N_0 * x\n result <- -logPprime -N_0 *tt/gg - S*log(gg) + S * digamma(tt)\n return(result)\n}\n####################\nJ <- 20\nmaxA <- 1\n\nadaptive.ca0.estimates <- read.csv(paste(\"../../data/constant_data/Poisson_logCA0_adaptive_J=\", J, \".csv\", sep = \"\")) \n\n\ncurve(l_a0_p, 0, maxA, lwd = 2, lty = 2, col = 2, ylab = \"\", xlab = expression(a[0]), ylim = c(-200, 200))\nabline(h = 0 , lwd = 2 , lty = 3)\ncurve(l_a0, 0, maxA, lwd = 2, add = TRUE)\npoints(adaptive.ca0.estimates$a0, adaptive.ca0.estimates$lc_a0)\ncurve(l_a0_pp, 0, maxA, lwd = 2, col = 3, add = TRUE)\npoints(adaptive.ca0.estimates$a0, adaptive.ca0.estimates$second_deriv_lc, col = 3)\nlegend(x = \"bottomright\", legend = c(\"l(a_0)\", \"l'(a_0)\", \"l''(a_0)\"), col = 1:3, lwd = 2, bty = 'n')\npoints(adaptive.ca0.estimates$a0, adaptive.ca0.estimates$deriv_lc, col = 2)\n\n######################################\nmidpoint_integrate_la0 <- function(x_preds, fit){\n ## takes a grid of values for the input and a fit object that gives predictions (GLM, GAM, etc) and\n ## Gives the integrated function\n n <- length(x_preds)\n delta <- (x_preds[2]-x_preds[1])\n midpoints <- 0.5*(x_preds[2:n] + x_preds[1:(n-1)])\n ans <- cumsum(predict(fit, newdata = data.frame(a0 = midpoints))) * delta\n ans <- c(0, ans)\n return(ans)\n}\n\nfit.gam <- mgcv::gam(lc_a0 ~ s(a0, k = J + 1), data = adaptive.ca0.estimates)\nderiv.gam.fit <- mgcv::gam(deriv_lc ~ s(a0, k = J + 1), data = adaptive.ca0.estimates)\n\nK <- 20000\npred_a0s <- seq(0, maxA, length.out = K)\n\npreds.gam <- get_band(fit.gam, xpred = pred_a0s)\nderiv.preds <- midpoint_integrate_la0(pred_a0s, deriv.gam.fit)\n\ntrue.lca0s <- l_a0(pred_a0s)\n\ngam.preds.list <- list(\n gam = data.frame (a0 = pred_a0s, lca0 = preds.gam$mean, dev = preds.gam$mean - true.lca0s, lwr = preds.gam$lwr,\n upr = preds.gam$upr, approximating_function = \"gam\", design = \"adaptive\"),\n derivative = data.frame (a0 = pred_a0s, lca0 = deriv.preds, dev = deriv.preds - true.lca0s, lwr = NA, upr = NA,\n approximating_function = \"gam-derivative\", design = \"adaptive_numerical\")\n)\n\n## RMSE\nlapply(gam.preds.list, function(pred) sqrt(mean( (pred$lca0 - true.lca0s)^2 )) )\n## MAD\nlapply(gam.preds.list, function(pred) mean( abs(pred$lca0 - true.lca0s) )) \n\n## RMSE, a0 < 1\nlapply(gam.preds.list, function(pred) sqrt(mean( (pred[pred$a0 < 1, ]$lca0 - true.lca0s[pred_a0s < 1])^2 )) )\n## MAD, a0 < 1\nlapply(gam.preds.list, function(pred) mean( abs(pred[pred$a0 < 1, ]$lca0 - true.lca0s[pred_a0s < 1]) )) \n\n### Exporting\n\nforplot_ca0 <- do.call(rbind, gam.preds.list)\n\nwrite.csv(forplot_ca0, file = paste(\"../../data/constant_data/fitted_predictions_lca0_Poisson_J=\", J, \".csv\", sep = \"\"),\n row.names = FALSE)\n\nlibrary(ggplot2)\n\ndev_plot <- ggplot(data = forplot_ca0, aes(x = a0, y = dev, colour = approximating_function, fill = approximating_function)) +\n geom_line() +\n scale_x_continuous(expression(a[0])) +\n theme_bw(base_size = 16)\ndev_plot\n\np0 <- ggplot(data = forplot_ca0, aes(x = a0, y = lca0, colour = approximating_function, fill = approximating_function)) +\n geom_line() +\n geom_ribbon(aes(min = lwr, max = upr), alpha = .4) +\n geom_point(data = adaptive.ca0.estimates,\n mapping = aes(x = a0, y = lc_a0), colour = \"black\", alpha = .4, size = 5, inherit.aes = FALSE) + \n stat_function(fun = l_a0, linetype = \"dashed\", size = 1.2, colour = \"black\") + \n scale_x_continuous(expression(a[0])) +\n scale_y_continuous(expression(log(c(a[0])))) +\n theme_bw(base_size = 20) + \n theme(legend.position = \"bottom\",\n legend.justification = \"centre\",\n legend.title = element_blank(),\n strip.background = element_blank(),\n strip.text.y = element_blank(),\n legend.margin = margin(0, 0, 0, 0),\n legend.box.margin = margin(0, 0, 0, 0))\np0 \n\nggsave(p0, filename = paste(\"../../figures/estimates_log_ca0_Poisson_J=\", J, \".pdf\", sep = \"\"), dpi = 300)\n", "meta": {"hexsha": "6b7c77a235d72f3b324367295214eca1343b5d5a", "size": 4789, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Poisson/simple_Poisson_plot_c(a0).r", "max_stars_repo_name": "maxbiostat/propriety_power_priors", "max_stars_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Poisson/simple_Poisson_plot_c(a0).r", "max_issues_repo_name": "maxbiostat/propriety_power_priors", "max_issues_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-29T19:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-29T15:58:08.000Z", "max_forks_repo_path": "code/Poisson/simple_Poisson_plot_c(a0).r", "max_forks_repo_name": "maxbiostat/propriety_power_priors", "max_forks_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7388059701, "max_line_length": 134, "alphanum_fraction": 0.630194195, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7467639840631877}} {"text": "library(tidyverse)\nlibrary(R0)\nlibrary(scales)\nlibrary(incidence)\nlibrary(EpiDynamics)\n\n# https://cran.r-project.org/web/packages/earlyR/earlyR.pdf\n## example: onsets on days 1, 5, 6 and 12; estimation on day 24\n\n\n# https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7014672/\nweibull_mean = 6.4\nweibull_sd = 2.3\n\ne = exp(1)\nr0=3.765201\nincubation_period = 5\ninfection_rate = r0/incubation_period\nt = 0:65\nn0=1\ne = exp(1)\nn_t = n0*e^(infection_rate*t)\npar(mfrow = c(1,1))\nplot(t, n_t)\n\nn_t2 = 0.007900 * r0^(t/incubation_period)\nplot(n_t2, n_t)\n\n##### pull in data ####\njohns_hopkins_cases = read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv') %>%\n pivot_longer(cols = matches('^([0-9])'), names_to = 'date', values_to = 'cases')\n\nnames(johns_hopkins_cases) = names(johns_hopkins_cases) %>% tolower() %>% str_replace('[\\\\/]', '_')\n\nus_jh_cases = filter(johns_hopkins_cases, country_region == 'US') %>%\n mutate(date = as.Date(date, format = '%m/%d/%y')) %>%\n arrange(date) %>%\n mutate(\n lag_cases = lag(cases, 1), \n new_cases = cases - lag_cases,\n new_cases = ifelse(is.na(new_cases), 1, new_cases),\n t = as.numeric(date - min(date))\n ) %>%\n filter(\n date <= as.Date('2020-03-26')\n )\n\n# fit a simple exponnetial model using non-linear least squares\nexponential_model_long_incubation = nls(cases ~ case_networks * r0^(t/6.4), data = us_jh_cases, \n start = list(case_networks = 1, r0 = 2.5))\nsummary(exponential_model_long_incubation)\n\nexponential_model_short_incubation = nls(cases ~ case_networks * r0^(t/5), data = us_jh_cases, \n start = list(case_networks = 1, r0 = 2.5))\nsummary(exponential_model_short_incubation)\n\n\n\nmGT_weibull <- generation.time(\"weibull\", c(6.4, 2.3))\nmGT_gamma <- generation.time(\"gamma\", c(5, 1.5))\n\npar(mfrow = c(2, 1))\nplot(mGT_weibull$time, mGT_weibull$GT)\nlines(mGT_weibull$time, mGT_weibull$GT)\nplot(mGT_gamma$time, mGT_gamma$GT)\nlines(mGT_gamma$time, mGT_gamma$GT)\n\nest.R0.EG(us_jh_cases$new_cases, mGT_weibull, begin=as.integer(1), end=as.integer(length(us_jh_cases$new_cases)))\nest.R0.EG(us_jh_cases$new_cases, mGT_gamma, begin=as.integer(1), end=as.integer(length(us_jh_cases$new_cases)))\n\n\n\n\n\n\n# https://web.stanford.edu/~jhj1/teachingdocs/Jones-Epidemics050308.pdf\n# λ(t) = λ(0)e^(Λt)\n# Λ = ν(R0 − 1)\n\n# Formula: cases ~ case_networks * r0^(t/6.4)\n# \n# Parameters:\n# Estimate Std. Error t value Pr(>|t|) \n# case_networks 9.14908 2.09934 4.358 4.17e-05 ***\n# r0 2.48856 0.05072 49.063 < 2e-16 ***\n# ---\n# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n# \n# Residual standard error: 8936 on 74 degrees of freedom\n# \n# Number of iterations to convergence: 9 \n# Achieved convergence tolerance: 7.431e-06\n\n# Formula: cases ~ case_networks * r0^(t/5)\n# \n# Parameters:\n# Estimate Std. Error t value Pr(>|t|) \n# case_networks 0.004309 0.001168 3.691 0.000474 ***\n# r0 3.729612 0.082046 45.457 < 2e-16 ***\n# ---\n# Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1\n# \n# Residual standard error: 887.8 on 62 degrees of freedom\n# \n# Number of iterations to convergence: 23 \n# Achieved convergence tolerance: 4.429e-06\n\n# fit using existing R package, R0\n\n# this is the generation time or incubation period\n# https://annals.org/aim/fullarticle/2762808/incubation-period-coronavirus-disease-2019-covid-19-from-publicly-reported\n\n# https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7014672/\n# mGT <- generation.time(\"gamma\", c(6.5, 2.6))\n\n\n# Reproduction number estimate using Exponential Growth method.\n# R : 3.836266[ 3.799067 , 3.873994 ]\n\n\n### plot confirmed vs. predicted ###\nus_jh_cases$simple_exp_prediction = predict(simple_exponential_model)\nus_jh_cases_long = pivot_longer(us_jh_cases, cols = c('simple_exp_prediction', 'cases'))\n\n\nggplot(us_jh_cases_long, aes(date, value, colour = name)) +\n geom_line() +\n scale_colour_hue(name = 'Estimate', labels = c('cases' = 'Confirmed Cases', 'simple_exp_prediction' = 'Modeled Cases')) +\n scale_y_continuous(labels = comma) +\n labs(x = 'Date', y = 'Cases', title = 'Exponential Growth Model vs. Confirmed Cases')\nggsave('exp_growth_vs_cases.png', height = 6, width = 6, units = 'in', dpi = 600)\n\n\n# get shape/scale for weibull distribution\nfit_weibull = function(pars) {\n shape = pars[1]\n scale = pars[2]\n the_dist = rweibull(10000, shape, scale)\n the_sd = abs(sd(the_dist) - 2.3)\n the_mean = abs(mean(the_dist) - 6.4)\n return(\n the_sd * the_mean\n )\n}\nthe_solution = optim(par = c(3, 7), fn = fit_weibull)\n# \n# > the_solution$par\n# [1] 3.005484 7.201339\nthe_weibull = rweibull(1000, the_solution$par[1], the_solution$par[2])\n# \n# r0_dist = map_dbl(the_weibull, function(gen_time){\n# return_val = NA\n# tryCatch({\n# simple_exponential_model = nls(cases ~ case_networks * r0^(t/gen_time), data = us_jh_cases, \n# start = list(case_networks = 1, r0 = 2.5))\n# \n# return_val = coef(simple_exponential_model)[2] \n# }, error = function(e){\n# return(return_val)\n# })\n# \n# return(return_val)\n# })\nsummary(r0_dist)\n\ncumulative_dist = tibble(\n time = mGT$time,\n proportion = mGT$GT,\n cum_prop = cumsum(proportion)\n)\n\n?SIR\n\n# covid\nparameters <- c(beta = 2.5/5, gamma = 1/5)\ninitials <- c(S = 1 - 1e-06, I = 1e-06, R = 1 - (1 - 1e-06 - 1e-06))\n\ncovid_sir <- SIR(pars = parameters, init = initials, time = 0:180)\n\n# flu\nparameters <- c(beta = 1.3/5, gamma = 1/5)\ninitials <- c(S = 1 - 1e-06, I = 1e-06, R = 1 - (1 - 1e-06 - 1e-06))\n\n# Solve and plot.\nflu_sir <- SIR(pars = parameters, init = initials, time = 0:180)\n# PlotMods(sir)\n\ndistancing_effect = 0.6\n\ncomb_sirs = tibble(\n time = covid_sir$time, \n covid_s = covid_sir$results$S * 15e6,\n new_cases = round(lag(covid_s, 1) - covid_s),\n covid_i = covid_sir$results$I,\n flu_i = flu_sir$results$I\n) %>%\n mutate(\n new_cases = ifelse(is.na(new_cases), 0, new_cases),\n deaths = rbinom(length(comb_sirs$new_cases), comb_sirs$new_cases, prob = 0.004)\n )\n\ncomb_sirs$deaths\nsum(comb_sirs$new_cases, na.rm = T) / 60e6\nsum(comb_sirs$deaths, na.rm = T)\n\nfilter(comb_sirs, time <= 42) %>% pull(deaths) %>% sum(na.rm=T)\n\nggplot(comb_sirs, aes(time, deaths)) +\n geom_point()\n\nsum(comb_sirs$covid_i * 19e6)\n\nsum(comb_sirs$flu_deaths)\nsum(comb_sirs$covid_deaths)\n\nggplot(comb_sirs, aes(time)) +\n geom_line(aes(y = covid_i)) +\n geom_line(aes(y = flu_i))\nsum(comb_sirs$covid_i)\n\n# http://rstudio-pubs-static.s3.amazonaws.com/6852_c59c5a2e8ea3456abbeb017185de603e.html\n\n# simulate proportion of deaths\n# x1 = 1:(30*6)\n# \n# z = 0.15 + 0.015*x1 \n# pr = 1/(1+exp(-z)) # pass through an inv-logit function\n# y = rbinom(length(x1),1,pr) # bernoulli response variable\n# \n# #now feed it to glm:\n# df = data.frame(y=y,x1=x1)\n# mod = glm( y~x1,data=df,family=\"binomial\")\n# \n# plot(x1, predict(mod, type = 'response')) \n# summary(pr)\n# \n# \n\n", "meta": {"hexsha": "57bbc0a207e40e6d03e3d635567e79912bb7ce10", "size": 7023, "ext": "r", "lang": "R", "max_stars_repo_path": "Projects/COVID-19/scripts/investigations/compute_covid_r0.r", "max_stars_repo_name": "vishalbelsare/Public_Policy", "max_stars_repo_head_hexsha": "4f57140f85855859ff2e49992f4b7673f1b72857", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-09T01:39:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T19:11:44.000Z", "max_issues_repo_path": "Projects/COVID-19/scripts/investigations/compute_covid_r0.r", "max_issues_repo_name": "vishalbelsare/Public_Policy", "max_issues_repo_head_hexsha": "4f57140f85855859ff2e49992f4b7673f1b72857", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-06-03T20:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-07T00:03:58.000Z", "max_forks_repo_path": "Projects/COVID-19/scripts/investigations/compute_covid_r0.r", "max_forks_repo_name": "vishalbelsare/Public_Policy", "max_forks_repo_head_hexsha": "4f57140f85855859ff2e49992f4b7673f1b72857", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-06-04T22:48:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-09T14:00:22.000Z", "avg_line_length": 29.3849372385, "max_line_length": 188, "alphanum_fraction": 0.6656699416, "num_tokens": 2451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7467639806544583}} {"text": "# 4. faza: Analiza podatkov\n\n\n#############################################################\n#REGRESIJSKA PREMICA ZA ŠTEVILO UMRLIH V CESTNOPROMETNIH NESREČAH V NASLEDNJIH LETIH\n\ngrup <- group_by(umrli, Leto)\numrli_slo <- summarise(grup, Stevilo=(sum(Umrli, na.rm = TRUE)))\numrli_slo <- transform(umrli_slo, Stevilo = (Stevilo / 12))\numrli_slo$Stevilo <- round(umrli_slo$Stevilo, digits=2)\nprileg <- lm(data = umrli_slo, Stevilo ~ Leto )\nm <- data_frame(Leto=seq(2018,2022,1))\nnapoved <- mutate(m, Stevilo=predict(prileg,m))\nnapoved$Stevilo <- round(napoved$Stevilo, digits = 2)\n\ngraf_regresija_umrli <- ggplot(umrli_slo, aes(x=Leto, y=Stevilo)) +\n geom_smooth(method=lm, fullrange = TRUE, color = 'blue') +\n geom_point(data=napoved, aes(x=Leto, y=Stevilo), color='red', size=2) +\n geom_point() +\n labs(title='Napoved števila smrti v prometu v naslednjih letih', y=\"Stevilo\")\n\n\n\n# REGRESIJSKA PREMICA ZA ŠTEVILO OSEBNIH AVTOMOBILOV NA 1000 PREBIVALCEV V PRIHODNOSTI\navti <- group_by(avtomobili,Leto)\navti1 <- summarise(avti, Stevilo=sum(Avtomobili, na.rm=TRUE))\navti_regije <- transform(avti1, Stevilo = Stevilo / 12)\navti_regije$Stevilo <- round(avti_regije$Stevilo, digits=2)\nprileg <- lm(data = avti_regije, Stevilo ~ Leto )\nnapoved_avti <- mutate(m, Stevilo=predict(prileg, m))\n\ngraf_regresija_avti <- ggplot(avti_regije, aes(x=Leto, y=Stevilo)) +\n geom_smooth(method=lm, fullrange = TRUE, color = 'blue') +\n geom_point(data=napoved_avti, aes(x=Leto, y=Stevilo), color='red', size=2) +\n geom_point() +\n labs(title='Napoved števila osebnih avtomobilov na 1000 prebivalcev v prometu v naslednjih letih', y=\"Stevilo\")\n\n\n\n\n##################################################################################\n# CLUSTER REGIJ ŠTEVILO UMRLIH V CESTNOPROMETNIH NESREČAH\n\n# umrli\ngrp <- group_by(umrli, Regija)\numrli_sum <- summarise(grp, vsote=sum(Umrli, na.rm = TRUE))\n\numrli_e <- dcast(umrli, Regija~Leto, value.var = 'Umrli' )\numrli_e <- left_join(umrli_e, umrli_sum, by = 'Regija')\numrli_e <- umrli_e[order(umrli_e$vsote, decreasing = FALSE),]\numrli_b <- umrli_e[,-19]\numrli_b <- umrli_b[,-1]\n\nn <- 5\nfit <- hclust(dist(scale(umrli_b)))\nskupine4 <- cutree(fit, n)\n\ncluster4 <- mutate(umrli_e, skupine4)\ncluster4 <- cluster4[,-2:-19]\ncolnames(cluster4) <- c(\"Regija\", \"Umrli\")\n# zemljevid\n\nregije <- unique(zemljevid$NAME_1)\nregije <- as.data.frame(regije, stringsAsFactors=FALSE) \nnames(regije) <- \"Regija\"\nskupaj <- left_join(regije, cluster4, by=\"Regija\")\n\n\nzemljevid_cluster_umrli <- ggplot() + geom_polygon(data=left_join(zemljevid, skupaj, by=c(\"NAME_1\"=\"Regija\")),\n aes(x=long, y=lat, group=group, \n fill=factor(Umrli))) +\n geom_line() +\n theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.text.y=element_blank(),\n axis.ticks.y=element_blank()) +\n guides(fill=guide_colorbar(title=\"Skupine\")) +\n ggtitle('Razvrstitev regij v skupine glede na število umrlih v cestnoprometnih nesrečah') +\n labs(x = \" \") +\n labs(y = \" \") +\n scale_fill_brewer(palette=\"YlOrRd\", na.value = \"#e0e0d1\") \n\n\n###################################################################################\n# SHINY\n\n\ngraf.regije <- function(regija){\n ggplot(umrli %>% filter(Regija %in% regija)) + aes(x=Leto, y=Umrli, group=Regija, color=Regija) +\n geom_line() + geom_point()+ xlab(\"Leto\") + ylab(\"Število umrlih\") +\n theme(axis.text.x = element_text(angle = 90, vjust = 0.3, hjust=1))\n}\n\ngraf_avto <- function(cifra) {\n ggplot(avtomobili %>% filter(Leto==cifra), aes(x=Regija, y=Avtomobili, fill=factor(Regija))) + \n ylim(0, 650) + geom_bar(stat = \"identity\") +\n xlab(\"Regija\") + ylab(\"Število avtomobilov\") + \n theme(axis.text.x = element_text(angle = 90, size = 8)) +\n labs(fill='Regija')\n\n}\n\n\n\n\n\n#==================================================================================\n\n\n", "meta": {"hexsha": "2a9460217ba5e79d97671f6ec34af730ac21aeb2", "size": 3908, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "janimetez/APPR-2018-19", "max_stars_repo_head_hexsha": "b0d9bb7e601b1302a5a806ac41f5a81e7bd21cec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analiza/analiza.r", "max_issues_repo_name": "janimetez/APPR-2018-19", "max_issues_repo_head_hexsha": "b0d9bb7e601b1302a5a806ac41f5a81e7bd21cec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-14T15:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-18T21:43:03.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "janimetez/APPR-2018-19", "max_forks_repo_head_hexsha": "b0d9bb7e601b1302a5a806ac41f5a81e7bd21cec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1851851852, "max_line_length": 113, "alphanum_fraction": 0.6284544524, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7466079096641822}} {"text": "y1bar=1.175\r\ny2bar=1.293\r\ny3bar=1.328\r\ny4bar=1.415\r\ny5bar=1.500\r\n\r\nalpha=0.05\r\ntstar=qt(1-alpha/2,df=25)\r\nMSError=0.0153\r\nLSD=tstar*sqrt((2*MSError)/6)\r\nprint(LSD)\r\n\r\n# the 95% confidence interval for y3bar-y1bar\r\nleft_i=(y3bar-y1bar)-LSD\r\nright_i=(y3bar-y1bar)+LSD\r\nprint(\"Confidence interval is\")\r\nprint(left_i)\r\nprint(right_i)", "meta": {"hexsha": "fb6a58b2f972a2b09c485fec91711f73ee325d36", "size": 330, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH9/EX9.9/Ex9_9.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH9/EX9.9/Ex9_9.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH9/EX9.9/Ex9_9.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 18.3333333333, "max_line_length": 47, "alphanum_fraction": 0.7121212121, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7466079000803091}} {"text": "#########################################\n# A toy example of Gibbs sampling\n# author: Alberto Lumbreras\n#########################################\nlibrary(mvtnorm)\nlibrary(coda)\n\n# Parameters of a multivarite gaussian\nmu1 <- 0\nmu2 <- 0\ncov12 <- 0.5 # same than cov21\n\n# Plot the target distribution\ndugly <- function(xy) {\n x <- xy[1]\n y <- xy[2]\n covariance <- matrix(c(1, cov12, cov12, 1), nrow=2)\n mvtnorm::dmvnorm(c(x,y), mean = c(mu1,mu2), sigma=covariance)\n}\nx <- seq(-3, 3, length.out=100)\ny <- seq(-3, 3, length.out=100)\nz <- matrix(NA, nrow=100, ncol=100)\ni <- 1\nfor (n in 1:length(x)){\n for(m in 1:length(y)){\n z[n,m] <- dugly(c(x[n],y[m]))\n i <- i+1\n }\n}\ncontour(x,y,z)\ntitle(\"Gibbs sampling\") \n\n# Gibbs sampler\nnsamples <-1000\nsamples <- matrix(NA,nsamples, 2)\nsamples[1,] <-c(0,0) # init\nfor(i in 2:nsamples){\n # Sample x1 given last x2\n samples[i,1] <- rnorm(1, mu1 + cov12*(samples[i-1,2]-mu2), sqrt(1-cov12^2)) # easy!\n # Sample x2 given last x1\n samples[i,2] <- rnorm(1, mu2 + cov12*(samples[i,1]-mu1), sqrt(1-cov12^2)) # easy!\n}\n\n# Plot samples showing the unidimensional steps at each iteration\nsteps.x1 <- rep(samples[,1], each=2)\nsteps.x2 <- rep(samples[,2], each=2)\nlines(steps.x1[1:(length(steps.x1)-1)], steps.x2[2:(length(steps.x2))], col=\"green\")\nlines(samples, col='yellow')\npoints(samples, col='red', pch=19, cex=0.5)\n\n# Check the MCMC traces\nplot(mcmc(samples))\n", "meta": {"hexsha": "87784c64c1543a42d6032fb78f20f19386a2bf41", "size": 1406, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/gibbs.r", "max_stars_repo_name": "alumbreras/MCMC_intro", "max_stars_repo_head_hexsha": "a07022fb09b0cc65b7c4741917ee02364ec4c6b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/gibbs.r", "max_issues_repo_name": "alumbreras/MCMC_intro", "max_issues_repo_head_hexsha": "a07022fb09b0cc65b7c4741917ee02364ec4c6b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/gibbs.r", "max_forks_repo_name": "alumbreras/MCMC_intro", "max_forks_repo_head_hexsha": "a07022fb09b0cc65b7c4741917ee02364ec4c6b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-16T18:13:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-16T18:13:26.000Z", "avg_line_length": 26.5283018868, "max_line_length": 85, "alphanum_fraction": 0.6031294452, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7465021851361829}} {"text": "# Example : 2 Chapter : 6.6 Page No: 356\n# Similar matrices with repeated eigen values\nA<-matrix(c(0,0,1,0),ncol=2)\nAev<-eigen(A)$values\nA1<-matrix(c(1,1,-1,-1),ncol=2)\nA1ev<-round(eigen(A1)$values)\nprint(\"Both th egiven matrices are similar because their eigen values are same\")\nprint(Aev)\nprint(A1ev)\n#The answer may slightly vary due to rounding off values\n", "meta": {"hexsha": "91ec2c0dbdb58f5c6b40c6b6ac2094b62e88bfdc", "size": 369, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.6.2/Ex6.6_2.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.6.2/Ex6.6_2.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.6.2/Ex6.6_2.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 33.5454545455, "max_line_length": 80, "alphanum_fraction": 0.7154471545, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7464840909478684}} {"text": "#The naïve Bayes classifier is one of the simplest approaches to the \n#classification task that is still capable of providing reasonable accuracy\n\n#It is superior for certain specific application domains, with text classification \n#being the most prominent example. Its simplicity—conceptual, implementational, and \n#computational—makes it easy and inexpensive to try besides or before more \n#sophisticated classifiers.\n\n\nlibrary(dmr.stats)\nlibrary(dmr.util)\ndata(weather, package=\"dmr.data\")\ndata(weatherc, package=\"dmr.data\")\n\n\n## calculate the posterior probability given prior and inverse probabilities\nbayes.rule <- function(prior, inv)\n{\n prior*inv/sum(prior*inv)\n}\n\n# posterior probabilities\nbayes.rule(c(0.2, 0.3, 0.5), c(0.9, 0.9, 0.5))\n\n # let P(burglery)=0.001,\n # P(alarm|burglery)=0.95,\n # P(alarm|not burglery)=0.005\n # calculate P(burglery|alarm)\nbayes.rule(c(0.001, 0.999), c(0.95, 0.005))[1]\n", "meta": {"hexsha": "dd4b4ddbe7cccfa2da1a3124c6c3a7909a2ef696", "size": 914, "ext": "r", "lang": "R", "max_stars_repo_path": "books/Data_mining_explained_R/classification/naivebayes.r", "max_stars_repo_name": "gardner-dev/data_mining", "max_stars_repo_head_hexsha": "1b2224cbb424057cde0a7be204d51270e3cf203e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-16T03:57:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T03:57:13.000Z", "max_issues_repo_path": "books/Data_mining_explained_R/classification/naivebayes.r", "max_issues_repo_name": "gardner-dev/data_mining", "max_issues_repo_head_hexsha": "1b2224cbb424057cde0a7be204d51270e3cf203e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "books/Data_mining_explained_R/classification/naivebayes.r", "max_forks_repo_name": "gardner-dev/data_mining", "max_forks_repo_head_hexsha": "1b2224cbb424057cde0a7be204d51270e3cf203e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4666666667, "max_line_length": 84, "alphanum_fraction": 0.749452954, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7463209479630132}} {"text": "#!/usr/bin/env Rscript\n\n############################################################\n### Least squares estimation\n### y = beta0 + beta1*x --> Y = (1, X)beta\n### Y = XB ---> X 不一定可逆\n### t(X)Y = t(X)XB --> inverse(t(X)X)t(X)Y = B\n############################################################\n\nX = cbind(rep(1, 5), c(1.00, 2.00, 3.00, 4.00, 5.00))\nY = c(3.70, 4.20, 4.90, 5.70, 6.00)\n\nbeta.hat = solve(t(X) %*% X) %*% t(X) %*% Y\n", "meta": {"hexsha": "2a49143020d27b4dc961a7e384486dddc58ccb07", "size": 426, "ext": "r", "lang": "R", "max_stars_repo_path": "R/learn/AI/linear_mode.r", "max_stars_repo_name": "qrsforever/workspace", "max_stars_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-07T03:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-07T09:14:26.000Z", "max_issues_repo_path": "R/learn/AI/linear_mode.r", "max_issues_repo_name": "qrsforever/workspace", "max_issues_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/learn/AI/linear_mode.r", "max_forks_repo_name": "qrsforever/workspace", "max_forks_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4285714286, "max_line_length": 60, "alphanum_fraction": 0.3497652582, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140216112959, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7463063056246888}} {"text": "\n\n##' @title\n##' Cohen’s Kappa\n##'\n##' @description\n##'\n##' \\code{mtr_cohen_kappa} computes Kappa statistic which measures inter-rater\n##' agreement for categorical items.\n##'\n##' The form of Kappa statistic is: \\eqn{Kappa = (O - E) / (1 - E)} where O is\n##' the observed accuracy and E is the expected accuracy based on the marginal\n##' total of the confusion matrix. The statistic can take on values between -1\n##' and 1; a value of 0 means there is no agreement between the actual and the\n##' predicted, while a value of 1 indicates perfect concordance of the model\n##' prediction and the observed classes.\n##'\n##' @references\n##'\n##' \\itemize{\n##' \\item Max Kuhn and Kjell Johnson, Applied Predictive Modeling (New York: Springer-Verlag, 2013)\n##' \\item \\href{https://stats.stackexchange.com/questions/82162/cohens-kappa-in-plain-english}{\"Classification - Cohen’s Kappa in Plain English, Cross Validated\"}\n##' }\n##'\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @include helper-functions.r\n##' @export\n##' @examples\n##'\n##' act <- c(1, 0, 1, 0, 1)\n##' pred <- c(0.1, 0.9, 0.3, 0.5, 0.2)\n##' mtr_cohen_kappa(act, pred)\n##'\n##'\n##' set.seed(2093)\n##' pred <- runif(1000)\n##' act <- round(pred)\n##' pred[sample(1000, 300)] <- runif(300) # noises\n##' mtr_cohen_kappa(act, pred)\n##'\nmtr_cohen_kappa <- function(actual, predicted, cutoff = 0.5) {\n\n check_equal_length(actual, predicted)\n check_cutoff_range(cutoff)\n check_binary(actual)\n\n conf_mat <- mtr_confusion_matrix(actual, predicted, cutoff = cutoff)\n n <- sum(conf_mat)\n\n observed_accuracy <- mtr_accuracy(actual, predicted, cutoff = cutoff)\n\n expected_accuracy <- sum((rowSums(conf_mat) * colSums(conf_mat)) / n) / n\n\n kappa <- (observed_accuracy - expected_accuracy) / (1 - expected_accuracy)\n kappa\n}\n", "meta": {"hexsha": "4ffa9b79f5c7964b7d822e5cb02599726b763a08", "size": 1850, "ext": "r", "lang": "R", "max_stars_repo_path": "R/kappa.r", "max_stars_repo_name": "maiing/metrics", "max_stars_repo_head_hexsha": "ae4e4cbe5b025c53f2fbf552a46f335aa34f687f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/kappa.r", "max_issues_repo_name": "maiing/metrics", "max_issues_repo_head_hexsha": "ae4e4cbe5b025c53f2fbf552a46f335aa34f687f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/kappa.r", "max_forks_repo_name": "maiing/metrics", "max_forks_repo_head_hexsha": "ae4e4cbe5b025c53f2fbf552a46f335aa34f687f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8333333333, "max_line_length": 164, "alphanum_fraction": 0.6783783784, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7462806042383325}} {"text": "# ......................................................................................\n# ..................Exercise 1 - Brief introduction to R, Combinatorics.................\n# ......................................................................................\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# First we will go through some basics of R.\n# \n# Brief introduction to R ####\n# \n\n\n# simple arithmetic operations\n2+4\n5/2\n\n# BEWARE of brackets! Only round ones are used for counting!\n# Square and compound have a different role in R.!\n(((10+2)*(340-33))-2)/3\n\n# combination number, factorials\nchoose(10,2)\nfactorial(4)\n\n# data types ->numeric, character, logical,(complex)\n# the class function determines the type of the object\na=2+3\nclass(a)\n\nb=\"some text\"\nclass(b)\n\nc=(1>3)\nclass(c)\n\nd=3+1i\nclass(d)\n\n# * data structures in R ####\n# \n# - vector (column vector)\n# \n# - factor (special case of vector)\n# \n# - matrix (matrix with dimensions n x m)\n# \n# - data.frame (data frame with columns representing diferent types of informations and\n# rows representing single records)\n\n\n# vector definition\na = c(3,4,6,7)\na <- c(3,4,6,7)\na[2]\n\n# other options\nrep(1,4) # creates a vector with four ones\n\nseq(1,10,2) # sequence from 1 to 10 with step 2\n\n1:10 # sequence from 1 to 10 with step 1\n\nb=c(\"A\",\"B\",\"C\",\"D\")\nb\n\nclass(b)\n\n# redefining an object to another type - eg as.vector, as.matrix, as.factor,...\nb=as.factor(b)\nb\n\n# working with vectors - merging by columns/rows\ncbind(a,b)\n\nrbind(a,b)\n\nc(a,b)\n\n# matrix definition\nA=matrix(c(3,4,6,7,3,2),nrow=2,ncol=3)\nB=matrix(c(3,4,6,7,3,2),nrow=2,ncol=3,byrow=TRUE)\nC=matrix(c(3,4,6,7,3,2),nrow=3,ncol=2)\n\nB\n\nB[1,3]\n\nA[1,]\n\nA[,2:3]\n\n# diagonal matrix\ndiag(4)\n\ndiag(4,2)\n\n# matrix operations - pay attention to matrix multiplication -> %*%\nA+B\n\nA-B\n\nA*B\n\nA%*%C\n\n", "meta": {"hexsha": "23766977eccd02774dd76846f0588f80eb8436ed", "size": 2066, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 1/T1_Rintro.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise 1/T1_Rintro.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise 1/T1_Rintro.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 18.9541284404, "max_line_length": 88, "alphanum_fraction": 0.5726040658, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.746280603892482}} {"text": "# Calculate slope and aspect of a digital terrain model\n\nslope<-function(r, res=1){\n # returns a slope surface of elevation raster r of resolution res,\n # according to Burrough et McDonnell 2000, p. 191\n newr<-matrix(0, nrow=nrow(r), ncol=ncol(r))\n h<-nrow(r)\n w<-ncol(r)\n for(i in 2:(h-1)){\n for(j in 2:(w-1)){\n newr[i,j]<-sqrt( ((r[i+1,j]-r[i-1,j])/(2*res))^2 + ((r[i,j+1]-r[i,j-1])/(2*res))^2 )\n }\n }\n newr[1,]<-0; newr[h,]<-0; newr[,1]<-0; newr[,w]<-0; #adjust border\n return(newr)\n}\n\n\n# parameters\ninput_terrain <- 'c:/temp/terrain.txt'\n\n# read data\nm<-as.matrix(read.table(input_terrain))\n\n# calculate slope\ns<-slope(m)\n\n# plot results\nimage(m, main=\"elevation\")\nimage(s, main=\"slope\")\n", "meta": {"hexsha": "921079e8001bc67c3ffe7a02e35cad95473c6478", "size": 712, "ext": "r", "lang": "R", "max_stars_repo_path": "slope.r", "max_stars_repo_name": "filipkral/slopeaspect", "max_stars_repo_head_hexsha": "cc251751cdf81a9401299e7caca58e369337aa67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slope.r", "max_issues_repo_name": "filipkral/slopeaspect", "max_issues_repo_head_hexsha": "cc251751cdf81a9401299e7caca58e369337aa67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slope.r", "max_forks_repo_name": "filipkral/slopeaspect", "max_forks_repo_head_hexsha": "cc251751cdf81a9401299e7caca58e369337aa67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9677419355, "max_line_length": 90, "alphanum_fraction": 0.6151685393, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7461678948892426}} {"text": "## Strategy: For a bunch of Ns, compute the z_star by achieving desired alpha, then\n## compute what beta would be for that N using the acquired z_star. \n## Pick the smallest N at which beta crosses the desired value\n\n# Inputs:\n# The desired alpha for a two-tailed test\n# Returns: The z-critical value\nget_z_star = function(alpha) {\n return(-qnorm(alpha / 2))\n}\n\n# Inputs:\n# z-star: The z-critical value\n# s: The standard error of the metric at N=1\n# d_min: The practical significance level\n# N: The sample size of each group of the experiment\n# Returns: The beta value of the two-tailed test\nget_beta = function(z_star, s, d_min, N) {\n SE = s / sqrt(N)\n return(pnorm(z_star * SE, mean=d_min, sd=SE))\n}\n\n# Inputs:\n# s: The standard error of the metric with N=1 in each group\n# d_min: The practical significance level\n# Ns: The sample sizes to try\n# alpha: The desired alpha level of the test\n# beta: The desired beta level of the test\n# Returns: The smallest N out of the given Ns that will achieve the desired\n# beta. There should be at least N samples in each group of the experiment.\n# If none of the given Ns will work, returns -1. N is the number of\n# samples in each group.\n\nrequired_size = function(s, d_min, Ns=1:20000, alpha=0.05, beta=0.2) {\n for (N in Ns) {\n if (get_beta(get_z_star(alpha), s, d_min, N) <= beta) {\n return(N)\n }\n }\n \n return(-1)\n}\n\n# Example analytic usage\n# This is the example from Lesson 1, for which the online calculate gave 3,623\n# samples in each group\n\n# s is the pooled standard error for N=1 in each group,\n# which is sqrt(p*(1-p)*(1/1 + 1/1))\nrequired_size(s=sqrt(0.1*0.9*2), d_min=0.02)\n\n# Sizing: Example\n# Cookie-based diversion\n# Since the standard error is proportional to 1/sqrt(N), s, or\n# the standard error for N=1, is equal to the mesaured standard error with 5000\n# in each group times sqrt(5000)\nrequired_size(s=0.00515*sqrt(5000), d_min=0.02)\n# User-id-based diversion\nrequired_size(s=0.0119*sqrt(5000), d_min=0.02)\n\n# Sizing: Quiz\n# Original size\nrequired_size(s=0.0628*sqrt(1000), d_min=0.01, Ns=seq(10, 500000, 100))\n# Size with event-based diversion\nrequired_size(s=0.0209*sqrt(1000), d_min=0.01, Ns=seq(10, 500000, 100))\n# Size with event-based diversion and English-only traffic\nrequired_size(s=0.0188*sqrt(1000), d_min=0.015)\n# Size with cookie-based diversion, English-only traffic, and \n# click-through-probability instead of click-through-rate\nrequired_size(s=0.0445*sqrt(1000), d_min=0.015, Ns=seq(10, 500000, 100))", "meta": {"hexsha": "95359d44cd675cb2e6a1eae69249db257225f48c", "size": 2571, "ext": "r", "lang": "R", "max_stars_repo_path": "src/empirical-sizing.r", "max_stars_repo_name": "Alisaahy/ABTesting-Project", "max_stars_repo_head_hexsha": "8eebcd7dd18765a0487f0fd4b44dc057658223f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/empirical-sizing.r", "max_issues_repo_name": "Alisaahy/ABTesting-Project", "max_issues_repo_head_hexsha": "8eebcd7dd18765a0487f0fd4b44dc057658223f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/empirical-sizing.r", "max_forks_repo_name": "Alisaahy/ABTesting-Project", "max_forks_repo_head_hexsha": "8eebcd7dd18765a0487f0fd4b44dc057658223f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-26T02:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-26T02:58:34.000Z", "avg_line_length": 36.7285714286, "max_line_length": 84, "alphanum_fraction": 0.6993387787, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7461678831757141}} {"text": "###CHAPTER 5: BIAS VARIANCE TRADE-OFF \nN <- 500\nx <- seq(.09,.5,len=N)\nf <- 2*sin(1/x)\n\ny <- f + rnorm(N)\npostscript(\"Plots/plot-05-01.ps\")\nplot(x,y,main=\"True f(x)=5 sin(1/x) and observations\")\nlines(x,f,type=\"l\")\ndev.off() \n\nNN <- 5\n\npostscript(\"Plots/plot-05-02.ps\")\nresults <- sapply(1:NN,function(i){\n y <- f + rnorm(N)\n ksmooth(x,y,kernel=\"box\",bandwidth=.01)$y\n })\n\npar(mfrow=c(2,2),mai=c(0,0,0,0),oma=c(1,1,1,1))\nplot(x,f,type=\"l\",lwd=1.5,ylim=range(c(f,as.vector(results))))\nlines(x,results[,1],lty=4)\n\t\nplot(x,f,ylim=range(results),type=\"l\",lwd=1.5)\napply(results,2,function(aux) lines(x,aux,lty=4))\nresults <- sapply(1:NN,function(i){\n y <- f + rnorm(N)\n ksmooth(x,y,kernel=\"box\",bandwidth=.1)$y\n })\n\nplot(x,f,type=\"l\",lwd=1.5)\nlines(x,results[,1],lty=4)\n\t\nplot(x,f,type=\"l\",lwd=1.5)\napply(results,2,function(aux) lines(x,aux,lty=4))\ndev.off()\n\n\n", "meta": {"hexsha": "ebc3a2319da032c026dbbdc204e0c0c655a283af", "size": 889, "ext": "r", "lang": "R", "max_stars_repo_path": "pages/754/Old-gam-code/code-05.r", "max_stars_repo_name": "igrabski/rafalab.github.io", "max_stars_repo_head_hexsha": "2f27ea0d9e0b8a2342bb851ae7415ba3268fd00f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2016-08-17T23:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T19:21:02.000Z", "max_issues_repo_path": "pages/754/Old-gam-code/code-05.r", "max_issues_repo_name": "igrabski/rafalab.github.io", "max_issues_repo_head_hexsha": "2f27ea0d9e0b8a2342bb851ae7415ba3268fd00f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-08-18T00:41:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T22:35:40.000Z", "max_forks_repo_path": "pages/754/Old-gam-code/code-05.r", "max_forks_repo_name": "igrabski/rafalab.github.io", "max_forks_repo_head_hexsha": "2f27ea0d9e0b8a2342bb851ae7415ba3268fd00f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2016-08-17T22:17:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T12:17:08.000Z", "avg_line_length": 22.7948717949, "max_line_length": 62, "alphanum_fraction": 0.607424072, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7460266885476843}} {"text": "### CHALLENGER ###\n\n# Get the data\nlibrary(ggplot2)\nlibrary(GGally)\nlibrary(dplyr)\n\ndata_1 = read.delim('challenger_data.txt')\n\nggplot(data_1, aes(T, I)) + \n geom_point(color = 'dark blue', alpha = .2) + \n xlab('Temperature') +\n ylab('Damage') +\n ggtitle('Challenger - temperature vs damage')\n\n\n# Regression\nmodel_1 = lm(I ~ T, data)\n\nsummary(model_1)\n\n# Plot with reg line\nggplot(data_1, aes(T, I)) + \n geom_point(color = 'dark blue', alpha = .2) + \n xlab('Temperature') +\n ylab('Damage') +\n ggtitle('Challenger - temperature vs damage') +\n geom_line(aes(T, fitted(model_1)), color = 'red')\n\n# Predict for 31 degrees\npredict(model_1, data.frame(T = 31), interval = 'predict')\n\n# Posterior prediction interval (same as frequentist)\npred_1 = predict(model_1, data.frame(T = 31))\n \nk = length(model_1$coefficients) - 1 # Subtract one to ignore intercept\nSSE = sum(model_1$residuals**2)\nn = length(model_1$residuals)\n\nresid_std_error = sqrt(SSE / (n-(1+k))) # Residual Standard Error\n\n\npred_1 - resid_std_error * qt(.975, model_1$df.residual) * sqrt(1 + 1/23)\n# 10.82052 - 2.102*qt(.975,21)*sqrt(1+1/23+((31-mean(T))^2/22/var(T)))\n\n# posterior probability that damage index is greater than zero\n1-pt((0-10.82052)/(2.102*sqrt(1+1/23+((31-mean(T))^2/22/var(T)))),21)\n\n\n### HEIGHT ###\n\n# Get the data\ndata_2 = read.delim('http://www.randomservices.org/random/data/Galton.txt')\n\n# Plot\ndata_2 %>% select(-c('Family')) %>% ggpairs(., lower = list(continuous = wrap(\"smooth\", alpha = 0.3, size=0.1)))\n\n# Regress\nmodel_2 = lm(Height ~ Father + Mother + Gender, data_2)\n\nsummary(model_2)\n\n\n### GOLFERS ###\n\n# Get the data\ndata_3 = read.delim('http://www.stat.ufl.edu/~winner/data/pgalpga2008.dat', header = FALSE, sep = ' ')\ndata_3 = data_3[, c(4, 8, 15)]\n\ncolnames(data_3) <- c('dist', 'accuracy', 'gender') # 1 = F, 2 = M\n\nhead(data_3)\n\ndata_3 %>% filter(gender == 1) %>% ggplot(., aes(dist, accuracy)) + \n geom_point(alpha = .5) + geom_smooth(method = 'lm') +\n ggtitle('Mean distance vs accuracy - Females')\n\ndata_3 %>% filter(gender == 2) %>% ggplot(., aes(dist, accuracy)) + \n geom_point(alpha = .5) + geom_smooth(method = 'lm') +\n ggtitle('Mean distance vs accuracy - Males')\n\n\n# Fit a linear regression model to the female golfer data only with \n# drive distance as the explanatory variable x and accuracy as the response variable y. \n# Use the standard reference (non-informative) prior.\n\n# Recall that in a linear regression, we are modeling E(y) = b0 + b1x.\n\n# In this particular model, the intercept term is not interpretable, \n# as we would not expect to see a 0-yard drive (but it is still necessary). \n# Predictions should generally be made only within the range of the observed data.\n\n# Report the posterior mean estimate of the slope parameter b relating drive distance to accuracy. \n# Round your answer to two decimal places.\n\ndata_3_F = data_3 %>% filter(gender == 1)\n\nmodel_3 = lm(accuracy ~ dist, data_3_F)\n\nsummary(model_3)\n\n# Use the posterior mean estimates of the model coefficients to obtain a posterior predictive \n# mean estimate of driving accuracy for a new female golfer whose average driving distance \n# is x = 260 yards. Round your answer to one decimal place.\n\n\npredict(model_3, data.frame(dist = 260), interval = 'predict')\n\n\n\n", "meta": {"hexsha": "50a60fec15e443d3097097931a731b8b8746bcc8", "size": 3409, "ext": "r", "lang": "R", "max_stars_repo_path": "bayesian-notes-santa-cruz/ex_3.r", "max_stars_repo_name": "AlxndrMlk/bayesian-stuff", "max_stars_repo_head_hexsha": "86a45f4a2835d512093813faa27775c2dddc25e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bayesian-notes-santa-cruz/ex_3.r", "max_issues_repo_name": "AlxndrMlk/bayesian-stuff", "max_issues_repo_head_hexsha": "86a45f4a2835d512093813faa27775c2dddc25e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayesian-notes-santa-cruz/ex_3.r", "max_forks_repo_name": "AlxndrMlk/bayesian-stuff", "max_forks_repo_head_hexsha": "86a45f4a2835d512093813faa27775c2dddc25e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7117117117, "max_line_length": 112, "alphanum_fraction": 0.6611909651, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7458776786770324}} {"text": "# -----------------------\n# App Title: t-test\n# Author: Jimmy Wong\n# -----------------------\n\n#####################################################################################################################\n#####################################################################################################################\n## t-distribution shading area function\n#####################################################################################################################\n#####################################################################################################################\n\nt.dist.area = function(tstat,tail,df)\n{\n x = seq(-5,5,length.out=200)\n df = round(df, digits=3)\n \n if(tail==\"right\")\n {\n xmin=tstat\n xmax=5\n \n area = seq(xmin,xmax,length.out=200)\n dat = data.frame(x=area,ymin=0,ymax=dt(area,df=df))\n \n graph = ggplot() + geom_line(data.frame(x=x, y=dt(x,df=df)), mapping=aes(x=x, y=y)) + \n geom_ribbon(data=dat, mapping=aes(x=x, ymin=ymin, ymax=ymax), fill=\"navy\") + \n ggtitle(paste(\"t-distribution with\", df, \"degrees of freedom\")) +\n xlab(\"t-values\") + ylab(\"Relative frequency\") + theme_bw()\n } else if(tail==\"left\")\n {\n xmin=-5\n xmax=tstat\n \n area = seq(xmin,xmax,length.out=200)\n dat = data.frame(x=area,ymin=0,ymax=dt(area,df=df))\n \n graph = ggplot() + geom_line(data.frame(x=x, y=dt(x,df=df)), mapping=aes(x=x, y=y)) + \n geom_ribbon(data=dat, mapping=aes(x=x, ymin=ymin, ymax=ymax), fill=\"navy\") +\n ggtitle(paste(\"t-distribution with\", df, \"degrees of freedom\")) +\n xlab(\"t-values\") + ylab(\"Relative frequency\") + theme_bw()\n } else if(tail==\"both\")\n {\n xmin1=abs(tstat)\n xmax1=5\n area1 = seq(xmin1,xmax1,length.out=200)\n dat1 = data.frame(x=area1,ymin1=0,ymax1=dt(area1,df=df))\n \n xmin2=-5\n xmax2=-abs(tstat)\n area2 = seq(xmin2,xmax2,length.out=200)\n dat2 = data.frame(x=area2,ymin2=0,ymax2=dt(area2,df=df))\n \n graph = ggplot() + geom_line(data.frame(x=x, y=dt(x,df=df)), mapping=aes(x=x, y=y)) + \n geom_ribbon(data=dat1, mapping=aes(x=x, ymin=ymin1, ymax=ymax1),fill=\"navy\") +\n geom_ribbon(data=dat2, mapping=aes(x=x, ymin=ymin2, ymax=ymax2),fill=\"navy\") +\n ggtitle(paste(\"t-distribution with\", df, \"degrees of freedom\")) +\n xlab(\"t-values\") + ylab(\"Relative frequency\") + theme_bw()\n }\n return(graph)\n}\n\n#####################################################################################################################\n#####################################################################################################################\n## Library and data sets\n#####################################################################################################################\n#####################################################################################################################\n\noptions(shiny.maxRequestSize=30*1024^2)\nlibrary(ggplot2)\nlibrary(shinyBS)\ndata(faithful)\ndata(mtcars)\n\n#####################################################################################################################\n#####################################################################################################################\n## Shiny server\n#####################################################################################################################\n#####################################################################################################################\n\nshinyServer(function(input, output) {\n #####################################################################################################################\n #####################################################################################################################\n ## Data Exploration Panel\n #####################################################################################################################\n #####################################################################################################################\n \n data = reactive({\n if(is.null(input$file) & !input$usedata) \n {\n return(NULL)\n } else if(!is.null(input$file) & !input$usedata)\n {\n file = read.csv(input$file$datapath, header=input$header, sep=input$sep, quote=input$quote)\n return(file)\n } else if(input$sampdat==1 & input$usedata)\n {\n return(data.frame(eruptions=faithful$eruptions))\n } else if(input$sampdat==2 & input$usedata)\n {\n mtcars$amcoded = rep(NA,length(mtcars$hp))\n mtcars$amcoded[which(mtcars$am==0)] = \"automatic\"\n mtcars$amcoded[which(mtcars$am==1)] = \"manual\"\n return(data.frame(transmission=mtcars$amcoded, horsepower=mtcars$hp))\n }\n })\n \n output$data.tab = renderDataTable({\n if(!input$usedata) data()\n })\n \n output$data.tab1 = renderDataTable({\n if(input$usedata) data()\n })\n \n output$datagraph = renderPlot({\n if((input$datformat==1 & !input$usedata) | (input$sampdat!=2 & input$usedata)) \n {\n dat=unlist(data())\n dat1=data.frame(x=as.numeric(as.character(dat)))\n \n if(input$usedata)\n lab = \"Eruption times\"\n else\n lab = paste(names(data())[1])\n \n ggplot(data=dat1) + geom_histogram(aes(x=x), fill=\"navy\", alpha=.5) +\n xlab(lab) + ylab(\"Frequency\") +\n ggtitle(paste(\"Histogram of\",lab)) + theme_bw()\n } else if((input$datformat==2 & !input$usedata) | (input$sampdat!=1 & input$usedata))\n {\n dat=data()\n dat1=data.frame(x=dat[[1]],y=dat[[2]])\n if(length(unique(dat1$x))>length(unique(dat1$y)))\n {\n dat1$x = as.numeric(as.character(dat1$x))\n ggplot(data=dat1) + geom_boxplot(aes(x=factor(y),y=x,fill=factor(y)),alpha=.5) + \n xlab(paste(names(dat)[2])) + ylab(paste(names(dat)[1])) + theme_bw() +\n ggtitle(paste(\"Boxplots of\",paste(names(dat)[1]),\"by\",paste(names(dat)[2]))) +\n scale_fill_manual(name=paste(names(dat)[1]),values=c(\"seagreen2\",\"gold2\")) +\n theme(legend.position=\"bottom\")\n } else\n { \n dat1$y = as.numeric(as.character(dat1$y))\n ggplot(data=dat1) + geom_boxplot(aes(x=factor(x),y=y,fill=factor(x)),alpha=.5) +\n xlab(paste(names(dat)[1])) + ylab(paste(names(dat)[2])) + theme_bw() +\n ggtitle(paste(\"Boxplots of\",paste(names(dat)[2]),\"by\",paste(names(dat)[1]))) +\n scale_fill_manual(name=paste(names(dat)[2]),values=c(\"seagreen2\",\"gold2\")) +\n theme(legend.position=\"bottom\")\n }\n } else if((input$datformat==3 & !input$usedata) | (input$sampdat!=1 & input$usedata))\n {\n dat=data()\n dat1=data.frame(x=c(as.numeric(as.character(dat[[1]])),as.numeric(as.character(dat[[2]]))),\n y=c(rep(names(dat)[1],length(dat[[1]])),rep(names(dat)[2],length(dat[[2]]))))\n ggplot(data=dat1) + geom_boxplot(aes(x=factor(y),y=x,fill=factor(y)),alpha=.5) + \n xlab(\"Explanatory variable\") + ylab(\"Response variable\") +\n scale_fill_manual(name=\"\",values=c(\"seagreen2\",\"gold2\")) +\n ggtitle(\"Boxplots\") + theme_bw() + theme(legend.position=\"bottom\")\n }\n })\n \n output$summarystats = renderTable({\n if(input$displaystats & ((input$datformat==1 & !input$usedata) | (input$sampdat!=2 & input$usedata)))\n {\n vec = as.numeric(as.character(data()[[1]]))\n table = t(matrix(c((as.matrix(summary(vec)[1:6])),\n round(sd(vec,na.rm=TRUE)))))\n \n if(input$usedata)\n rownames(table) = \"Eruption times\"\n else\n rownames(table) = names(data())[[1]]\n \n colnames(table) = c(\"Min\",\"Q1\",\"Median\",\"Mean\",\"Q3\",\"Max\",\"SD\")\n return(table)\n } else if(input$displaystats & ((input$datformat==2 & !input$usedata) | (input$sampdat!=1 & input$usedata)))\n {\n dat=data()\n dat1=data.frame(x=dat[[1]],y=dat[[2]])\n if(length(unique(dat1$x)) > length(unique(dat1$y)))\n {\n dat1$y = factor(dat1$y)\n dat1$x = as.numeric(as.character(dat1$x))\n dat1 = dat1[which(complete.cases(dat1)),]\n sum = tapply(dat1$x,dat1$y,summary)\n table = data.frame(matrix(c(sum[[1]],sum[[2]]),nrow=2,ncol=6,byrow=TRUE))\n std = tapply(dat1$x,dat1$y,sd,na.rm=TRUE)\n table$sd[1] = round(std[1],digits=2)\n table$sd[2] = round(std[2],digits=2)\n table = as.matrix(table)\n colnames(table) = c(\"Min\",\"Q1\",\"Median\",\"Mean\",\"Q3\",\"Max\",\"SD\")\n rownames(table) = c(levels(dat1$y)[1],levels(dat1$y)[2])\n return(table) \n } else if(length(unique(dat1$x)) < length(unique(dat1$y)))\n {\n dat1$x = factor(dat1$x)\n dat1$y = as.numeric(as.character(dat1$y))\n dat1 = dat1[which(complete.cases(dat1)),]\n sum = tapply(dat1$y,dat1$x,summary)\n table = data.frame(matrix(c(sum[[1]],sum[[2]]),nrow=2,ncol=6,byrow=TRUE))\n std = tapply(dat1$y,dat1$x,sd)\n table$sd[1] = round(std[1],digits=2)\n table$sd[2] = round(std[2],digits=2)\n table = as.matrix(table)\n colnames(table) = c(\"Min\",\"Q1\",\"Median\",\"Mean\",\"Q3\",\"Max\",\"SD\")\n rownames(table) = c(levels(dat1$x)[1],levels(dat1$x)[2])\n return(table) \n }\n } else if(input$displaystats & ((input$datformat==3 & !input$usedata) | (input$sampdat!=1 & input$usedata)))\n {\n dat = data()\n dat[,1] = as.numeric(as.character(dat[,1]))\n dat[,2] = as.numeric(as.character(dat[,2]))\n table = data.frame(t(as.matrix(apply(dat,2,summary)[-7,])))\n table$sd[1] = round(sd(dat[,1],na.rm=TRUE),digits=2)\n table$sd[2] = round(sd(dat[,2],na.rm=TRUE),digits=2)\n table = as.matrix(table)\n colnames(table) = c(\"Min\",\"Q1\",\"Median\",\"Mean\",\"Q3\",\"Max\",\"SD\")\n return(table)\n }\n })\n \n #####################################################################################################################\n #####################################################################################################################\n ## T-test Panel\n #####################################################################################################################\n #####################################################################################################################\n \n output$info = renderUI({\n HTML(as.character(code(\"Click here for hypothesis test information.\")))\n })\n \n output$onesample = renderUI({\n HTML(as.character(code(\"Click here for one-sample t-test information.\")))\n })\n \n output$twosample = renderUI({\n HTML(as.character(code(\"Click here for two-sample t-test information.\")))\n })\n \n output$hypo1 = renderUI({\n if((input$datformat==1 & !input$usedata) | (input$sampdat!=2 & input$usedata))\n {\n if(input$alt1==\"less than\") \n HTML(\"Ho: μ =\", input$null1,\"

Ha: μ <\",input$null1)\n else if(input$alt1==\"greater than\")\n HTML(\"Ho: μ =\", input$null1,\"

Ha: μ >\",input$null1)\n else \n HTML(\"Ho: μ =\", input$null1,\"

Ha: μ ≠\",input$null1)\n } \n })\n \n output$hypo2 = renderUI({\n if((input$datformat!=1 & !input$usedata) | (input$sampdat!=1 & input$usedata))\n {\n if(input$alt2==\"less than\") \n HTML(\"Ho: μ12 =\",input$null2,\n \"

Ha: μ12 <\",input$null2)\n else if(input$alt2==\"greater than\")\n HTML(\"Ho: μ12 =\",input$null2,\n \"

Ha: μ12 >\",input$null2)\n else \n HTML(\"Ho: μ12 =\",input$null2,\n \"

Ha: μ12 ≠\",input$null2)\n } \n })\n \n mod = reactive({\n input$teststart\n isolate({\n if(input$teststart>0)\n {\n if((input$datformat==1 & !input$usedata) | (input$sampdat!=2 & input$usedata))\n {\n if(input$alt1==\"less than\") \n mod = t.test(x=as.numeric(as.character(unlist(data()))),alternative=\"less\",mu=input$null1,conf.level=1-input$alpha)\n else if(input$alt1==\"greater than\") \n mod = t.test(x=as.numeric(as.character(unlist(data()))),alternative=\"greater\",mu=input$null1,conf.level=1-input$alpha)\n else \n mod = t.test(x=as.numeric(as.character(unlist(data()))),alternative=\"two.sided\",mu=input$null1,conf.level=1-input$alpha)\n } else if((input$datformat==2 & !input$usedata) | (input$sampdat!=1 & input$usedata))\n {\n dat=data()\n if(length(unique(dat[[1]])) > length(unique(dat[[2]])))\n {\n if(input$alt2==\"less than\")\n mod = t.test(as.numeric(as.character(dat[[1]]))~dat[[2]],\n alternative=\"less\",mu=input$null2,conf.level=1-input$alpha)\n else if(input$alt2==\"greater than\")\n mod = t.test(as.numeric(as.character(dat[[1]]))~dat[[2]],\n alternative=\"greater\",mu=input$null2,conf.level=1-input$alpha)\n else \n mod = t.test(as.numeric(as.character(dat[[1]]))~dat[[2]],\n alternative=\"two.sided\",mu=input$null2,conf.level=1-input$alpha)\n } else\n {\n if(input$alt2==\"less than\")\n mod = t.test(as.numeric(as.character(dat[[2]]))~dat[[1]],\n alternative=\"less\",mu=input$null2,conf.level=1-input$alpha)\n else if(input$alt2==\"greater than\")\n mod = t.test(as.numeric(as.character(dat[[2]]))~dat[[1]], \n alternative=\"greater\",mu=input$null2,conf.level=1-input$alpha)\n else \n mod = t.test(as.numeric(as.character(dat[[2]]))~dat[[1]],\n alternative=\"two.sided\",mu=input$null2,conf.level=1-input$alpha)\n }\n } else if((input$datformat==3 & !input$usedata) | (input$sampdat!=1 & input$usedata))\n {\n dat=data()\n if(input$alt2==\"less than\")\n mod = t.test(x=as.numeric(as.character(dat[[1]])),y=as.numeric(as.character(dat[[2]])),\n alternative=\"less\",mu=input$null2,conf.level=1-input$alpha)\n else if(input$alt2==\"greater than\")\n mod = t.test(x=as.numeric(as.character(dat[[1]])),y=as.numeric(as.character(dat[[2]])),\n alternative=\"greater\",mu=input$null2,conf.level=1-input$alpha)\n else \n mod = t.test(x=as.numeric(as.character(dat[[1]])),y=as.numeric(as.character(dat[[2]])),\n alternative=\"two.sided\",mu=input$null2,conf.level=1-input$alpha)\n }\n }\n })\n })\n \n output$est=renderUI({\n if(input$teststart>0 & input$showpoint & ((input$datformat==1 & !input$usedata) | (input$sampdat!=2 & input$usedata)))\n {\n HTML(\"x̅ =\",round(mod()$estimate[1],2))\n } else if(input$teststart>0 & input$showpoint & ((input$datformat!=1 & !input$usedata) | (input$sampdat!=1 & input$usedata)))\n {\n HTML(\"x̅1 =\",round(mod()$estimate[1],2),\"

2 =\",round(mod()$estimate[2],2),\n \"

1 - x̅2 =\",round(mod()$estimate[1]-mod()$estimate[2],2))\n }\n })\n \n output$test = renderTable({\n input$teststart\n isolate({\n if(input$teststart>0)\n {\n tab = matrix(c(mod()$parameter,mod()$statistic,mod()$p.value),nrow=1)\n colnames(tab) = c(\"df\",\"t-statistic\",\"p-value\")\n rownames(tab) = \"Values\"\n tab\n } \n })\n })\n \n output$tdist = renderPlot({\n input$teststart\n isolate({\n if(input$alt1==\"less than\" | input$alt2==\"less than\")\n {\n tail=\"left\"\n } else if(input$alt1==\"greater than\" | input$alt2==\"greater than\")\n {\n tail=\"right\"\n } else if(input$alt1==\"two-sided\" | input$alt2==\"two-sided\")\n {\n tail=\"both\"\n } \n \n return(t.dist.area(mod()$statistic,tail=tail,mod()$parameter))\n })\n })\n\n output$citab = renderTable({\n if(input$ci & input$teststart>0)\n {\n tab = matrix(c(mod()$conf.int[1],mod()$conf.int[2]),nrow=1)\n colnames(tab) = c(\"Lower bound\",\"Upper bound\")\n rownames(tab) = paste(round(1-input$alpha, digits=3)*100,\"% CI\",sep=\"\")\n tab\n }\n })\n \n #####################################################################################################################\n #####################################################################################################################\n ## Diagnostics Panel\n #####################################################################################################################\n #####################################################################################################################\n \n output$qqplot = renderPlot({\n if((input$datformat==1 & !input$usedata) | (input$sampdat==1 & input$usedata))\n {\n dat=unlist(data())\n dat1=data.frame(x=as.numeric(as.character(dat)))\n ggplot(data=dat1, aes(sample=x)) + stat_qq(geom=\"point\",color=\"navy\",shape=1) +\n theme_bw() + theme(text=element_text(size=15)) + ggtitle(\"Q-Q Plot\")\n } else if((input$datformat==2 & !input$usedata) | (input$sampdat!=1 & input$usedata))\n {\n dat=data()\n dat1=data.frame(x=dat[[1]],y=dat[[2]])\n if(length(unique(dat[[1]])) > length(unique(dat[[2]])))\n {\n dat1$x=as.numeric(as.character(dat1$x))\n ggplot(data=dat1, aes(sample=x)) + stat_qq(aes(color=factor(y)),geom=\"point\",shape=1) + theme_bw() +\n theme(text=element_text(size=15)) + ggtitle(\"Q-Q Plot\") + facet_wrap(~y) +\n scale_color_manual(name=\"\", values=c(\"navy\",\"gold2\")) + guides(color=FALSE)\n } else\n {\n dat1$y=as.numeric(as.character(dat1$y))\n ggplot(data=dat1, aes(sample=y)) + stat_qq(aes(color=factor(x)),geom=\"point\",shape=1) + theme_bw() +\n theme(text=element_text(size=15)) + ggtitle(\"Q-Q Plot\") + facet_wrap(~x) +\n scale_color_manual(name=\"\", values=c(\"navy\",\"gold2\")) + guides(color=FALSE) \n }\n } else if((input$datformat==3 & !input$usedata) | (input$sampdat!=1 & input$usedata))\n {\n dat=data()\n dat1=data.frame(x=c(as.numeric(as.character(dat[[1]])),as.numeric(as.character(dat[[2]]))),\n y=c(rep(names(dat)[1],length(dat[[1]])),rep(names(dat)[2],length(dat[[2]]))))\n ggplot(data=dat1, aes(sample=x)) + stat_qq(aes(color=factor(y)),geom=\"point\",shape=1) + theme_bw() +\n theme(text=element_text(size=15)) + ggtitle(\"Q-Q plot\") + facet_wrap(~y) +\n scale_color_manual(name=\"\", values=c(\"navy\",\"gold2\")) + guides(color=FALSE) \n }\n })\n \n output$sw = renderTable({\n if((input$datformat==1 & !input$usedata) | (input$sampdat!=2 & input$usedata))\n {\n dat=unlist(data())\n dat1=data.frame(x=as.numeric(as.character(dat)))\n \n validate(\n need(try(shapiro.test(dat1$x)), \"Do not need to conduct normality test\")\n )\n \n norm = shapiro.test(dat1$x)\n \n tab = matrix(c(norm$statistic,norm$p.value),nrow=1)\n colnames(tab) = c(\"W statistic\",\"p-value\")\n rownames(tab) = \"Data\"\n tab\n } else if((input$datformat==2 & !input$usedata) | (input$sampdat!=1 & input$usedata))\n {\n dat=data()\n dat1=data.frame(x=dat[[1]],y=dat[[2]])\n if(length(unique(dat[[1]])) > length(unique(dat[[2]])))\n {\n dat1$x=as.numeric(as.character(dat1$x))\n \n norm1 = shapiro.test(dat1$x[which(dat1$y==unique(dat1$y)[1])])\n norm2 = shapiro.test(dat1$x[which(dat1$y==unique(dat1$y)[2])])\n \n tab = matrix(c(norm1$statistic,norm2$statistic,norm1$p.value,norm2$p.value),ncol=2)\n colnames(tab) = c(\"W statistic\",\"p-value\")\n rownames(tab) = c(\"Data 1\",\"Data 2\")\n tab\n } else\n {\n dat1$y=as.numeric(as.character(dat1$y))\n \n norm1 = shapiro.test(dat1$y[which(dat1$x==unique(dat1$x)[1])])\n norm2 = shapiro.test(dat1$y[which(dat1$x==unique(dat1$x)[2])])\n \n tab = matrix(c(norm1$statistic,norm2$statistic,norm1$p.value,norm2$p.value),ncol=2)\n colnames(tab) = c(\"W statistic\",\"p-value\")\n rownames(tab) = c(\"Data 1\",\"Data 2\")\n tab \n }\n } else if((input$datformat==3 & !input$usedata) | (input$sampdat!=1 & input$usedata))\n {\n dat=data()\n \n norm1 = shapiro.test(as.numeric(as.character(dat[[1]])))\n norm2 = shapiro.test(as.numeric(as.character(dat[[2]])))\n \n tab = matrix(c(norm1$statistic,norm2$statistic,norm1$p.value,norm2$p.value),ncol=2)\n colnames(tab) = c(\"W statistic\",\"p-value\")\n rownames(tab) = c(\"Data 1\",\"Data 2\")\n tab \n }\n })\n \n})", "meta": {"hexsha": "9bf46e31fb9d853388200d5762f01dbb1d8a791c", "size": 20669, "ext": "r", "lang": "R", "max_stars_repo_path": "t_Test/server.r", "max_stars_repo_name": "townsenddw/shiny1", "max_stars_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "t_Test/server.r", "max_issues_repo_name": "townsenddw/shiny1", "max_issues_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "t_Test/server.r", "max_forks_repo_name": "townsenddw/shiny1", "max_forks_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-21T12:48:05.000Z", "avg_line_length": 43.6054852321, "max_line_length": 130, "alphanum_fraction": 0.4874933475, "num_tokens": 5539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7458499267687464}} {"text": "# matrice\n\nelementi <- c(2,4,3,1,5,7)\nprva <- matrix( elementi,\n nrow = 2,\n ncol =3,\n byrow = TRUE)\nprva\n\ndruga <- matrix( elementi,\n nrow = 2,\n ncol =3,\n byrow = FALSE)\ndruga\n\ntreca <- matrix( elementi,\n nrow = 2,\n ncol =3)\ntreca\n\n \n# indeksiranje\nna.poziciji.2.2 <- druga[2,2]\nna.poziciji.2.2\n\nprva\nprva.vrsta.od.prva <- prva[1,]\nprva.vrsta.od.prva\ndruga.kolona.od.prva <- prva[,2]\ndruga.kolona.od.prva\n\nmatrica.A <- matrix(\n c(1,2,3,4,5),\n nrow = 4,\n ncol = 3)\nmatrica.A\n\npodmatrica.A <- matrica.A[c(2,4), c(1,3)]\npodmatrica.A\n\nzamenili.prvu.i.trecu.kolonu <- matrica.A[,c(3,2,1)]\nzamenili.prvu.i.trecu.kolonu\n\nmatrica.A[2,2] <- 22\nmatrica.A\n\nmatrica.A[2,] <- c(7,8,9)\nmatrica.A\n\nmatrica.A[,2] <- c(0.5,1.5)\nmatrica.A\n\nmatrica.A <- matrix(\n c(1,2,3,4,5,6),\n nrow = 4,\n ncol = 3)\nmatrica.A\ndimnames(matrica.A) <- list(\n c(\"najvisa\",\"skoro najvisa\", \"skoro najniza\", \"najniza\"),\n c(\"prva\", \"druga\", \"treca\")\n )\nmatrica.A\n\ntreca.vrsta.matrice.A <- matrica.A[\"skoro najniza\",]\ntreca.vrsta.matrice.A\n\n# operacije nad matricama\nelementi <- c(2,4,3,1,5,7)\nprva <- matrix( elementi,\n nrow = 2,\n ncol =3,\n byrow = TRUE)\nprva\ndruga <- matrix( elementi,\n nrow = 2,\n ncol =3,\n byrow = FALSE)\ndruga\nzbir <- prva + druga\n\nprva\ntransponovana.prva <- t(prva)\ntransponovana.prva\n\nprva\ndruga\nspojene.po.koloni <- cbind (prva, druga)\nspojene.po.koloni\n\nprva\ndruga\nspojene.po.vrsti <- rbind (prva, druga)\nspojene.po.vrsti\n\n\n", "meta": {"hexsha": "93be4dfb3d77da3c55c1f04a37ad0908f6e40c24", "size": 1641, "ext": "r", "lang": "R", "max_stars_repo_path": "predavanja/primeri-r/004-matrice.r", "max_stars_repo_name": "PmfBlPRB/PRB", "max_stars_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "predavanja/primeri-r/004-matrice.r", "max_issues_repo_name": "PmfBlPRB/PRB", "max_issues_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-05T11:49:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-19T07:53:58.000Z", "max_forks_repo_path": "predavanja/primeri-r/004-matrice.r", "max_forks_repo_name": "PmfBlPRB/PRB", "max_forks_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.09375, "max_line_length": 59, "alphanum_fraction": 0.5588056063, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7456500781092393}} {"text": "#' Scaling data\n#'\n#' @description Rescale data\n#'\n#' @param x numeric vector\n#' @param lim_inf numeric value of the inferior limit (0 by default)\n#' @param lim_sup numeric value of the superior limit (1 by default)\n#'\n#' @return numeric vector\n#'\n#' @export\n#'\n#' @examples\n#'\n#' x <- seq(-3,3,l = 100)\n#'\n#' range(x)\n#'\n#' y <- scale01(x)\n#'\n#' range(y)\n#'\n#' plot(x,y)\n#'\n\nscale01 <- function(x, lim_inf = 0, lim_sup = 1){\n\n if(is.numeric(x) == F){\n stop(\"x must be numeric\")\n }\n\n if(length(x) == 1){\n stop(\"length of x must be > 1\")\n }\n\n if(is.numeric(lim_sup) == F){\n stop(\"lim_sup must be numeric\")\n }\n\n if(is.numeric(lim_inf) == F){\n stop(\"lim_inf must be numeric\")\n }\n\n if(length(lim_sup) != 1){\n stop(\"lim_sup must be just one numeric value\")\n }\n\n if(length(lim_inf) != 1){\n stop(\"lim_inf must be just one numeric value\")\n }\n\n if(lim_sup <= lim_inf){\n stop(\"lim_sup must be > lim_inf\")\n }\n\n max_x <- max(x, na.rm = T)\n\n min_x <- min(x, na.rm = T)\n\n out <- (lim_sup-lim_inf) * ((x - min_x)/(max_x - min_x)) + lim_inf\n\n return(out)\n}\n\n\n", "meta": {"hexsha": "33f6d24a418e5b5c8cea951f5cd8131d21d28ee3", "size": 1082, "ext": "r", "lang": "R", "max_stars_repo_path": "R/scale01.r", "max_stars_repo_name": "larissabf/relper", "max_stars_repo_head_hexsha": "fc6ed8006190fdb829ebbf8b2f24b3c8ef39c3a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/scale01.r", "max_issues_repo_name": "larissabf/relper", "max_issues_repo_head_hexsha": "fc6ed8006190fdb829ebbf8b2f24b3c8ef39c3a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/scale01.r", "max_forks_repo_name": "larissabf/relper", "max_forks_repo_head_hexsha": "fc6ed8006190fdb829ebbf8b2f24b3c8ef39c3a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3939393939, "max_line_length": 68, "alphanum_fraction": 0.5785582255, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7455472921878384}} {"text": "# the rank sum test \r\nMethodist=c(62,60,60,25,24,23,20,13,12,6)\r\nCatholic=c( 62,62,24,24,22,20,19,10,8,8)\r\nPentecostal=c(37,31,15,15,14,14,14,5,3,2 )\r\nn=30\r\ndata.value <- c( Methodist,Catholic,Pentecostal)\r\n \r\ndata.rank <- rank(data.value)\r\ndata <- data.frame(data.value, data.rank)\r\nprint(data)\r\n Sumofranks=c(182.5,167.5,115)\r\n #test statistic\r\n H=(12/(n*(n+1)))*((Sumofranks[1]^2+Sumofranks[2]^2+Sumofranks[3]^2)/10)-3*(n+1)\r\n print(H)\r\n \r\n", "meta": {"hexsha": "7112e9f966531dbf5268c8dc41567a0a794bb33e", "size": 444, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH8/EX8.7/Ex8_7.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH8/EX8.7/Ex8_7.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH8/EX8.7/Ex8_7.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 27.75, "max_line_length": 81, "alphanum_fraction": 0.6486486486, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876286, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7452263304658868}} {"text": "# P-valueBasics.r\n#\n# Using R to create a null distribution for a fair coin\n# and calculate a p value for an event\n#\n\n# Use a function to generate the coin flips\n\n# 0 = Tails and 1 = Heads\n\nFlipCoin <- function(n) sample(0:1,n,rep=T)\n\nheads <- FlipCoin(20) # to start calculation\n\n# Flip the 20 coins 10000 times\n\nfor(i in 1:10000) heads[i] <- sum(FlipCoin(20)==1)\n\nhist(heads, main=\"Number of heads out of 20 tosses\")\n\nhistinfo <- hist(heads)\n\nprint(histinfo)\n\n# Use the Binomial Distribution to work out the probability of\n# getting 16 heads out of 20 flips of a fair coin\n\nbinomial <- dbinom(16, size=20, prob=0.5) + dbinom(17, size=20, prob=0.5) + dbinom(18, size=20, prob=0.5) + dbinom(19, size=20, prob=0.5) + dbinom(20, size=20, prob=0.5)\n\nprint(binomial)\n", "meta": {"hexsha": "6a316f15ba5f376c58d8ae42aa44ef25cf415157", "size": 763, "ext": "r", "lang": "R", "max_stars_repo_path": "P-Value/P-valueBasics.r", "max_stars_repo_name": "dtinblack/R-Notes", "max_stars_repo_head_hexsha": "8017f7708d347669139a337ab0f78eebdc38c098", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P-Value/P-valueBasics.r", "max_issues_repo_name": "dtinblack/R-Notes", "max_issues_repo_head_hexsha": "8017f7708d347669139a337ab0f78eebdc38c098", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P-Value/P-valueBasics.r", "max_forks_repo_name": "dtinblack/R-Notes", "max_forks_repo_head_hexsha": "8017f7708d347669139a337ab0f78eebdc38c098", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6129032258, "max_line_length": 169, "alphanum_fraction": 0.6959370904, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659996, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.745226325546021}} {"text": "## 1. Condition vs Intersection ##\n\np_m <- 515/2000\np_m_given_l <- 32/90\np_m_and_l <- 32/2000\n\np_l <- 90/2000\np_m_or_l <- p_m + p_l - p_m_and_l\n\n## 2. Conditional Probability & Complements ##\n\np_b_given_m <- 0.1486\np_c_given_l <- 0.0928\np_non_b_given_c <- 0.7622\np_non_b_given_m <- 1 - p_b_given_m\np_non_c_given_l <- 1 - p_c_given_l\np_b_given_c <- 1 - p_non_b_given_c\n\n## 3. Distinguishing Between Event and Condition ##\n\np_m_given_non_l <- 483/1910\np_non_l_given_m <- 483/515\np_m_and_non_l <- 483/2000\np_non_l_and_m <- 483/2000\n\n## 4. More On Intersection Probabilities ##\n\np_ram <- 0.0822\np_gl <- 0.0184\np_ram_given_gl <- 0.0022\np_gl_and_ram <- p_gl * p_ram_given_gl\np_non_ram_given_gl <- 1 - p_ram_given_gl\np_gl_and_non_ram <- p_gl * p_non_ram_given_gl\np_gl_or_ram <- p_gl + p_ram - p_gl_and_ram\n\n## 5. Conditional Probability and Independence ##\n\nk_and_l <- 'independent'\nl_and_m <- 'independent'\nk_and_m <- 'dependent'\n\n## 6. Dependent Events ##\n\n# Exercise 1 & 2\nl_and_m <- 'dependent'\nl_and_non_m <- 'dependent'\n\n# Exercise 3\np_l <- 90/2000\np_m_given_l <- 32/90\np_l_and_m <- p_l * p_m_given_l\n\n# Exercise 4\np_not_m_given_l <- 58/90\np_l_and_non_m <- p_l * p_not_m_given_l\n\n## 7. Independence for Three Events ##\n\np_et <- 0.0432\np_ac <- 0.0172\np_ps <- 0.0236\np_et_and_ps <- p_et * p_ps\np_et_and_ac <- p_et * p_ac\np_ac_and_ps <- p_ac * p_ps\np_et_and_ac_and_ps <- p_et * p_ac * p_ps", "meta": {"hexsha": "3cad7d9ff21ca926a8ca156336d420af7a2c24cb", "size": 1385, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/4. Conditional Probability in R/2. Conditional Probability Intermediate.r", "max_stars_repo_name": "MyArist/Dataquest", "max_stars_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-27T12:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T04:39:33.000Z", "max_issues_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/4. Conditional Probability in R/2. Conditional Probability Intermediate.r", "max_issues_repo_name": "myarist/Dataquest", "max_issues_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/4. Conditional Probability in R/2. Conditional Probability Intermediate.r", "max_forks_repo_name": "myarist/Dataquest", "max_forks_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-03-30T06:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T03:55:02.000Z", "avg_line_length": 21.3076923077, "max_line_length": 51, "alphanum_fraction": 0.719133574, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831558, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7451421464511919}} {"text": "ex1 = function(a, b)\n{\n\tplot(log2, a, b, col=\"red\", lwd=2, main = \"f(x)= log2 x, x in [a,b]\")\n}\n\nex2 = function()\n{\n\tfor(pr in c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9))\n\t{\n\t\tpdf(file=\n\t\t\tpaste(\"D:\\\\Facultate\\\\Capitole Speciale de Inteligenta Artificiala\\\\homework2\\\\plots\\\\binom_\", pr, \".pdf\", sep=\"\"),\n\t\t\twidth=4, height=4\n\t\t )\n\t\t\n\t\tx = 0:20\n\t\tplot(x, dbinom(x, size=20, prob=pr),\n \t\t \ttype=\"h\",\n \t\t\tmain=paste(\"Binomial Distribution (n=20, p=\", pr, \")\", sep=\"\"),\n \t\t\tylab=\"Probability\",\n \t\t\txlab =\"# Successes\",\n \t\t\tlwd=3)\n\t\tdev.off()\n\t}\n}\n\nex3 = function()\n{\n\tx = seq(-7, 7, .1)\n\ty = dnorm(x, mean=0, sd=.5)\n\tplot(x, y, type=\"l\", col=\"red\", lwd=2)\n\tpar(new=T)\n\ty = dnorm(x, mean=0, sd=1)\n\tplot(x, y, type=\"l\", col=\"green\", lwd=2, yaxt='n', xaxt='n')\n\tpar(new=T)\n\ty = dnorm(x, mean=0, sd=2)\n\tplot(x, y, type=\"l\", col=\"blue\", lwd=2, yaxt='n', xaxt='n')\n}\n\nCLT = function(n)\n{\n\tvret = vector(\"double\", 1000)\n\tfor(i in 1:1000)\n\t{\n\t\tv = runif(n, 0, 20)\n\t\tvret[i] = mean(v)\n\t}\n\tvret\n}\n\nex3b = function()\n{\n\tpar(mfrow=c(2,2))\n\n\tfor(n in c(1, 5, 10, 100))\n\t{\n\t\ty = CLT(n)\n\t\thist(y, nclass=50, col=\"red\", main=paste(\"Histogram uniform of\", n))\n\t}\n\n}\n\nCLT2 = function(n)\n{\n\tvret = vector(\"double\", 1000)\n\tfor(i in 1:1000)\n\t{\n\t\tv = rbinom(n, 20, 0.1)\n\t\tvret[i] = mean(v)\n\t}\n\tvret\n}\n\nex3c = function()\n{\n\tpar(mfrow=c(2,2))\n\n\tfor(n in c(1, 5, 10, 100))\n\t{\n\t\ty = CLT2(n)\n\t\thist(y, nclass=50, col=\"blue\", main=paste(\"Histogram binomial of\", n))\n\t}\n}", "meta": {"hexsha": "02938f8f75e4faebe27ee53363198a6e74cf7a1d", "size": 1469, "ext": "r", "lang": "R", "max_stars_repo_path": "homework2/hw2.r", "max_stars_repo_name": "Amihaeseisergiu/Special-Chapters-Of-Artificial-Intelligence", "max_stars_repo_head_hexsha": "508de2e5277632d59f3330c9269357fdaf1fb5cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework2/hw2.r", "max_issues_repo_name": "Amihaeseisergiu/Special-Chapters-Of-Artificial-Intelligence", "max_issues_repo_head_hexsha": "508de2e5277632d59f3330c9269357fdaf1fb5cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework2/hw2.r", "max_forks_repo_name": "Amihaeseisergiu/Special-Chapters-Of-Artificial-Intelligence", "max_forks_repo_head_hexsha": "508de2e5277632d59f3330c9269357fdaf1fb5cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9146341463, "max_line_length": 118, "alphanum_fraction": 0.5302927161, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7451036172673449}} {"text": "\n# -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# Compuationally verifying that the t distribution with n df is generated from\n# the sampling distribution of the mean of (n+1) samples from a normal distribution.\n# (specifically, it is the distribution of sqrt(n+1)*(xbar - mu)/S)\n# -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n# To derive the t distribution from here, we need to multiply numerator and denominator\n# by sigma and rearrange to get ((xbar - mu)/((sigma^2)/sqrt(n))) / sqrt((S^2)/(sigma^2))\n# Then for this fraction, the top is ~ Z, the bottom is ~ sqrt(chisq(n-1)/n-1).\n\n# Please be aware that due to some quirk in the calculation of the kernel density, one finds\n# that the area under the curve can increase as the number of points -> Inf. Clearly this\n# contravenes the laws of probability. It can be largely rectified by specifying the number of\n# points to estimate at (argument n). HOWEVER, I'm finding an intermittent bug whereby the\n# density function is still plotting too large an area under the curve / not accepting the\n# n argument. The code is as-is, and if it happens, I suggest simply re-plotting.\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Function definitions\n\n# Function to plot the theoretical distribution - to compare against\nplot.analytic <- function(pdf, xlim = c(-3,3), ylim = c(0,0.5), res = 100, line.only = F, ...) {\n if(!is.vector(xlim) | !is.numeric(xlim) | !(length(xlim)==2)) stop(\"xlim must be limits of x axis\")\n if(!is.vector(ylim) | !is.numeric(ylim) | !(length(ylim)==2)) stop(\"ylim must be limits of y axis\")\n if(!is.function(pdf)) stop(\"pdf must be given as the density function of the distribution\")\n sx <- seq(xlim[1], xlim[2], length.out = res)\n px <- pdf(sx, ...)\n if(!line.only) plot(sx, px, type=\"l\", ylim=ylim, xlab = \"X\", ylab = \"Density\") else {\n lines(sx, px)\n }\n}\n\n# Function that simulates the sampling distribution for x_bar.\nxbar_smp <- function(rng=rnorm, n = 1000, size = 10, xlim = NULL, ylim = c(0,0.5), line.only = T, ...) {\n \n #Generate n samples of size 'size' (rng = random number generator specified)\n smp <- matrix(rng(n*size, ...), n, size)\n #Sample mean\n xbar <- rowSums(smp)/size\n #Sample sd (avoiding apply for efficiency reasons)\n S <- sqrt(rowSums(smp^2)/(size-1) - (xbar^2)*(size/(size-1)))\n \n #Standardise\n xbar <- (xbar - mean(xbar))/(S/sqrt(size))\n \n #Plot\n if(!line.only & is.null(xlim)) {\n plot(density(xbar, n=n), ylim=ylim, col = 2, xlab = \"X\", ylab = \"Density\") \n } else if(!line.only & !is.null(xlim)) {\n plot(density(xbar, n=n), xlim = xlim, ylim=ylim, col = 2, xlab = \"X\", ylab = \"Density\")\n } else {\n lines(density(xbar, n=n), col = 2)\n }\n invisible(xbar)\n}\n\n# Function that simulates the distribution of (S2.x/var.x)/(S2.y/var.y)\n# Note that (n-1)S2x/varx ~ Chisq(n-1), so the above is the ratio of two\n# Chisq distributions with (possibly) different dfs.\n\nS2_ratio_smp <- function(n = 1000, size = 10, var.x = 1, var.y = 1, mean.x = 0, mean.y = 0,\n rng=rnorm, xlim = NULL, ylim = c(0,0.8), line.only = T) {\n \n #Generate n samples of size 'size' (rng = random number generator specified)\n smp.x <- matrix(rng(n*size, mean.x, sqrt(var.x)), n, size)\n smp.y <- matrix(rng(n*size, mean.y, sqrt(var.y)), n, size)\n \n #Sample mean\n x.bar <- rowSums(smp.x)/size\n y.bar <- rowSums(smp.y)/size\n #Sample sd (avoiding apply for efficiency reasons)\n S2.x <- rowSums(smp.x^2)/(size-1) - (x.bar^2)*(size/(size-1))\n S2.y <- rowSums(smp.y^2)/(size-1) - (y.bar^2)*(size/(size-1))\n \n #Test statistic\n results <- (S2.x/S2.y)/(var.x/var.y)\n \n #Plot\n if(!line.only & is.null(xlim)) {\n plot(density(results, n=n), ylim=ylim, col = 3, xlab = \"X\", ylab = \"Density\") \n } else if(!line.only & !is.null(xlim)) {\n plot(density(results, n=n), xlim = xlim, ylim=ylim, col = 3, xlab = \"X\", ylab = \"Density\")\n } else {\n lines(density(results, n=n), col = 3)\n }\n invisible(results)\n}\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n# t - distribution:\n# ----------------- \n# Plot theoretical cauchy distribution / t distribution with 1 df.\n# It is immediate from the definition that the two distributions are the same.\nplot.analytic(dt, df = 1, xlim = c(-10,10))\n\n\n# Plot density generated from 5,000 samples of size 2 from a standard normal dist.\n# Should be distributed close to the theoretical distn plotted in black\nxbar_smp(size = 2, n = 10000)\n# Increase sample sizes (df) for the sampling distn of xbar\nxbar_smp(size = 10, n = 10000)\nxbar_smp(size = 20, n = 10000)\n\n# Plot theoretical standard normal distribution\nplot.analytic(dnorm, line.only = T)\n\n\n\n# F - distribution:\n# ----------------- \n\n# Simulate F distribution with sample size of 10\nsmp_size <- 10\nS2_ratio_smp(n = 100000, size = smp_size, xlim = c(0,10), line.only = F)\n# Verifying that changing the mean/variance makes 0 difference\nS2_ratio_smp(n = 100000, size = smp_size, mean.x = 1000, xlim = c(0,10), line.only = F)\nS2_ratio_smp(n = 100000, size = smp_size, mean.x = 1000, var.x = 10, xlim = c(0,10), line.only = F)\n\n# Compare to theoretical (black line)\nplot.analytic(df, df1 = smp_size-1, df2 = smp_size-1, line.only = T)\n\n# Compare distribution of different sample sizes\nS2_ratio_smp(n = 100000, size = 4, xlim = c(0,10), ylim = c(0,1), line.only = F)\nS2_ratio_smp(n = 100000, size = 7, xlim = c(0,10), line.only = T)\nS2_ratio_smp(n = 100000, size = 10, xlim = c(0,10), line.only = T)\nS2_ratio_smp(n = 100000, size = 20, xlim = c(0,10), line.only = T)\nS2_ratio_smp(n = 100000, size = 40, xlim = c(0,10), line.only = T)\nplot.analytic(df, df1 = 39, df2 = 39, line.only = T)\n\n# Compare summary of different distributions\nsmp_size <- c(4,7,10,20,40)\nresults <- sapply(1:length(smp_size), function(x) S2_ratio_smp(n = 100000, size = smp_size[x], line.only = T))\nresults <- noquote(format(apply(results, 2, function(x) {op <- c(mean(x), var(x))\n names(op) = c(\"Mean\",\"Var\"); op}), digits = 2))\ncolnames(results) <- paste(\"|smp|\", smp_size, sep = \" = \")\nprint(results)\n\n# As expected, mean -> 1. Variance of distribution looks to be -> 0 as n -> +Inf\n\nS2_ratio_smp(n = 100000, size = smp_size, var.x = 10, xlim = c(0,10), line.only = F)\ndebugonce(S2_ratio_smp)\nS2_ratio_smp(n = 100000, size = smp_size, var.x = 10, xlim = c(0,10), line.only = F)", "meta": {"hexsha": "75f5b2f6df7ea01f4616a4a375be168472af6665", "size": 6491, "ext": "r", "lang": "R", "max_stars_repo_path": "STATG000 - t-distn & F-distn.r", "max_stars_repo_name": "spoonbill/Miscellaneous", "max_stars_repo_head_hexsha": "77216f4f966b8ca3d02a140ff2f0ab4a7db0d873", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "STATG000 - t-distn & F-distn.r", "max_issues_repo_name": "spoonbill/Miscellaneous", "max_issues_repo_head_hexsha": "77216f4f966b8ca3d02a140ff2f0ab4a7db0d873", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "STATG000 - t-distn & F-distn.r", "max_forks_repo_name": "spoonbill/Miscellaneous", "max_forks_repo_head_hexsha": "77216f4f966b8ca3d02a140ff2f0ab4a7db0d873", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7655172414, "max_line_length": 110, "alphanum_fraction": 0.6159297489, "num_tokens": 2014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7451016771157283}} {"text": "#Series temporais e analises preditivas - Fernando Amaral\r\nlibrary(forecast)\r\nlibrary(ggplot2)\r\n\r\n#gerando serie random walk\r\n#tornar reprodutivel\r\nset.seed(4312)\r\nx = cumsum(sample(c(-1,1),100,T))\r\nprint(x)\r\nserie = ts(x,start = c(1900),end = c(2000), frequency = 1)\r\nprint(serie)\r\nautoplot(serie)\r\n\r\n#faz a previsao\r\nprev = naive(serie, h=5)\r\nclass(prev)\r\nprint(prev)\r\nprint(prev$fitted)\r\nprint(prev$residuals)\r\nautoplot(prev)\r\nprint(prev)\r\n\r\nprev2 = naive(serie, h=5, level = c(95, 99))\r\nprint(prev2)\r\nautoplot(prev2)\r\n\r\nsplit.screen( figs = c( 2, 1 ) )\r\nscreen(1)\r\nplot(prev)\r\nscreen(2)\r\nplot(prev2)\r\nclose.screen( all = TRUE )\r\n\r\n#naive sazonal\r\nautoplot(AirPassengers)\r\nprev3 = snaive(AirPassengers, h=12)\r\nprint(prev3)\r\nautoplot(prev3)\r\n\r\n#comparando a previsao com o ultimo ano\r\nprev3$mean\r\nwindow(AirPassengers,start=c(1960))\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "da859aae08a18be81cfac138c6670d1583b50afd", "size": 844, "ext": "r", "lang": "R", "max_stars_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/6.3.R Naive.r", "max_stars_repo_name": "tarsoqueiroz/Rlang", "max_stars_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/6.3.R Naive.r", "max_issues_repo_name": "tarsoqueiroz/Rlang", "max_issues_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/6.3.R Naive.r", "max_forks_repo_name": "tarsoqueiroz/Rlang", "max_forks_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9574468085, "max_line_length": 59, "alphanum_fraction": 0.6907582938, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.8198933447152498, "lm_q1q2_score": 0.744969774699792}} {"text": "# Chapter 7 Lab: Non-linear Modeling\n\nlibrary(ISLR)\nattach(Wage)\n\n# Polynomial Regression and Step Functions\n\nfit=lm(wage~poly(age,4),data=Wage)\ncoef(summary(fit))\nfit2=lm(wage~poly(age,4,raw=T),data=Wage)\ncoef(summary(fit2))\nfit2a=lm(wage~age+I(age^2)+I(age^3)+I(age^4),data=Wage)\ncoef(fit2a)\nfit2b=lm(wage~cbind(age,age^2,age^3,age^4),data=Wage)\nagelims=range(age)\nage.grid=seq(from=agelims[1],to=agelims[2])\npreds=predict(fit,newdata=list(age=age.grid),se=TRUE)\nse.bands=cbind(preds$fit+2*preds$se.fit,preds$fit-2*preds$se.fit)\npar(mfrow=c(1,2),mar=c(4.5,4.5,1,1),oma=c(0,0,4,0))\nplot(age,wage,xlim=agelims,cex=.5,col=\"darkgrey\")\ntitle(\"Degree-4 Polynomial\",outer=T)\nlines(age.grid,preds$fit,lwd=2,col=\"blue\")\nmatlines(age.grid,se.bands,lwd=1,col=\"blue\",lty=3)\npreds2=predict(fit2,newdata=list(age=age.grid),se=TRUE)\nmax(abs(preds$fit-preds2$fit))\nfit.1=lm(wage~age,data=Wage)\nfit.2=lm(wage~poly(age,2),data=Wage)\nfit.3=lm(wage~poly(age,3),data=Wage)\nfit.4=lm(wage~poly(age,4),data=Wage)\nfit.5=lm(wage~poly(age,5),data=Wage)\nanova(fit.1,fit.2,fit.3,fit.4,fit.5)\ncoef(summary(fit.5))\n(-11.983)^2\nfit.1=lm(wage~education+age,data=Wage)\nfit.2=lm(wage~education+poly(age,2),data=Wage)\nfit.3=lm(wage~education+poly(age,3),data=Wage)\nanova(fit.1,fit.2,fit.3)\nfit=glm(I(wage>250)~poly(age,4),data=Wage,family=binomial)\npreds=predict(fit,newdata=list(age=age.grid),se=T)\npfit=exp(preds$fit)/(1+exp(preds$fit))\nse.bands.logit = cbind(preds$fit+2*preds$se.fit, preds$fit-2*preds$se.fit)\nse.bands = exp(se.bands.logit)/(1+exp(se.bands.logit))\npreds=predict(fit,newdata=list(age=age.grid),type=\"response\",se=T)\nplot(age,I(wage>250),xlim=agelims,type=\"n\",ylim=c(0,.2))\npoints(jitter(age), I((wage>250)/5),cex=.5,pch=\"|\",col=\"darkgrey\")\nlines(age.grid,pfit,lwd=2, col=\"blue\")\nmatlines(age.grid,se.bands,lwd=1,col=\"blue\",lty=3)\ntable(cut(age,4))\nfit=lm(wage~cut(age,4),data=Wage)\ncoef(summary(fit))\n\n# Splines\n\nlibrary(splines)\nfit=lm(wage~bs(age,knots=c(25,40,60)),data=Wage)\npred=predict(fit,newdata=list(age=age.grid),se=T)\nplot(age,wage,col=\"gray\")\nlines(age.grid,pred$fit,lwd=2)\nlines(age.grid,pred$fit+2*pred$se,lty=\"dashed\")\nlines(age.grid,pred$fit-2*pred$se,lty=\"dashed\")\ndim(bs(age,knots=c(25,40,60)))\ndim(bs(age,df=6))\nattr(bs(age,df=6),\"knots\")\nfit2=lm(wage~ns(age,df=4),data=Wage)\npred2=predict(fit2,newdata=list(age=age.grid),se=T)\nlines(age.grid, pred2$fit,col=\"red\",lwd=2)\nplot(age,wage,xlim=agelims,cex=.5,col=\"darkgrey\")\ntitle(\"Smoothing Spline\")\nfit=smooth.spline(age,wage,df=16)\nfit2=smooth.spline(age,wage,cv=TRUE)\nfit2$df\nlines(fit,col=\"red\",lwd=2)\nlines(fit2,col=\"blue\",lwd=2)\nlegend(\"topright\",legend=c(\"16 DF\",\"6.8 DF\"),col=c(\"red\",\"blue\"),lty=1,lwd=2,cex=.8)\nplot(age,wage,xlim=agelims,cex=.5,col=\"darkgrey\")\ntitle(\"Local Regression\")\nfit=loess(wage~age,span=.2,data=Wage)\nfit2=loess(wage~age,span=.5,data=Wage)\nlines(age.grid,predict(fit,data.frame(age=age.grid)),col=\"red\",lwd=2)\nlines(age.grid,predict(fit2,data.frame(age=age.grid)),col=\"blue\",lwd=2)\nlegend(\"topright\",legend=c(\"Span=0.2\",\"Span=0.5\"),col=c(\"red\",\"blue\"),lty=1,lwd=2,cex=.8)\n\n# GAMs\n\ngam1=lm(wage~ns(year,4)+ns(age,5)+education,data=Wage)\nlibrary(gam)\ngam.m3=gam(wage~s(year,4)+s(age,5)+education,data=Wage)\npar(mfrow=c(1,3))\nplot(gam.m3, se=TRUE,col=\"blue\")\nplot.gam(gam1, se=TRUE, col=\"red\")\ngam.m1=gam(wage~s(age,5)+education,data=Wage)\ngam.m2=gam(wage~year+s(age,5)+education,data=Wage)\nanova(gam.m1,gam.m2,gam.m3,test=\"F\")\nsummary(gam.m3)\npreds=predict(gam.m2,newdata=Wage)\ngam.lo=gam(wage~s(year,df=4)+lo(age,span=0.7)+education,data=Wage)\nplot.gam(gam.lo, se=TRUE, col=\"green\")\ngam.lo.i=gam(wage~lo(year,age,span=0.5)+education,data=Wage)\nlibrary(akima)\nplot(gam.lo.i)\ngam.lr=gam(I(wage>250)~year+s(age,df=5)+education,family=binomial,data=Wage)\npar(mfrow=c(1,3))\nplot(gam.lr,se=T,col=\"green\")\ntable(education,I(wage>250))\ngam.lr.s=gam(I(wage>250)~year+s(age,df=5)+education,family=binomial,data=Wage,subset=(education!=\"1. < HS Grad\"))\nplot(gam.lr.s,se=T,col=\"green\")\n\n", "meta": {"hexsha": "1c47705b5ace0a15959f5a2fe5b0e32a8ba3ceed", "size": 3959, "ext": "r", "lang": "R", "max_stars_repo_path": "islr/r_code/chap7.r", "max_stars_repo_name": "AtmaMani/pyChakras", "max_stars_repo_head_hexsha": "e58a4e244d65858049914cf98dcb454ef009362a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "islr/r_code/chap7.r", "max_issues_repo_name": "AtmaMani/pyChakras", "max_issues_repo_head_hexsha": "e58a4e244d65858049914cf98dcb454ef009362a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T01:01:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:01:42.000Z", "max_forks_repo_path": "islr/r_code/chap7.r", "max_forks_repo_name": "AtmaMani/pyChakras", "max_forks_repo_head_hexsha": "e58a4e244d65858049914cf98dcb454ef009362a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-09T02:11:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T19:34:32.000Z", "avg_line_length": 36.6574074074, "max_line_length": 113, "alphanum_fraction": 0.7145743875, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7449697646440465}} {"text": "#!/usr/bin/env Rscript\n\n# R - https://www.r-project.org/\n#\n# Usage:\n# ./gcd.r 11 22 33 121\n# [1] 11\n#\n# Or:\n# Rscript ./gcd.r 11 22 33 121\n# [1] 11\n#\n\ngcd <- function (a, b) {\n if (b == 0) {\n a\n } else {\n gcd(b, a %% b)\n }\n}\n\ngcdn <- function(ns) {\n Reduce(gcd, ns)\n}\n\nargs <- commandArgs(trailingOnly=TRUE)\nns <- mapply(as.integer, args)\ngcdn(ns)\n", "meta": {"hexsha": "d4e11f95c5d01e679fec970efe261cfad0e70ab3", "size": 358, "ext": "r", "lang": "R", "max_stars_repo_path": "gcd.r", "max_stars_repo_name": "ip1981/GCD", "max_stars_repo_head_hexsha": "7e77b68f6879917a27a0fa3426b9ceef242a9879", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-04-18T04:59:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-05T12:48:32.000Z", "max_issues_repo_path": "gcd.r", "max_issues_repo_name": "ip1981/gcd", "max_issues_repo_head_hexsha": "7e77b68f6879917a27a0fa3426b9ceef242a9879", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcd.r", "max_forks_repo_name": "ip1981/gcd", "max_forks_repo_head_hexsha": "7e77b68f6879917a27a0fa3426b9ceef242a9879", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-11-23T17:57:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-11-23T17:57:40.000Z", "avg_line_length": 12.3448275862, "max_line_length": 38, "alphanum_fraction": 0.5391061453, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7448949826827884}} {"text": "library(tidyr)\nlibrary(ggplot2)\nlibrary(dplyr)\nlibrary(cowplot)\nlibrary(readr)\nlibrary(ggthemes)\n\n### Functions that evaluate theoretical fitness according to Sella and Hirsh\npredict_mean_fitness <- function(Ne, L, s, eps)\n{\n k <- c(0:L)\n f <- exp(-s*k^(1-eps))\t\n p_k <- (f^(2*Ne-2)*choose(L, k))/sum(f^(2*Ne-2)*choose(L, k))\n sum(f*p_k)\n}\n\nw_vs_eps <- function(Ne, L, s, epsstart, epsstop, epssteps = 0.01)\n{\n eps <- seq(epsstart, epsstop, epssteps) \n w_ave <- vapply(eps, function(eps){predict_mean_fitness(Ne, L, s, eps)}, 1)\n data.frame(s, w_ave, Ne, L, eps)\n}\n\n#########################################################################\n### Epistasis vs Fitness: theoretically derived and simulated fitness ###\n#########################################################################\n# import simulation results\nt_N100 <- read_csv(\"../processed_results/varying_eps_N100_max3.csv\")\nt_N10 <- read_csv(\"../processed_results/varying_eps_N10_max3.csv\")\n\nt <- rbind(t_N100, t_N10)\n\n# calculate a mean fitness across time when the population reached epistasis\nt %>% mutate(q = 1-epistasis_coef) %>% \n group_by(q, sel_coef, mu_prob, Ne, k_start, rep) %>% #one mean per simulation\n summarise(mean_f_over_time = mean(mean_fitness)) -> t_sum\n\nL = 100 #Number of maximum mutations\n\n### Sub-figure N=10, s=0.01\npop_size = 10\ns = 0.01\n\nt_sum %>% filter(sel_coef == s, Ne == pop_size) -> f\nan_f <- w_vs_eps(pop_size, L, s, -1, 1) %>% mutate(q=1-eps)\n\np_N10_s0.01 <- ggplot()+ \n stat_summary(data = f,\n inherit.aes = FALSE,\n aes(x = q, y = mean_f_over_time, color=factor(mu_prob)),\n fun.y = mean,\n fun.ymin = function(x) mean(x) - sd(x)/sqrt(length(x)),\n fun.ymax = function(x) mean(x) + sd(x)/sqrt(length(x)),\n geom = \"pointrange\",\n size = 0.4) +\n geom_line(data = an_f, aes(x = q, y = w_ave))+\n draw_text(x = 0, y =0, hjust = 0, vjust = 0, text = \"N = 10, s = 0.01\", size = 12, fontface = 'bold')+\n scale_y_continuous(breaks=seq(0,1,0.2))+\n coord_cartesian(ylim=c(0,1),xlim=c(0,2))+\n guides(col = guide_legend(title=\"Mutation\\nrate\"))+\n theme(axis.title = element_text(size = 14),\n axis.text = element_text(size = 12),\n legend.text = element_text(size = 11),\n legend.title = element_text(size = 12))+\n xlab('q') +\n ylab('Mean fitness') +\n scale_color_manual(labels= c(\"0.0001\", \"0.001\", \"0.01\", \"0.1\"), values = c(\"#F3DB7E\", \"#F5BE6C\", \"#E4945E\", \"#C05E4F\"))\n\n### Sub-figure N=10, s=0.001\npop_size = 10\ns = 0.001\n\nt_sum %>% filter(sel_coef == s, Ne == pop_size) -> f\nan_f <- w_vs_eps(pop_size, L, s, -1, 1) %>% mutate(q=1-eps)\n\np_N10_s0.001 <- ggplot()+ \n stat_summary(data = f,\n inherit.aes = FALSE,\n aes(x = q, y = mean_f_over_time,color=factor(mu_prob)),\n fun.y = mean,\n fun.ymin = function(x) mean(x) - sd(x)/sqrt(length(x)),\n fun.ymax = function(x) mean(x) + sd(x)/sqrt(length(x)),\n geom = \"pointrange\",\n size=0.4)+\n geom_line(data = an_f, aes(x = q, y = w_ave))+\n draw_text(x = 0, y =0, hjust = 0, vjust = 0, text = \"N = 10, s = 0.001\", size = 12, fontface = 'bold')+\n scale_y_continuous(breaks=seq(0,1,0.2))+\n coord_cartesian(ylim=c(0,1),xlim=c(0,2))+\n guides(col = guide_legend(title=\"Mutation\\nrate\"))+\n theme(axis.title = element_text(size = 14),\n axis.text = element_text(size = 12),\n legend.text = element_text(size = 11),\n legend.title = element_text(size = 12))+\n xlab('q') +\n ylab('Mean fitness') +\n scale_color_manual(labels= c(\"0.0001\", \"0.001\", \"0.01\", \"0.1\"), values = c(\"#F3DB7E\", \"#F5BE6C\", \"#E4945E\", \"#C05E4F\"))\n\n### Sub-figure N=100, s=0.01\npop_size = 100\ns = 0.01\n\nt_sum %>% filter(sel_coef == s, Ne == pop_size) -> f\nan_f <- w_vs_eps(pop_size, L, s, -1, 1) %>% mutate(q=1-eps)\n\np_N100_s0.01 <- ggplot()+ \n stat_summary(data = f,\n inherit.aes = FALSE,\n aes(x = q, y = mean_f_over_time,color=factor(mu_prob)),\n fun.y = mean,\n fun.ymin = function(x) mean(x) - sd(x)/sqrt(length(x)),\n fun.ymax = function(x) mean(x) + sd(x)/sqrt(length(x)),\n geom = \"pointrange\",\n size=0.4)+\n geom_line(data = an_f, aes(x = q, y = w_ave))+\n draw_text(x = 0, y =0, hjust = 0, vjust = 0, text = \"N = 100, s = 0.01\", size = 12, fontface = 'bold')+\n scale_y_continuous(breaks=seq(0,1,0.2))+\n coord_cartesian(ylim=c(0,1),xlim=c(0,2))+\n guides(col = guide_legend(title=\"Mutation\\nrate\"))+\n theme(axis.title = element_text(size = 14),\n axis.text = element_text(size = 12),\n legend.text = element_text(size = 11),\n legend.title = element_text(size = 12))+\n xlab('q') +\n ylab('Mean fitness') +\n scale_color_manual(labels= c(\"0.0001\", \"0.001\", \"0.01\", \"0.1\"), values = c(\"#F3DB7E\", \"#F5BE6C\", \"#E4945E\", \"#C05E4F\"))\n\n### Sub-figure N=100, s=0.001\npop_size = 100\ns = 0.001\n\nt_sum %>% filter(sel_coef == s, Ne == pop_size) -> f\nan_f <- w_vs_eps(pop_size, L, s, -1, 1) %>% mutate(q=1-eps)\n\np_N100_s0.001 <- ggplot()+ \n stat_summary(data = f,\n inherit.aes = FALSE,\n aes(x = q, y = mean_f_over_time,color=factor(mu_prob)),\n fun.y = mean,\n fun.ymin = function(x) mean(x) - sd(x)/sqrt(length(x)),\n fun.ymax = function(x) mean(x) + sd(x)/sqrt(length(x)),\n geom = \"pointrange\",\n size=0.4)+\n geom_line(data = an_f, aes(x = q, y = w_ave))+\n draw_text(x = 0, y =0, hjust = 0, vjust = 0, text = \"N = 100, s = 0.001\", size = 12, fontface = 'bold')+\n scale_y_continuous(breaks=seq(0,1,0.2))+\n coord_cartesian(ylim=c(0,1),xlim=c(0,2))+\n guides(col = guide_legend(title=\"Mutation\\nrate\"))+\n theme(axis.title = element_text(size = 14),\n axis.text = element_text(size = 12),\n legend.text = element_text(size = 11),\n legend.title = element_text(size = 12))+\n xlab('q') +\n ylab('Mean fitness') +\n scale_color_manual(labels= c(\"0.0001\", \"0.001\", \"0.01\", \"0.1\"), values = c(\"#F3DB7E\", \"#F5BE6C\", \"#E4945E\", \"#C05E4F\"))\n\n# extract the legend form the first sub-figure\ngrobs <- ggplotGrob(p_N100_s0.001)$grobs\nlegend <- grobs[[which(sapply(grobs, function(x) x$name) == \"guide-box\")]]\n\n# arrange subfigures\nprow <- plot_grid(p_N10_s0.001 + theme(legend.position=\"none\"),\n p_N10_s0.01 + theme(legend.position=\"none\", axis.title.y = element_blank()),\n p_N100_s0.001 + theme(legend.position=\"none\"),\n p_N100_s0.01 + theme(legend.position=\"none\", axis.title.y = element_blank()),\n labels=c(\"A\",\"B\",\"C\",\"D\"),\n align = 'vh',\n hjust = -1,\n ncol=2,\n nrow=2)\n\np <- plot_grid(prow, legend, rel_widths = c(2, .3))\n\nsave_plot(\"../plots/fitness_vs_epistasis.png\", p,\n ncol = 2, # we're saving a grid plot of 2 columns\n nrow = 2, # and 2 rows\n # each individual subplot should have an aspect ratio of 1.3\n base_height=4,\n base_width=4)\n\n#########################################################################\n### Two regimes: selection driven and drift driven ###\n#########################################################################\n# a function that calculates Q* (min of Q)\nf <- function(L, s, q, k){exp(-s*k**q)}\np_num <- function(L, s, N, q, k){choose(L, k)*f(L, s, q, k)**(2*N-2)}\nZ <- function(L, s, N, q){sum(p_num(L, s, N, q, 0:L))}\nfave <- function(L, s, N, q){sum(f(L, s, q, 0:L)*p_num(L, s, N, q, 0:L))/Z(L, s, N, q)}\n\n# assume p(k) independent of f(k) (i.e., no selection)\np_num2 <- function(L, s, N, q, k){choose(L, k)}\nZ2 <- function(L, s, N, q){sum(p_num2(L, s, N, q, 0:L))}\nfave2 <- function(L, s, N, q){sum(f(L, s, q, 0:L)*p_num2(L, s, N, q, 0:L))/Z2(L, s, N, q)}\n\n# assume k <= kmax only (limited drift)\nZ3 <- function(L, s, N, q, kmax){sum(p_num(L, s, N, q, 0:kmax))}\nfave3 <- function(L, s, N, q, kmax){sum(f(L, s, q, 0:kmax)*p_num(L, s, N, q, 0:kmax))/Z3(L, s, N, q, kmax)}\n\neval_model <- function(L, s, N) {\n q <- seq(0, 2, .01)\n df <- data.frame(\n q = q,\n full_model = vapply(q, function(x) fave(L, s, N, x), numeric(1)),\n no_selection = vapply(q, function(x) fave2(L, s, N, x), numeric(1)),\n limited_drift = vapply(q, function(x) fave3(L, s, N, x, 20), numeric(1))\n ) %>% gather(formula, f_ave, -q)\n}\n\n# get a data frame of 3 models evaluated for different Q values\ndf <- eval_model(L = 100, s = 0.01, N = 10)\n\ndf %>% filter(formula == \"full_model\") -> df1\ndf %>% filter(formula == \"no_selection\") -> df2\ndf %>% filter(formula == \"limited_drift\") -> df3\n\nname <- data.frame(x = c(1.76, 1.45, 1), y = c(0.34, 0.8, 0.25) , model = c(\"Full model\", \"Selection driven\", \"Drift driven\"))\n\n# Make a plot of the 3 models\np_models <- ggplot() +\n geom_line(\n data = df3, \n aes(q, f_ave, color = formula), \n size = 1,\n linetype = \"dotted\",\n color = \"#955804\",\n lineend = \"butt\") +\n geom_line(\n data = df2, \n aes(q, f_ave, color = formula), \n size = 1,\n linetype = \"dashed\",\n color = \"#3f72af\",\n lineend = \"round\") +\n geom_line(\n data = df1, \n aes(q, f_ave, color = formula), \n size = 1.1,\n lineend = \"round\") +\n geom_text(data = name, aes(x, y, label = model)) +\n xlab('q') +\n ylab('Mean fitness') +\n draw_text(x = 0, y =0, hjust = 0, vjust = 0, text = \"N = 10, s = 0.01\", size = 12, fontface = 'bold') +\n theme(plot.title = element_text(hjust = 0), legend.position=\"none\") +\n scale_color_manual(values = c(\"#000000\", \"#979797\", \"#979797\"))\n\nsave_plot(\"../plots/two_regimes.png\", \n p_models, \n # each individual subplot should have an aspect ratio of 1.3\n base_aspect_ratio = 1.2)\n\n#########################################################################\n### Theoretical calculations of Q* ###\n#########################################################################\n\n# predicted Q minimum (Q*)\nqmin <- function(N, L, s){log(L*log(2)/(2*s*N))/log(L/2)}\n\n# function that evalutes min Q (Q*) vs selection coefficient\nqmin_vs_s <- function(Ne, L, s_start, s_stop, s_steps = 0.001)\n{\n s <- seq(s_start, s_stop, s_steps) \n qmin <- vapply(s, function(s){qmin(Ne, L, s)}, 1)\n data.frame(s, qmin, Ne, L)\n}\n\n# make a data frame of Q* vs selection coefficient for N=10\ndf1 <- qmin_vs_s(10, 100, 0.0001, 0.1)\n\n# make a data frame of Q* vs selection coefficient for N=100\ndf2 <- qmin_vs_s(100, 100, 0.0001, 0.1)\n\n# make a data frame of Q* vs selection coefficient for N=1000\ndf3 <- qmin_vs_s(1000, 100, 0.0001, 0.1)\n\ndf <- rbind(df1, df2, df3)\n\n# a function that calculates Q* (min of Q)\nf <- function(L, s, q, k){exp(-s*k**q)}\np_num <- function(L, s, N, q, k){choose(L, k)*f(L, s, q, k)**(2*N-2)}\nZ <- function(L, s, N, q){sum(p_num(L, s, N, q, 0:L))}\nfave <- function(L, s, N, q){sum(f(L, s, q, 0:L)*p_num(L, s, N, q, 0:L))/Z(L, s, N, q)}\n\n# numerically find optimal q\nfopt_gen <- function(L, s, N) {\n function(q) fave(L, s, N, q)\n}\n\n# make a data frame with numerically inferred q minimum\nnum_min_q <- data.frame()\nfor (i in 1:25) {\n for (n in c(10, 100, 1000)) {\n s <- 0.0001*1.2^i\n qmin <- optimize(fopt_gen(100, s, n), interval = c(0, 10))$minimum\n row <- data.frame(s, qmin, n)\n num_min_q <- rbind(num_min_q, row)\n }\n}\n\np_qmin <- ggplot(df, aes(x = s, y = qmin, color = factor(Ne))) +\n geom_line(size = 1.1, lineend = \"round\") + \n geom_point(data = num_min_q, aes(x = s, y = qmin, color = factor(n))) +\n geom_hline(yintercept = 1) +\n scale_y_continuous(breaks=seq(0,2.5,0.5)) +\n scale_x_log10(breaks=c(0.0001, 0.001, 0.01, 0.1), labels = c(\"0.0001\", \"0.001\", \"0.01\", \"0.1\")) + \n coord_cartesian(ylim=c(0,2.6),xlim=c(0.000099999,0.1)) +\n xlab('s') +\n ylab('q*') +\n scale_color_manual(values = c(\"#9AC9D6\", \"#6E7FB3\", \"#6D0079\")) +\n guides(col = guide_legend(title=\"N\"))\n\nsave_plot(\"../plots/minimum_q_vs_selection.png\", \n p_qmin, \n # each individual subplot should have an aspect ratio of 1.3\n base_aspect_ratio = 1.3)\n\n#########################################################################\n### Simulations with high mutation rate and no selection model ###\n#########################################################################\n# evaluate fitness vs Q for the formula that's doesn't consider selection.\ndf <- eval_model(L = 100, s = 0.01, N = 100) %>% filter(formula == \"no_selection\")\nt_N100a <- read_csv(\"../processed_results/varying_eps_N100_max3.csv\")\nt_N100b <- read_csv(\"../processed_results/varying_eps_N100_max4.csv\")\n\nt <- rbind(t_N100a, t_N100b) \n\n# calculate a mean fitness across time when the population reached epistasis\nt %>% mutate(q = 1-epistasis_coef) %>% \n group_by(q, sel_coef, mu_prob, Ne, k_start, rep) %>% #one mean per simulation\n summarise(mean_f_over_time = mean(mean_fitness)) -> t_sum\n\nt_sum %>% filter(sel_coef == 0.01) -> f\n\np_mu <- ggplot() +\n geom_line(data = df, aes(q, f_ave), size = 1.1) + \n draw_text(x = 0, y =0, hjust = 0, vjust = 0, text = \"N = 100, s = 0.01\", size = 12, fontface = 'bold') +\n stat_summary(data = f,\n inherit.aes = FALSE,\n aes(x = q, y = mean_f_over_time, color=factor(mu_prob)),\n fun.y = mean,\n fun.ymin = function(x) mean(x) - sd(x)/sqrt(length(x)),\n fun.ymax = function(x) mean(x) + sd(x)/sqrt(length(x)),\n geom = \"pointrange\",\n size=0.4) +\n xlab('q') +\n ylab('Mean fitness') +\n guides(col = guide_legend(title=\"Mutation\\nrate\")) +\n scale_color_manual(labels= c(\"0.0001\", \"0.001\", \"0.01\", \"0.1\", \"1\"),\n values = c(\"#F3DB7E\", \"#F5BE6C\", \"#E4945E\", \"#C05E4F\", \"#8E063B\"))\n\nsave_plot(\"../plots/no_selection_model_vs_mu.png\", p_mu,\n # each individual subplot should have an aspect ratio of 1.3\n base_height=5,\n base_width=6)", "meta": {"hexsha": "cb22419ce5e8f91e450ef7ac7f64d3aef83d2b21", "size": 13925, "ext": "r", "lang": "R", "max_stars_repo_path": "fixed_q_sim/src/plot_figures.r", "max_stars_repo_name": "clauswilke/epistasis_evolution", "max_stars_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fixed_q_sim/src/plot_figures.r", "max_issues_repo_name": "clauswilke/epistasis_evolution", "max_issues_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fixed_q_sim/src/plot_figures.r", "max_forks_repo_name": "clauswilke/epistasis_evolution", "max_forks_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5596590909, "max_line_length": 126, "alphanum_fraction": 0.5597845601, "num_tokens": 4630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7448949788487813}} {"text": "v <- c(18,9,12,25)\nw <- c(5,2,4,6)\nW <- 10\n\nTabweights<-c(0,w)\nTabValues<-c(0,v)\nn<-length(w)\nTabMatrix<-matrix(NA,nrow =n+1,ncol = W+1)\n\nTabMatrix[,]<-0\n\nfor (j in 2:W+1){\n for (i in 2:n+1){\n if (Tabweights[i] > j) {\n TabMatrix[i,j] = TabMatrix[i-1,j]\n } \n else\n {\n TabMatrix[i,j]<-max(TabMatrix[i-1,j], TabValues[i] + TabMatrix[i-1,j-Tabweights[i]])\n }\n }\n}\n\ncat(\"The best value is\",TabMatrix[i,j])\n\ni = n+1 \nw = W+1\nItemSelected = c()\nwhile(i>1 & w>0)\n { \n if(TabMatrix[i,w]!=TabMatrix[i-1,w])\n {\n ItemSelected<-c(ItemSelected,(i)-1)\n w = w - Tabweights[i]\n i = i - 1\n }\n else\n { \n i = i - 1\n }\n}\n\ncat(\"The items selected are\",ItemSelected)\n", "meta": {"hexsha": "b78ef834fc9f42d4fab0e64c91e8f734aaae808d", "size": 708, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter05/DynamicProgramming.r", "max_stars_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_stars_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-01-19T06:32:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T06:37:07.000Z", "max_issues_repo_path": "Chapter05/DynamicProgramming.r", "max_issues_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_issues_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter05/DynamicProgramming.r", "max_forks_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_forks_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-12-25T17:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T13:19:18.000Z", "avg_line_length": 16.0909090909, "max_line_length": 92, "alphanum_fraction": 0.5268361582, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7448339037079037}} {"text": "#' BPR link cost function\r\n#'\r\n#' This function calculates the travel costs as a function of link flow using the classic separable BPR cost function. Specifically, c(x) = Alpha*(1+0.15 (x/Beta)^pow) for pow > 0; c(x) = Alpha for pow = 0.\r\n#' @param x Traffic volume on link\r\n#' @param Alpha Free flow travel time parameter\r\n#' @param Beta Link capacity parameter\r\n#' @param pow Polynomial order of cost function. Defaults to 4.\r\n#' @return Vector of link costs\r\n#' @keywords BPR link cost\r\n#' @examples\r\n#' x <- 1:25\r\n#' costs <- LinkCost(x,Alpha=5,Beta=20)\r\n#' plot(x,costs)\r\n#' @export\r\n\r\nLinkCost <- function(x,Alpha,Beta,pow=4){\r\n\tBeta[pow==0] <- 1\r\n\tAlpha*(1+(pow>0)*0.15*(x/Beta)^pow)\r\n}", "meta": {"hexsha": "9aca35cb1782156b89ea2b368c56123df976a7ce", "size": 693, "ext": "r", "lang": "R", "max_stars_repo_path": "R/LinkCost.r", "max_stars_repo_name": "MartinLHazelton/transportation", "max_stars_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/LinkCost.r", "max_issues_repo_name": "MartinLHazelton/transportation", "max_issues_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/LinkCost.r", "max_forks_repo_name": "MartinLHazelton/transportation", "max_forks_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4736842105, "max_line_length": 207, "alphanum_fraction": 0.6681096681, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632856092014, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7448338819665422}} {"text": "require(MASS)\n\n# Standard error for means\nstderr = function(x){ sqrt(var(x,na.rm=TRUE)/length(na.omit(x))) }\n\n# Geometric mean\ngmean=function(x) { exp(mean(log(x))) }\n\n# Power-law distribution functions\ndpareto=function(x, s=1, l=1) s * l^s / x^(s + 1);\nppareto=function(x, s=1, l=1) (x >= l) * (1 - (l / x)^s);\nqpareto=function(u, s=1, l=1) l/(1 - u)^(1 / s);\nrpareto=function(n, s=1, l=1) qpareto(runif(n), s, l);\n\n# Chi-square goodness of fit, d.f.=(discrete bins) - ((num parameters used in fit)+1)\ngoodfit.chisq.test=function(x,dfunc,params) {\n n=length(x)\n p=length(params)+1\n xvals=floor(min(x)):(max(x))\n ofset=min(x)-1\n counts=rep(0,length(xvals))\n for(i in 1:n) { counts[x[i]-ofset]=counts[x[i]-ofset]+1 }\n ob=counts[counts>5]\n df=length(ob)-p\n cl=call(dfunc, xvals[counts>5], params)\n if(is.call(cl)) {\n ex=eval(cl)\n ex=round(ex*sum(ob),0)\n ctmat=as.matrix(cbind(ob,ex))\n statistic=chisq.test(ctmat, correct=F)$statistic\n p.value=1-pchisq(statistic,df)\n list(statistic=statistic, df=df, p.value=p.value)\n } else {\n warning(\"unrecognized function\")\n }\n}\n\n# List of distributions fit to empirical data x, overlaid on plot\nnormhist=function(x,col=8,normcol=4,meancol=4,sdcol=5,border=F,xlab=deparse(substitute(x)),...) {\n truehist(x,col=col,border=border,xlab=xlab,...)\n lim1=par(\"usr\")[1]\n lim2=par(\"usr\")[2]\n nm=mean(x)\n nsd=sd(x)\n nx=seq(lim1,lim2,length=1000)\n ny=dnorm(nx,mean=nm,sd=nsd)\n if(!is.na(normcol)){ lines(nx,ny,col=normcol) }\n if(!is.na(meancol)){ lines(c(nm,nm),c(0,dnorm(nm,mean=nm,sd=nsd)),col=meancol) }\n if(!is.na(sdcol)){ lines(c(nm+nsd,nm+nsd),c(0,dnorm(nm+nsd,mean=nm,sd=nsd)),col=sdcol) }\n if(!is.na(sdcol)){ lines(c(nm-nsd,nm-nsd),c(0,dnorm(nm-nsd,mean=nm,sd=nsd)),col=sdcol) }\n p=ks.test(x,\"pnorm\",nm,nsd)$p\n legend(\"topright\",inset=0.05,legend=c(paste(\"Normal( \",round(nm,5),\", \",round(nsd,5),\" )\"), \"KS-test\", paste(\"p =\",signif(p,5))),bty=\"n\")\n}\n\nlognormhist=function(x,col=8,lnormcol=4,meancol=4,sdcol=5,border=F,xlab=deparse(substitute(x)),...) {\n truehist(x,col=col,border=border,xlab=xlab,...)\n lim1=par(\"usr\")[1]\n lim2=par(\"usr\")[2]\n nm=gmean(x)\n nsd=sd(x)\n lnm=mean(log(x))\n lnsd=sd(log(x))\n nx=seq(lim1,lim2,length=1000)\n ny=dlnorm(nx,meanlog=lnm,sdlog=lnsd)\n if(!is.na(lnormcol)){ lines(nx,ny,col=lnormcol) }\n if(!is.na(meancol)){ lines(c(nm,nm),c(0,dlnorm(nm,meanlog=lnm,sdlog=lnsd)),col=meancol) }\n if(!is.na(sdcol)){ lines(c(nm+nsd,nm+nsd),c(0,dlnorm(nm+nsd,meanlog=lnm,sdlog=lnsd)),col=sdcol) }\n p=ks.test(x,\"plnorm\",lnm,lnsd)$p\n legend(\"topright\",inset=0.05,legend=c(paste(\"Lognormal( \",round(lnm,5),\", \",round(lnsd,5),\" )\"), \"KS-test\", paste(\"p =\",signif(p,5))),bty=\"n\")\n}\n\ngammahist=function(x,shape,legtxt=\"\",col=8,gamcol=4,meancol=4,sdcol=NA,border=F,xlab=deparse(substitute(x)),...) {\n truehist(x,col=col,border=border,xlab=xlab,...)\n lim1=0\n lim2=par(\"usr\")[2]\n nm=mean(x)\n nsd=sd(x)\n nx=seq(lim1,lim2,length=1000)\n ny=dgamma(nx,shape=shape,rate=1/nm)\n if(!is.na(gamcol)){ lines(nx,ny,col=gamcol) }\n if(!is.na(meancol)){ lines(c(nm,nm),c(0,dgamma(nm,shape=shape,rate=1/nm)),col=meancol) }\n if(!is.na(sdcol)){ lines(c(nm+nsd,nm+nsd),c(0,dgamma(nm+nsd,shape=shape,rate=1/nm)),col=sdcol) }\n p=ks.test(x,\"pgamma\",shape,1/nm)$p\n leg=c(\"KS-test\",paste(\"p =\",signif(p,5)))\n if(nchar(legtxt)>0) {\n leg=c(legtxt, leg)\n } else {\n leg=c(paste(\"Gamma( \",round(shape,5),\", 1/\",round(nm,5),\" )\",sep=\"\"), leg)\n }\n legend(\"topright\",inset=0.05,legend=leg,bty=\"n\")\n}\n\nexphist=function(x,col=8,expcol=4,meancol=4,sdcol=NA,border=F,xlab=\"\",...) {\n gammahist(x,shape=1,paste(\"Exponential( 1, 1/\",round(mean(x),5),\" )\",sep=\"\"), col=col,gamcol=expcol,meancol=meancol,sdcol=sdcol,border=border,xlab=xlab,...)\n}\n\ndiscretehist=function(x,dfunc,param,legtxt=\"\",col=8,denscol=4,meancol=4,sdcol=NA,border=F,xlab=deparse(substitute(x)),...) {\n truehist(x,h=1,col=col,border=border,xlab=xlab,...)\n lim1=0\n lim2=par(\"usr\")[2]\n nm=mean(x)\n nsd=sd(x)\n nx=(lim1):(lim2)\n cl=call(dfunc, nx, param)\n cl2=call(dfunc, floor(nm), param)\n cl3=call(dfunc, floor(nm+nsd), param)\n if(is.call(cl)) {\n ny=eval(cl)\n if(!is.na(denscol)){ lines(nx,ny,col=denscol,type=\"s\") }\n if(!is.na(meancol)){ lines(c(nm,nm),c(0,eval(cl2)),col=meancol) }\n if(!is.na(sdcol)){ lines(c(nm+nsd,nm+nsd),c(0,eval(cl3)),col=sdcol) }\n p=goodfit.chisq.test(x,dfunc,param)$p.value\n leg=c(expression(paste(\"Pearson \",chi^2,\"-test\")),paste(\"p =\",signif(p,5)))\n if(nchar(legtxt)>0){ leg=c(legtxt,leg) }\n legend(\"topright\",inset=0.05,legend=leg,bty=\"n\")\n } else {\n warning(\"not a recognized function\")\n }\n}\n\ngeomhist=function(x,col=8,geomcol=4,meancol=4,sdcol=NA,border=F,xlab=deparse(substitute(x)),...) {\n param=1/mean(x)\n discretehist(x,\"dgeom\",param,paste(\"Geometric( 1/\",round(mean(x),5),\" )\",sep=\"\"),col,geomcol,meancol,sdcol,border,xlab,...)\n}\n\npoishist=function(x,col=8,poiscol=4,meancol=4,sdcol=NA,border=F,xlab=deparse(substitute(x)),...) {\n param=mean(x)\n discretehist(x,\"dpois\",param,paste(\"Poisson( \",round(param,5),\" )\",sep=\"\"),col,poiscol,meancol,sdcol,border,xlab,...)\n}\n\nparetohist=function(x,col=8,pcol=4,meancol=4,sdcol=NA,border=F,xlab=deparse(substitute(x)),...) {\n truehist(x,col=col,border=border,xlab=xlab,...)\n lim1=par(\"usr\")[1]\n lim2=par(\"usr\")[2]\n nm=mean(x)\n nsd=sd(x)\n location=min(x)\n nx=seq(lim1,lim2,length=1000)\n \n # estimate shape parameter, by linear regression of head of distribution on log-log\n logx=log(x)\n lxbins=seq(min(logx),max(logx),length=50)\n lxcounts=rep(0,10)\n for(i in 1:10) { lxcounts[i]=length(logx[logx>=lxbins[i] & logx% mutate(q = q)\n\nq <- 1.5\neps <- 1 - q\ns <- 0.01\nan_f2 <- w_vs_Ne(eps, 100, s, 0, 1000) %>% mutate(q = q)\n\nq <- 0.5\neps <- 1 - q\ns <- 0.01\nan_f3 <- w_vs_Ne(eps, 100, s, 0, 1000) %>% mutate(q = q)\n\n# combine all output\nrbind(an_f1, an_f2, an_f3) -> an_f\n\n# plot numerically calculated fitness for different N and q\np1 <- ggplot(an_f, aes(x = Ne, y = w_ave, color = factor(q))) +\n geom_line(size = 1, lineend = \"round\", linejoin = \"round\") +\n scale_color_manual(name = \"q\", values = c(\"#d3d4d8\", \"#3fbac2\", \"#4d606e\")) +\n xlab(\"N\") +\n ylab(\"Mean fitness\") +\n scale_x_log10(limits = c(1, 1000), breaks = c(1, 10, 100, 1000), labels = c(\"1\", \"10\", \"100\", \"1000\")) +\n coord_cartesian(ylim = c(0, 1)) +\n theme(\n axis.title = element_text(size = 14),\n axis.text = element_text(size = 12),\n legend.text = element_text(size = 11),\n legend.title = element_text(size = 12)\n )\n\n# set parameters to be used in numerical derivations\nN <- 10\ns <- 0.01\nan_f1 <- w_vs_eps(N, 100, s, -1, 1) %>% mutate(q = 1 - eps)\n\nN <- 50\ns <- 0.01\nan_f2 <- w_vs_eps(N, 100, s, -1, 1) %>% mutate(q = 1 - eps)\n\nN <- 100\ns <- 0.01\nan_f3 <- w_vs_eps(N, 100, s, -1, 1) %>% mutate(q = 1 - eps)\n\n# combine all output\nrbind(an_f1, an_f2, an_f3) -> an_f\n\n# plot numerically calculated fitness for different N and q\np2 <- ggplot(an_f, aes(x = q,y = w_ave)) +\n geom_line(\n aes(color = factor(Ne)), \n size = 1.2, \n lineend = \"round\", \n linejoin = \"round\"\n ) +\n scale_color_manual(values = c(\"#f67280\", \"#c06c84\", \"#6c5b7c\")) +\n scale_y_continuous(breaks = seq(0, 1, 0.2)) +\n coord_cartesian(ylim = c(0, 1)) +\n xlab('q') +\n ylab('Mean fitness') +\n guides(col = guide_legend(title = \"N\",reverse = TRUE))\n\np <- plot_grid(p1, p2, labels = c(\"A\", \"B\"))\n\n# save the plot\nsave_plot(\n paste0(root_dir, \"/evolving_q_sim/plots/theoretical_fitness_s\", s, \".png\"),\n p,\n base_height = 4,\n base_width = 9\n)\n", "meta": {"hexsha": "ea60698cdbda33a358c722125f85952a7475f88e", "size": 3562, "ext": "r", "lang": "R", "max_stars_repo_path": "evolving_q_sim/src/plot_theoretical_fitness.r", "max_stars_repo_name": "clauswilke/epistasis_evolution", "max_stars_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "evolving_q_sim/src/plot_theoretical_fitness.r", "max_issues_repo_name": "clauswilke/epistasis_evolution", "max_issues_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "evolving_q_sim/src/plot_theoretical_fitness.r", "max_forks_repo_name": "clauswilke/epistasis_evolution", "max_forks_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4444444444, "max_line_length": 167, "alphanum_fraction": 0.6151038742, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7439167478909391}} {"text": "### Examen Parcial 2 - Inferencia Estadistica 2\r\n### Sergio García Prado\r\n\r\nrm(list = ls())\r\n\r\n### Ejercicio 1\r\n###############################################################################\r\n\r\n### Ejercicio 1 - Apartado A\r\n\r\nobserved1 <- c(0.87, 0.20, 0.99, 0.40, 0.39, 0.72, 0.33, 0.88, 0.22, 0.45,\r\n 0.01, 0.37, 0.59, 0.80, 0.93, 0.54, 0.66, 0.49, 0.73, 0.68)\r\n\r\n(n1 <- length(observed1))\r\n#20\r\n\r\n## Función de distribución bajo hipótesis nula.\r\nCummulativeH0 <- function(x) {\r\n ifelse(x < 0, 0,\r\n ifelse(1 < x, 1,\r\n (1 / 3) * x ^ 4 * (5 - 2 * x)))\r\n}\r\n\r\n## Por ser una hipótesis simple, podemos utilizar el test de kolgomorov-smirnov\r\ntest1 <- ks.test(observed1, CummulativeH0)\r\n\r\n(D1 <- test1$statistic)\r\n# 0.4149008\r\n\r\n(pvalue1 <- test1$p.value)\r\n# 0.001244618\r\n\r\n## Nos vemos obligados a rechazar la hipótesis de que los datos observados\r\n## pertenezcan a la distribución definida en la hipótesis nula.\r\n\r\n\r\n### Ejercicio 1 - Apartado B\r\n\r\nalpha <- 0.05\r\n\r\n## Para simular la potencia calculamos el promedio sobre la variable indicador\r\n## que toma el valor 1 cuando rechazamos la hipótesis nula, y 0 en cuando la\r\n## aceptamos.\r\n\r\n(power1 <- mean(replicate(1000, ks.test(runif(n1), CummulativeH0)$p.value < alpha)))\r\n# 0.985\r\n\r\n\r\n### Ejercicio 2\r\n###############################################################################\r\n\r\n# Fijamos el número de simulaciones bootstrap.\r\nnsims2 <- 1000\r\n\r\n\r\nobserved2 <- c(2.27,2.28,0.05,0.56,0.59,1.21,0.46,1.74,1.66,0.66,1.94,0.33,\r\n 0.33,0.22,2.16,1.69,0.45,1.13,1.00,1.85,1.28,7.61,0.03,0.86,\r\n 0.66,3.84,1.42,0.80,0.25,5.03,2.23,0.83,4.33,1.35,0.91,0.87,\r\n 0.06,6.80,1.62,0.02,0.05,3.40,0.72,1.58,0.53,0.90,0.35,0.95,\r\n 0.95,0.46)\r\n\r\n(n2 <- length(observed2))\r\n# 50\r\n\r\n(observed2.mean <- mean(observed2))\r\n# 1.4654\r\n\r\n(observed2.sd <- sd(observed2))\r\n# 1.609788\r\n\r\n## Generamos una muestra bootstrap paramétrica asumiendo una distribución\r\n## normal en los datos.\r\nbootstrap.sample <- matrix(rnorm(n = n2 * nsims2, mean = observed2.mean, sd = observed2.sd),\r\n nsims2, n2)\r\n\r\nbootstrap.mean <- rowMeans(bootstrap.sample)\r\n\r\n## Utilizamos el mismo alpha que en el ejercicio anterior (alpha = 0.05)\r\n\r\nquantile(bootstrap.mean, c(alpha / 2, 1 - alpha / 2))\r\n# 2.5% 97.5%\r\n# 1.054534 1.886941\r\n\r\n\r\n### Ejercicio 3\r\n###############################################################################\r\n\r\nobserved3 <- c(20, 18, 8, 14)\r\n\r\n(k3 <- length(observed3))\r\n# 4\r\n\r\n(n3 <- sum(observed3))\r\n# 60\r\n\r\n### Ejercicio 3 - Apartado A\r\n\r\n\r\nPoissonExpected <- function(n, k, lambda) {\r\n ## Método 1\r\n\r\n # n * c(dpois(0:(k - 2), lambda = lambda),\r\n # ppois(k - 2, lambda = lambda, lower.tail = FALSE))\r\n\r\n ## Método 2:\r\n\r\n Probability <- function(x) {\r\n lambda ^ x * exp(- lambda) / factorial(x)\r\n }\r\n\r\n n * c(Probability(0:(k - 2)), 1 - sum(Probability(0:(k - 2))))\r\n}\r\n\r\nNegativeBinomialExpected <- function(n, k, size, prob) {\r\n ## Método 1\r\n\r\n # n * c(dnbinom(0:(k - 2), size = size, prob = prob),\r\n # pnbinom(k - 2, size = size, prob = prob, lower.tail = FALSE))\r\n\r\n ## Método 2:\r\n\r\n Probability <- function(x) {\r\n (x + 1) * prob ^ 2 * (1 - prob) ^ x\r\n }\r\n\r\n n * c(Probability(0:(k - 2)), 1 - sum(Probability(0:(k - 2))))\r\n}\r\n\r\n(expected3 <- PoissonExpected(n3, k3, 1.2))\r\n# 18.071653 21.685983 13.011590 7.230774\r\n\r\n(Q3 <- sum((observed3 - expected3) ^ 2 / expected3))\r\n# 9.099696\r\n\r\n(pvalue3 <- 1 - pchisq(Q3, k3 - 1))\r\n# 0.02799433\r\n\r\n## Nos vemos obligados a rechazar la hipótesis nula (los datos siguen una\r\n## distribución de Poisson(1.2)) en favor de la alternativa (no pertenecen\r\n## a dicha distribución).\r\n\r\n### Ejercicio 3 - Apartado B\r\n\r\n(null3 <- PoissonExpected(n3, k3, 1.2))\r\n# 18.071653 21.685983 13.011590 7.230774\r\n\r\n(alternative3 <- NegativeBinomialExpected(n3, k3, 2, 2 / 3))\r\n# 26.666667 17.777778 8.888889 6.666667\r\n\r\n(Q3b <- sum((alternative3 - null3) ^ 2 / null3))\r\n# 6.142462\r\n\r\n(power3b <- 1 - pchisq(qchisq(1 - alpha, df = k3 - 1), df = k3 - 1, ncp = Q3b))\r\n# 0.5286654\r\n\r\n### Ejercicio 3 - Apartado C\r\n\r\nfn <- function(n) {\r\n null <- PoissonExpected(n, k3, 1.2)\r\n alternative <- NegativeBinomialExpected(n, k3, 2, 2 / 3)\r\n Q <- sum((alternative - null) ^ 2 / null)\r\n power <- 1 - pchisq(qchisq(1 - alpha, df = k3 - 1), df = k3 - 1, ncp = Q)\r\n return(power)\r\n}\r\n\r\n(n.exact3 <- uniroot(function(n) {fn(n) - 0.9}, c(1, 1000))$root)\r\n# 138.4281\r\n\r\nceiling(n.exact3)\r\n# 139\r\n\r\n\r\n## Necesitamos un tamaño muestral de 139 observaciones para poder obtener una\r\n## potencia == 0.9 en el contraste acerca de si los datos siguen una\r\n## distribución de Poisson(1.2) cuando realmente pertenecen a una distribución\r\n## BinomialNegativa(2, 2/3)", "meta": {"hexsha": "1816259738ac27480a86e424d45030a7f1fa432e", "size": 4745, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/goodness-of-fit/2018-exam.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/goodness-of-fit/2018-exam.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/goodness-of-fit/2018-exam.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9602272727, "max_line_length": 93, "alphanum_fraction": 0.5719704953, "num_tokens": 1741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.743899254044077}} {"text": "### Code skeleton for Series 6, Exercise 1\n### Please replace all triple questionmarks by some\n### code. \n\nset.seed(3)\n(true.par <- mean(rgamma(100000000, shape = 2, rate = 2), trim = 0.1))\n\n\nset.seed(1)\nsample40 <- rgamma(n = 40, shape = 2, rate = 2)\nmean(sample40, trim = 0.1)\n\n\n###################################################\n### TASK a)\n###################################################\nrequire(\"boot\")\ntm <- function(x, ind) {mean(x[ind], trim = 0.1)}\n\n# nominal levels at which we want to evaluate coverage\nlevels <- c(round(seq(0.7, 0.99, 0.01), 2), round(seq(0.992, 0.996, 0.002), 3))\nnl <- length(levels)\n# desired coverage\nconf <- 0.9\n\n# outer layer\nM <- 50\n# inner layer and final estimate\nB <- 500\n\n# function called by the outer bootstrap\n# estimates confidence intervals on second layer of bootstrap\nboot.outer.fnn <- function(data, ind, B){\n res.boot.inner <- boot(data = data[ind], statistic = tm, R = B, \n sim = \"ordinary\")\n bci <- boot.ci(res.boot.inner, conf = levels,\n type = c(\"basic\"))\n ci <- bci[[\"basic\"]][,4:5]\n # returns theta_hat*, all lower bound and all upper bounds\n out <- c(res.boot.inner$t0, ci[,1], ci[,2])\n names(out) <- c(\"tm\", paste(\"lower\", levels, sep=\"_\"), paste(\"upper\", levels, sep=\"_\"))\n out\n}\n\n# get the confidence interval on the nominal levels 1-alpha and 1-alpha' based on B samples\n# this can be pulled from $t0\nget.ci <- function(res.boot.outer, conf, level.prime) {\n if(!is.na(level.prime)) {\n level.indices <- c(which(levels == conf), which(levels == level.prime))\n } else {\n # if we don't find any applicable level, we cheat and use the highest available\n level.indices <- c(which(levels == conf), nl)\n }\n \n lower0 <- res.boot.outer$t0[2:(nl + 1)]\n upper0 <- res.boot.outer$t0[(nl + 2):(2*nl + 1)]\n \n matrix(cbind(lower0[level.indices], upper0[level.indices]), nrow = 2,\n dimnames = list(c(\"basic\", \"double\"), c(\"lower\", \"upper\")))\n}\n\n\nres.boot.outer <- boot(sample40, statistic = boot.outer.fnn, R = M, B = B)\n\n# function to find 1 - alpha'\nget.level.prime <- function(res.boot.outer, conf){\n thh <- res.boot.outer$t0[1]\n # 1 + 33 + 33\n lower <- res.boot.outer$t[, 2:34] # lower from 2 to 34\n upper <- res.boot.outer$t[, 35:67] # upper from 35 to 67\n included <- lower <= thh & thh <= upper\n colnames(included) <- levels\n cover <- apply(included, 2, mean)\n if(max(cover) >= conf){\n level.prime <- min(levels[cover >= conf])\n } else {\n # if we are unable to to receive the desired coverage\n level.prime <- NA\n }\n level.prime\n}\n\n(level.prime <- get.level.prime(res.boot.outer, conf))\nget.ci(res.boot.outer, conf, level.prime)\n\n\n\n###################################################\n### TASK b, c)\n###################################################\n\n##' Checks if a confidence interval contains the true parameter (separately \n##' for the lower and the upper end)\n##'\n##' @param ci: Output of the function boot.ci which contains CIs\n##' @param ty: Type of confidence interval\n##' @param true.par: True parameter\n##' \n##' @return Vector with two elements where first one corresponds to the lower\n##' end and the second to the upper end of the confidence interval. \n##' If the CI is [CI_l, CI_u], the first element is 1 if theta < CI_l\n##' and 0 otherwise. The second element is 1 if theta > CI_u and 0\n##' otherwise.\ncheck_ci <- function(ci, ty, true.par) {\n # Get confidence interval of type ty from object ci\n lower.upper <- ci[ty,]\n \n res <- if (true.par < lower.upper[1]) {\n c(1, 0)\n } else if (true.par > lower.upper[2]) {\n c(0, 1)\n } else {\n c(0, 0)\n }\n names(res) <- c(\"lower\", \"upper\")\n \n return(res)\n}\n\n##' Runs one simulation run, i.e. creates new data set, calculates bootstrap\n##' CIs, and checks if true parameter is contained.\n##'\n##' @param n: Size of sample\n##' @param true.par: True parameter\n##' @param B: Number of bootstrap replicates in inner bootstrap\n##' @param M: Number of bootstrap replicates in outer bootstrap\n##' @param conf: desired coverage\n##' @param type: Type of bootstrap CIs, only \"basic\" or \"double\"\n##' \n##' @return A vector containing the result of the function check_ci for each \n##' of the confidence intervals and the estimated 1-alpha'\ndo_sim <- function(n, true.par, B = 500, M = 50, conf = 0.9,\n type = c(\"basic\", \"double\")) {\n # Generate the data\n x <- rgamma(n = n, shape = 2, rate = 2)\n # Evaluate the double bootstrap\n res.boot.outer <- boot(x, statistic = boot.outer.fnn, R = M, B = B)\n # find 1 - alpha'\n level.prime <- get.level.prime(res.boot.outer, conf)\n # find CIs at level 1-alpha and 1-alpha'\n res.ci <- get.ci(res.boot.outer, conf, level.prime)\n \n # Check if CIs contain true.par\n res <- vector(mode = \"integer\", length = 0)\n for (ty in type) {\n res <- c(res, check_ci(ci = res.ci, ty = ty, true.par = true.par))\n names(res)[(length(res) - 1):length(res)] <- \n paste(c(ty, ty), c(\"lower\", \"upper\"), sep = \"_\") #add names in the format \n #'type_lower' and 'type_upper'\n }\n # store 1 - alpha' as well\n res <- c(res, level.prime)\n names(res)[length(res)] <- \"level.prime\"\n \n return(res)\n}\n\n##########################\n### Run simulation ###\n##########################\nset.seed(22)\nrequire(\"boot\")\nsample.size <- c(10, 40, 160, 640)\nn.sim <- 200\ntype <- c(\"basic\", \"double\")\n\n# The object RES stores the results, i.e. each row corresponds\n# to the non-coverage rate for the lower and upper ends of the \n# confidence intervals, i.e. the percentage of times that theta < CI_l \n# and the percentage of times that theta > CI_u, if the CI is \n# denoted by (CI_l, CI_u). Further we add one column for the median of the estimated 1 - alpha',\n# one for the fraction of times we could not find 1 - alpha' and one for n. \nRES <- matrix(NA, nrow = length(sample.size), ncol = 7)\ncolnames(RES) <- c(paste(rep(type, each = 2), \n rep(c(\"lower\", \"upper\"), times = length(type)), \n sep = \"_\"), \"median_level_prime\", \"NA_fraction\", \"n\")\n\nfor (j in 1:length(sample.size)) {\n n <- sample.size[j]\n cat(\"n =\", n ,\"\\n\")\n # The object res.sim stores the results, i.e. each row corresponds\n # to the output of the function do_sim. This means that each row contains 0\n # and 1 encoding whether the true parameter was inside the CI or outside\n # as well as 1 - alpha'.\n res.sim <- matrix(NA, nrow = n.sim, ncol = length(type) * 2 + 1)\n for (i in 1:n.sim) {\n cat(\".\"); if(i %% 20 == 0) cat(i ,\"\\n\")\n # Simulate one data-set\n res.sim[i, ] <- do_sim(n = n, true.par = true.par, type = type)\n }\n # Compute the upper and lower non-coverage rate, the median of 1 - alpha' \n # and the fraction of simulation runs, where we did not find 1 - alpha'\n RES[j, ] <- c(apply(res.sim[,1:(length(type) * 2)], 2, mean),\n median(res.sim[,(length(type) * 2) + 1 ], na.rm = TRUE),\n mean(is.na(res.sim[,(length(type) * 2) + 1 ])), n)\n}\n\n\ny.lim <- max(RES[, 1:(length(type) * 2)])\n\n# Plot of lower non-coverage\nplot(basic_lower ~ n, data = RES, col = 1, pch = 1, ylim = c(0, y.lim), \n log = \"x\", ylab = \"One-sided non-coverage\", \n main = \"Non-coverage of the lower end of the CIs.\") \npoints(double_lower ~ n, data = RES, col = 2, pch = 2, xlog = TRUE)\nlines(basic_lower ~ n, data = RES, col = 1, lty = 1, xlog = TRUE)\nlines(double_lower ~ n, data = RES, col = 2, lty = 2, xlog = TRUE)\nabline(h = 0.05, lty = 5)\nlegend(\"topright\", legend = c(\"reversed\", \"double bootstrap\"), \n pch = 1:2, lty = 1:2, col = 1:2)\n\n# do it analogously for the upper non-coverage", "meta": {"hexsha": "ca64b352aba6d9f85de116fdbff0127eb9d8b5a8", "size": 7677, "ext": "r", "lang": "R", "max_stars_repo_path": "Computational_Statistics/Exercices/6_1.r", "max_stars_repo_name": "DanDoge/course_ethz", "max_stars_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Computational_Statistics/Exercices/6_1.r", "max_issues_repo_name": "DanDoge/course_ethz", "max_issues_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computational_Statistics/Exercices/6_1.r", "max_forks_repo_name": "DanDoge/course_ethz", "max_forks_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2122641509, "max_line_length": 96, "alphanum_fraction": 0.5971082454, "num_tokens": 2278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7438448662371545}} {"text": "### Code skeleton for Series 5, Exercise 2\n### Please replace all triple questionmarks by some\n### code. \n\n###################################################\n### TASK a)\n###################################################\nset.seed(3)\n(true.par <- mean(rgamma(100000000, shape = 2, rate = 2), trim = 0.1))\n\nprint(true.par)\n\n###################################################\n### TASK b)\n###################################################\nset.seed(1)\nsample40 <- rgamma(n = 40, shape = 2, rate = 2)\n\nprint(mean(sample40, trim = 0.1))\n \n###################################################\n### TASK c)\n###################################################\nrequire(\"boot\")\ntm <- function(x, ind) {mean(x[ind], trim = 0.1)}\n\nres.boot <- boot(data = sample40, statistic = tm, R = 10000, \n sim = \"ordinary\")\nprint(boot.ci(res.boot, conf = 0.95, type = c(\"basic\", \"norm\", \"perc\")))\n\n\n###################################################\n### TASK d)\n###################################################\n\n##' Checks if a confidence interval contains the true parameter (separately \n##' for the lower and the upper end)\n##'\n##' @param ci: Output of the function boot.ci which contains CIs\n##' @param ty: Type of confidence interval\n##' @param true.par: True parameter\n##' \n##' @return Vector with two elements where first one corresponds to the lower\n##' end and the second to the upper end of the confidence interval. \n##' If the CI is [CI_l, CI_u], the first element is 1 if theta < CI_l\n##' and 0 otherwise. The second element is 1 if theta > CI_u and 0\n##' otherwise.\ncheck_ci <- function(ci, ty, true.par) {\n # Get confidence interval of type ty from object ci\n lower.upper <- switch (ty,\n \"norm\" = ci[[\"normal\"]][2:3],\n \"perc\" = ci[[\"percent\"]][4:5], \n \"basic\" = ci[[\"basic\"]][4:5]\n )\n \n res <- if (true.par < lower.upper[1]) {\n c(1, 0)\n } else if (true.par > lower.upper[2]) {\n c(0, 1)\n } else {\n c(0, 0)\n }\n names(res) <- c(\"lower\", \"upper\")\n \n return(res)\n}\n\n##' Runs one simulation run, i.e. creates new data set, calculates bootstrap\n##' CIs, and checks if true parameter is contained.\n##'\n##' @param n: Size of sample\n##' @param true.par: True parameter\n##' @param R: Number of bootstrap replicates\n##' @param type: Type of bootstrap CIs, see function boot.ci\n##' \n##' @return A vector containing the result of the function check_ci for each \n##' of the confidence intervals\ndo_sim <- function(n, true.par, R = 500, \n type = c(\"basic\", \"norm\", \"perc\")) {\n # Generate the data\n x <- rgamma(n = 40, shape = 2, rate = 2)\n # Construct the CIs for the trimmed mean\n res.boot <- boot(data = x, statistic = tm, R = R, sim = \"ordinary\")\n res.ci <- boot.ci(res.boot, conf = 0.95, type = type)\n \n # Check if CIs contain true.par\n res <- vector(mode = \"integer\", length = 0)\n for (ty in type) {\n res <- c(res, check_ci(ci = res.ci, ty = ty, true.par = true.par))\n names(res)[(length(res) - 1):length(res)] <- \n paste(c(ty, ty), c(\"lower\", \"upper\"), sep = \"_\") #add names in the format \n #'type_lower' and 'type_upper'\n }\n\n return(res)\n}\n\n##########################\n### Run simulation ###\n##########################\nset.seed(22)\nrequire(\"boot\")\nsample.size <- c(10, 40, 160, 640)\nn.sim <- 200\ntype <- c(\"basic\", \"norm\", \"perc\")\n\n# The object RES stores the results, i.e. each row corresponds\n# to the non-coverage rate for the lower and upper ends of the \n# confidence intervals, i.e. the percentage of times that theta < CI_l \n# and the percentage of times that theta > CI_u, if the CI is \n# denoted by (CI_l, CI_u). The last column of RES corresponds to \n# the number of observations. \nRES <- matrix(NA, nrow = length(sample.size), ncol = length(type) * 2 + 1)\ncolnames(RES) <- c(paste(rep(type, each = 2), \n rep(c(\"lower\", \"upper\"), times = length(type)), \n sep = \"_\"), \"n\")\n\nfor (j in 1:length(sample.size)) {\n n <- sample.size[j]\n # The object res.sim stores the results, i.e. each row corresponds\n # to the output of the function do_sim. This means that each row contains 0\n # and 1 encoding whether the true parameter was inside the CI or outside. \n # Also see the function check_ci.\n res.sim <- matrix(NA, nrow = n.sim, ncol = length(type) * 2)\n for (i in 1:n.sim) {\n # Compute CIs and check if true.par is contained in them\n res.sim[i, ] <- do_sim(n = n, true.par = true.par, type = type)\n }\n # Compute the upper and lower non-coverage rate\n RES[j, ] <- c(apply(res.sim, 2, mean), n)\n}\n\nprint(RES)\n\n###################################################\n### TASK e)\n###################################################\ny.lim <- max(RES[, -ncol(RES)])\n\n# Plot of lower non-coverage\nplot(basic_lower ~ n, data = RES, col = 1, pch = 1, ylim = c(0, y.lim), \n log = \"x\", ylab = \"One-sided non-coverage\", \n main = \"Non-coverage of the lower end of the CIs.\") \npoints(norm_lower ~ n, data = RES, col = 2, pch = 2, xlog = TRUE)\npoints(perc_lower ~ n, data = RES, col = 3, pch = 3, xlog = TRUE)\nlines(basic_lower ~ n, data = RES, col = 1, lty = 1, xlog = TRUE)\nlines(norm_lower ~ n, data = RES, col = 2, lty = 2, xlog = TRUE)\nlines(perc_lower ~ n, data = RES, col = 3, lty = 3, xlog = TRUE)\nabline(h = 0.025, lty = 5)\nlegend(\"topright\", legend = c(\"quantile\", \"normal\", \"reverse\"), \n pch = 1:3, lty = 1:3, col = 1:3)\n\n# do it analogously for the upper non-coverage", "meta": {"hexsha": "6826f0a7d07bba37ac74263f6b83bef028a87b20", "size": 5610, "ext": "r", "lang": "R", "max_stars_repo_path": "Computational_Statistics/Exercices/5_2.r", "max_stars_repo_name": "DanDoge/course_ethz", "max_stars_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Computational_Statistics/Exercices/5_2.r", "max_issues_repo_name": "DanDoge/course_ethz", "max_issues_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computational_Statistics/Exercices/5_2.r", "max_forks_repo_name": "DanDoge/course_ethz", "max_forks_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6666666667, "max_line_length": 85, "alphanum_fraction": 0.534402852, "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7436980491723525}} {"text": "library(CreditMetrics)\nset.seed(1)\n\nRatingClasses <- c(\"AAA\", \"AA\", \"A\", \"BBB\", \"BB\", \"B\", \"CCC\", \"D\")\nTransitionMatrix <- matrix(c(90.710,\t8.340,\t0.710,\t0.075,\t0.095,\t0.025,\t0.022,\t0.023,\n 0.710,\t90.550,\t7.810,\t0.720,\t0.060,\t0.120,\t0.020,\t0.010,\n 0.092,\t2.220,\t91.250,\t5.420,\t0.720,\t0.230,\t0.011,\t0.057,\n 0.020,\t0.420,\t5.890,\t85.880,\t5.290,\t1.190,\t1.140,\t0.170,\n 0.036,\t0.124,\t0.670,\t7.730,\t80.590,\t8.790,\t1.010,\t1.050,\n 0.011,\t0.119,\t0.230,\t0.440,\t6.510,\t83.440,\t4.060,\t5.190,\n 0.220,\t0.000,\t0.230,\t1.330,\t2.360,\t11.210,\t64.830,\t19.820,\n 0, 0, 0, 0, 0, 0, 0, 100\n)/100, 8, 8, dimnames = list(RatingClasses, RatingClasses), byrow = TRUE)\nTransitionMatrix\n\nlibrary(markovchain)\n\nMCModel <- new(\"markovchain\", transitionMatrix = TransitionMatrix, states=RatingClasses, byrow = TRUE, name=\"MarkovChainModel\")\nMCModel\n\nMCModel@states\n\ntransitionProbability(MCModel,\"AAA\",\"AA\")\n\n#CREDIT SPREAD\n\nLGD <- 0.40\n\nCreditRiskSpread<-cm.cs(TransitionMatrix, LGD)\nCreditRiskSpread\n\n\n# reference value\nRating <- c(\"B\", \"BB\", \"CCC\")\nEAD <- c(4000, 10000, 500000)\nRindex <- 0.02\n\nRefValue<-cm.ref(TransitionMatrix, LGD, EAD, Rindex, Rating)\n\nRefValue$constVal\nRefValue$constPV\n\nabsorbingStates(MCModel)", "meta": {"hexsha": "b6fe3edb1577a18f133c2de2314c8e1852c76f10", "size": 1382, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter09/CreditRisk1.r", "max_stars_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_stars_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-01-19T06:32:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T06:37:07.000Z", "max_issues_repo_path": "Chapter09/CreditRisk1.r", "max_issues_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_issues_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter09/CreditRisk1.r", "max_forks_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_forks_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-12-25T17:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T13:19:18.000Z", "avg_line_length": 32.1395348837, "max_line_length": 127, "alphanum_fraction": 0.5730824891, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7433695094895312}} {"text": "fib <- function(n) {\n if (n < 2) n else Recall(n - 1) + Recall(n - 2)\n}\n\nfibLinear <- function(n) {\n fibs <- c(0, 1)\n while (n > 0) {\n temp <- fibs[2]\n fibs[2] <- sum(fibs)\n fibs[1] <- temp\n n <- n - 1\n }\n fibs[1]\n}\n\nfibFormula <- function(n) {\n round(((5 ^ 0.5 + 1) / 2) ^ n / 5 ^ 0.5)\n}\n\nfibTailRecursive <- function(n, prevFib = 0, fib = 1) {\n if (n == 0) prevFib else Recall(n - 1, fib, prevFib + fib)\n}\n\nfibFastDoubling <- function(n) {\n fibFastAuxiliary <- function(n) {\n if (n == 0) return(list(0, 1))\n\n fibs <- Recall(floor(n / 2))\n prevFib <- fibs[[1]]\n fib <- fibs[[2]]\n a <- prevFib * (fib * 2 - prevFib)\n b <- prevFib * prevFib + fib * fib\n if (n %% 2 == 0) list(a, b) else list(b, a + b)\n }\n fibFastAuxiliary(n)[[1]];\n}\n\nargs = commandArgs(trailingOnly=TRUE)\ninput = if (length(args) > 0) as.numeric(args[1]) else 29\nprint(fibFastDoubling(input))\n", "meta": {"hexsha": "64cd3bffcbaeb1cd4d100b65e89ec8eed3d5fca2", "size": 903, "ext": "r", "lang": "R", "max_stars_repo_path": "language/r/fib.r", "max_stars_repo_name": "A1rPun/nurture", "max_stars_repo_head_hexsha": "d050837444a7ffb6d38be78044e7c1678f92b2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-30T17:12:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T17:12:31.000Z", "max_issues_repo_path": "language/r/fib.r", "max_issues_repo_name": "A1rPun/nurture", "max_issues_repo_head_hexsha": "d050837444a7ffb6d38be78044e7c1678f92b2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "language/r/fib.r", "max_forks_repo_name": "A1rPun/nurture", "max_forks_repo_head_hexsha": "d050837444a7ffb6d38be78044e7c1678f92b2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0243902439, "max_line_length": 60, "alphanum_fraction": 0.5415282392, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7431680864678625}} {"text": "#Intro\npng(\"#45_confidence_interval_around_model.png\" , width = 480, height = 480 )\npar(mar=c(2,2,1,1))\n\n# We create 2 vectors x and y. It is a polynomial function.\nx <- runif(300, min=-30, max=30) \ny <- -1.2*x^3 + 1.1 * x^2 - x + 10 + rnorm(length(x),0,100*abs(x)) \n \n# Basic plot of x and y :\nplot(x,y,col=rgb(0.4,0.4,0.8,0.6), pch=16 , cex=1.3 , xlab=\"\" , ylab=\"\") \n \n# Can we find a polynome that fit this function ?\nmodel=lm(y ~ x + I(x^2) + I(x^3))\n\n# I can get the features of this model :\nsummary(model)\nmodel$coefficients\nsummary(model)$adj.r.squared\n\n#For each value of x, I can get the value of y estimated by the model, and the confidence interval around this value.\nmyPredict <- predict( model , interval=\"predict\" )\n\n#Finally, I can add it to the plot using the line and the polygon function with transparency.\nix <- sort(x,index.return=T)$ix\nlines(x[ix], myPredict[ix , 1], col=2, lwd=2 ) \npolygon(c(rev(x[ix]), x[ix]), c(rev(myPredict[ ix,3]), myPredict[ ix,2]), col = rgb(0.7,0.7,0.7,0.4) , border = NA)\n\ndev.off()\n\n\n", "meta": {"hexsha": "33795dbc6b5c86916346c6837754a2378a203815", "size": 1037, "ext": "r", "lang": "R", "max_stars_repo_path": "OLD_GALLERY_RSCRIPT/#45_confidence_interval_around_model.r", "max_stars_repo_name": "JedStephens/R-graph-gallery", "max_stars_repo_head_hexsha": "a7a65d2f66372ea3724cf6e930d3c4b209f44dad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 447, "max_stars_repo_stars_event_min_datetime": "2016-10-05T14:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:20:42.000Z", "max_issues_repo_path": "OLD_GALLERY_RSCRIPT/#45_confidence_interval_around_model.r", "max_issues_repo_name": "JedStephens/R-graph-gallery", "max_issues_repo_head_hexsha": "a7a65d2f66372ea3724cf6e930d3c4b209f44dad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2016-10-20T14:45:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T19:15:22.000Z", "max_forks_repo_path": "OLD_GALLERY_RSCRIPT/#45_confidence_interval_around_model.r", "max_forks_repo_name": "JedStephens/R-graph-gallery", "max_forks_repo_head_hexsha": "a7a65d2f66372ea3724cf6e930d3c4b209f44dad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 172, "max_forks_repo_forks_event_min_datetime": "2015-12-01T15:34:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:37:06.000Z", "avg_line_length": 33.4516129032, "max_line_length": 117, "alphanum_fraction": 0.6547733848, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7431329840095778}} {"text": "#Copyright (c) 2016 Riccardo Francescato\np = 5 # number of rows \nN = p^2\nalpha = .05\nRawLatin=c(\"A\",\"B\",\"C\",\"D\",\"E\",\n \t\t\t\"B\",\"C\",\"D\",\"E\",\"A\",\n \t\t\t\"C\",\"D\",\"E\",\"A\",\"B\",\n \t\t\t\"D\",\"E\",\"A\",\"B\",\"C\",\n \t\t\t\"E\",\"A\",\"B\",\"C\",\"D\")\nRawData = c(-1,-5,-6,-1,-1,\n \t\t \t-8,-1, 5, 2,11,\n \t\t \t-7,13, 1, 2,-4,\n \t\t \t 1, 6, 1,-2,-3,\n \t\t \t-3, 5,-5, 4, 6)\n\ndata = matrix(RawData,nrow=p,ncol=p,byrow = TRUE) \nlatin = matrix(RawLatin,nrow=p,ncol=p,byrow = TRUE) \n\nSStot = sum(data^2) - sum(data)^2/N\n\nSSrows = 0\nfor(i in 1:p){\n\tSSrows = SSrows + sum(data[i,])^2\n}\nSSrows = SSrows *(1/p) - sum(data)^2/N\n\nSScol = 0\nfor(i in 1:p){\n\tSScol = SScol + sum(data[,i])^2\n}\nSScol = SScol *(1/p) - sum(data)^2/N\n\nTreatTot = vector(,p)\nfor(i in 1:p){\n\tTreatTot[i]=0\n}\n\nfor(i in 1:N){\n\tif(RawLatin[i]==\"A\") TreatTot[1]=TreatTot[1]+RawData[i]\n\tif(RawLatin[i]==\"B\") TreatTot[2]=TreatTot[2]+RawData[i]\n\tif(RawLatin[i]==\"C\") TreatTot[3]=TreatTot[3]+RawData[i]\n\tif(RawLatin[i]==\"D\") TreatTot[4]=TreatTot[4]+RawData[i]\n\tif(RawLatin[i]==\"E\") TreatTot[5]=TreatTot[5]+RawData[i]\n}\n\nSStreat=0\nfor(i in 1:p){\n\tSStreat = SStreat + TreatTot[i]^2\n}\nSStreat = SStreat *(1/p) - sum(data)^2/N\n\n\nSSerr = SStot - SSrows - SScol - SStreat\n\nMStreat = SStreat/(p-1)\nMSrows = SSrows/(p-1)\nMScols = SScol/(p-1)\nMSerr = SSerr/((p-2)*(p-1))\n\nF0 = MStreat/MSerr\nFa = qf(alpha,df1=p-1,df2=((p-2)*(p-1)),lower.tail=F)\n\nif(F0 > Fa) print(paste0(\" reject H0 \", F0)) else print(paste0(\" Accept H0 \", F0))\ncat(paste0(\" Treatments SS: \",SStreat,\" Df: \", p-1 ,\" MS: \",MStreat, \" F0: \",F0,\n\t\t\"\\n Rows SS: \",SSrows,\" Df: \", p-1 ,\" MS: \",MSrows,\n\t\t\"\\n Cols SS: \",SScol,\" Df: \", p-1 ,\" MS: \",MScols,\n\t\t\"\\n Error SS: \",SSerr,\" Df: \", (p-2)*(p-1) ,\" MS: \",MSerr,\n\t\t\"\\n Total SS: \",SStot,\" Df: \", (p^2)-1))\n\n\ndelivery.df = data.frame(\n Opersators = c(rep(\"O1\", p), rep(\"O2\", p), rep(\"O3\", p), rep(\"O4\", p), rep(\"O5\", p)),\n Batches = c(rep(c(\"B1\", \"B2\", \"B3\", \"B4\",\"B5\"), p)),\n Formulation = RawLatin,\n Data = RawData\n)\n\ndelivery.mod1 = lm(Data ~ Formulation+Batches+Opersators, delivery.df)\nanova(delivery.mod1)\n", "meta": {"hexsha": "8dcd962a1b43d731487558c51fdece609ca584a6", "size": 2061, "ext": "r", "lang": "R", "max_stars_repo_path": "ANOVA_latin.r", "max_stars_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_stars_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ANOVA_latin.r", "max_issues_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_issues_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ANOVA_latin.r", "max_forks_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_forks_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7625, "max_line_length": 87, "alphanum_fraction": 0.5516739447, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.743120466467532}} {"text": "### 判別分析の例\n### - 企業別の利益データ (2007-2012年度)\n\n## データの読み込み (\"jpcompany.csv\"を用いる)\nraw <- read.csv(file=\"data/jpcompany.csv\",row.names=1) # データの読み込み\nscan(file=\"data/jpcompany.txt\",what=character(),sep=\";\") # 説明の表示\n\n## データの内容を表示\n## print(raw) # 全データの表示\nhead(raw,n=3) # 最初の3個を表示\n## tail(raw,n=3) # 最後の3個を表示\n\n## 判別分析のためにデータを整形\n## class: 2011年から2012年に掛けて営業利益が増収(pos)/減収(neg)\n## 特徴量: 売上高に占める各利益の割合\nmydata <- data.frame(class=ifelse(raw[,26]-raw[,22]>0,\"pos\",\"neg\"))\nfor (k in 1:5){\n mydata <- data.frame(mydata,raw[,(4*k+1)+(1:3)]/raw[,4*k+1])\n}\nnames(mydata)[2:ncol(mydata)] <- # 特徴量の名前\n paste(rep(c(\"営業利益率\",\"経常利益率\",\"純利益率\"),5),\n rep((1:5)+2006,each=3),sep=\".\")\nrownames(mydata) <- raw[,2] # 各社の名前\nmydata <- na.exclude(mydata) # 欠損(NA)の除去 \nhead(mydata,n=3) # 最初の3個を表示\n\n## データの一部とラベルの関係を図示\nitem <- c(1,5,8,11,14)\n## print(names(mydata)[item]) # 項目名の表示\n## データの散布図: 図(a)\nggpairs(mydata,\n columns=item, mapping=aes(colour=class)) +\n theme(text=element_text(family=\"HiraMaruProN-W4\"))\n## ## ggscatmat を用いる場合 (class以外が表示される)\n## ggscatmat(mydata,\n## columns=item, color=\"class\", alpha=.5) +\n## theme(text=element_text(family=\"HiraMaruProN-W4\"))\n\n## データ全体で判別式を作成\nmodel <- lda(class ~ ., data=mydata)\ntable(true=mydata$class,predict=predict(model)$class)\n\n## 線形判別関数の値の分布をクラス毎に表示\npredict.tr <- predict(model) \nres.tr <- data.frame(x=as.vector(predict.tr$x), \n class=mydata$class,\n d=c(neg=0,pos=1)[mydata$class]) \n## 判別関数の値の分布: 図(b)\nggplot(res.tr, aes(x)) + \n geom_histogram(aes(fill=class)) +\n facet_grid(class ~ .) + theme(legend.position=\"none\") \n\n## 全体を用いると判別があまり良好でないので\n## 2011年の経常利益率で層別に調べてみる\n## (業種別に調べると良いかもしれないが各業種のデータが少ない)\nconditions <- c(\"経常利益率.2011<0.05\",\n \"経常利益率.2011>0.05&経常利益率.2011<0.1\",\n \"経常利益率.2011>0.1&経常利益率.2011<0.2\",\n \"経常利益率.2011>0.2\")\nfor(i in 1:4){\n subdata <- subset(mydata, subset=eval(parse(text=conditions[i])))\n submodel <- lda(class ~ ., data=subdata)\n tbl <- table(true=subdata$class,predict=predict(submodel)$class)\n print(conditions[i])\n print(tbl)\n ## 線形判別関数の値の分布をクラス毎に表示\n predict.tr <- predict(submodel) \n res.tr <- data.frame(x=as.vector(predict.tr$x), \n class=subdata$class,\n d=c(neg=0,pos=1)[subdata$class]) \n ## 層別の判別関数の値の分布: 図(c)-(f)\n gg <- ggplot(res.tr, aes(x)) + \n geom_histogram(aes(fill=class)) +\n facet_grid(class ~ .) +\n theme(text=element_text(family=\"HiraMaruProN-W4\"),\n legend.position=\"none\") +\n labs(title=conditions[i])\n print(gg)\n}\n", "meta": {"hexsha": "754257cd911e8e8272bb7ba4bdaced79f2f532e9", "size": 2616, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/code/d-jpcompany.r", "max_stars_repo_name": "noboru-murata/multivariate-analysis", "max_stars_repo_head_hexsha": "645bff23d3868e5d7c245ef4af7d0ff9fe98e017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/code/d-jpcompany.r", "max_issues_repo_name": "noboru-murata/multivariate-analysis", "max_issues_repo_head_hexsha": "645bff23d3868e5d7c245ef4af7d0ff9fe98e017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/code/d-jpcompany.r", "max_forks_repo_name": "noboru-murata/multivariate-analysis", "max_forks_repo_head_hexsha": "645bff23d3868e5d7c245ef4af7d0ff9fe98e017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7, "max_line_length": 69, "alphanum_fraction": 0.6154434251, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7431204543525399}} {"text": "do.sim <- function(mix.par=0.2,mu1=5,sigma1=4,mu2=5,df=4,n=30,\r\n alpha.vec=c(0,0.1,0.2), M=1000) {\r\n#Purpose:\r\n# Runs a simulation to compute the RMSEs for trimmed means from \r\n# samples taken from a 2 point normal and t mixture model\r\n#Inputs:\r\n# mix.par - mixture parameter of the distribution (range 0-1)\r\n# mu1 - mean of the normal component of the mixture\r\n# sigma1 - sd of the normal component of the mixture\r\n# mu2 - mean of the t component of the mixture\r\n# df - degrees of freedom for the t component\r\n# n - size of samples to generate in simulation\r\n# alpha.vec - vector of trimming levels to try (0=no trim i.e. mean, \r\n# 0.5=trim 50th quantile above and below - i.e., median)\r\n# M - number of simultions to run\r\n#Output: List containing elements:\r\n# MSE - vector of the MSEs at each trim level\r\n# ests - matrix with M rows and length(alpha.vec) columns containing the raw estimates\r\n# mu - the true mean of the input distribution\r\n \r\n \r\n#initialize matrix of outputs\r\n est.matrix <- matrix(NA,M,length(alpha.vec)) \r\n#run simulation\r\n for(simulation in 1:M) {\r\n temp <- mix.dist(n,mix.par,mu1,sigma1,mu2,df) \r\n est.matrix[simulation, ] <- estimate.mean(temp,alpha.vec) \r\n }\r\n \r\n#work out the expected value of the input distribution\r\n E.Z <- get.expectation(mix.par,mu1,mu2)\r\n \r\n#Calculate MSEs \r\n mean.square.error <- mean.square.error(est.matrix,E.Z)\r\n \r\n return(list(MSE=mean.square.error, ests=est.matrix, mu=E.Z))\r\n \r\n} ", "meta": {"hexsha": "0bc8539bdf95d4eb3cb6d87c6b8f983cbbf7a8fd", "size": 1475, "ext": "r", "lang": "R", "max_stars_repo_path": "Practicals/Practical 3/functions/do.sim.r", "max_stars_repo_name": "yc59/2018", "max_stars_repo_head_hexsha": "4c74a67a4d0dadecc4213dd57289120b31806aa6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Practicals/Practical 3/functions/do.sim.r", "max_issues_repo_name": "yc59/2018", "max_issues_repo_head_hexsha": "4c74a67a4d0dadecc4213dd57289120b31806aa6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Practicals/Practical 3/functions/do.sim.r", "max_forks_repo_name": "yc59/2018", "max_forks_repo_head_hexsha": "4c74a67a4d0dadecc4213dd57289120b31806aa6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8157894737, "max_line_length": 87, "alphanum_fraction": 0.6833898305, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7426977926012532}} {"text": ".kernel.squared.exponential <- function(x1, x2, l) {\n factor <- -1.0 / (2 * l * l)\n if (is.matrix(x1)) {\n sigma <- matrix(0, nrow(x1), nrow(x2))\n for (i in 1:nrow(sigma)) {\n v <- t(x1[i,] - t(x2))\n rsq <- apply(v * v, 1, sum)\n sigma[i,] <- exp(factor * rsq)\n }\n } else {\n sigma <- matrix(0, length(x1), length(x2))\n for (i in 1:nrow(sigma)) {\n v <- x1[i] - x2\n sigma[i,] <- exp(factor * v * v)\n }\n }\n\n return(sigma)\n}\n\n.kernel.se.integral <- function(alpha, l, D) {\n d <- sqrt((2*pi*l*l)^D)\n integral <- sum(d * alpha)\n return(integral)\n}\n\n.kernel.matern32 <- function(x1, x2, l) {\n if (is.matrix(x1)) {\n sigma <- matrix(0, nrow(x1), nrow(x2))\n for (i in 1:nrow(sigma)) {\n v <- t(x1[i,] - t(x2))\n rsq <- apply(v * v, 1, sum)\n y <- sqrt(3) * sqrt(rsq) / l\n sigma[i,] <- (1 + y) * exp(-y)\n }\n } else {\n sigma <- matrix(0, length(x1), length(x2))\n for (i in 1:nrow(sigma)) {\n v <- x1[i] - x2\n y <- sqrt(3) * sqrt(v * v) / l\n sigma[i, ] <- (1 + y) * exp(-y)\n }\n }\n \n return(sigma)\n}\n\n.kernel.matern32.integral <- function(alpha, l, D) {\n d <- 2 * (1+D) * (l * sqrt(pi/3)) ^ D * gamma(D) / gamma(D / 2)\n integral <- sum(d * alpha)\n return(integral)\n}\n\n.gp.log.marginal.likelihood <- function(l, b1, b2, result, verbose) {\n kxx <- result$kernel(result$x, result$x, l) + result$sigman * diag(result$n)\n \n return_value <- try(L <- chol(kxx), silent = !verbose)\n if (inherits(return_value, \"try-error\")) {\n return(NA)\n }\n \n if (is.null(result$meanfn)) {\n mean_sub <- rep(NA, length(result$p))\n for (i in 1:length(result$p)) {\n mean_sub[i] <- result$p[i] - b1 - b2 * (result$xcentered[i,] %*% result$xcentered[i,])\n }\n p1 <- sum(backsolve(L, mean_sub, transpose = T) ^ 2)\n } else {\n p1 <- sum(backsolve(L, result$pmean_sub, transpose = T) ^ 2)\n }\n logdet <- 2.0 * sum(log(diag(L)))\n logml <- -0.5 * p1 - 0.5 * logdet - 0.5 * result$n * log(2*pi)\n if (verbose) {\n cat(c(\"l:\", l, \"b1:\", b1, \"b2:\", b2, \"logml:\",logml, \"\\n\"))\n }\n return(logml)\n}\n\n.gp.log.marginal.likelihood.optiml <- function(x, result, verbose) {\n return(.gp.log.marginal.likelihood(x, result$b1, result$b2, result, verbose))\n}\n.gp.log.marginal.likelihood.optimb1 <- function(x, result, verbose) {\n return(.gp.log.marginal.likelihood(result$l, x, result$b2, result, verbose))\n}\n\n.gp.cv.optimize2 <- function(par, result, verbose) {\n result$sigman <- par[2]\n .gp.cv.optimize(par[1], result, verbose)\n}\n\n.gp.cv.optimize <- function(l, result, verbose) {\n nfolds <- 5\n n <- result$n\n if (is.matrix(result$x)) {\n D <- ncol(result$x)\n } else {\n D <- 1\n }\n \n sse <- rep(NA, nfolds)\n for (fi in 1:nfolds) {\n foldsize <- n / nfolds\n test_ix <- (fi - 1) * foldsize + 1:foldsize\n #test_ix <- sample(n, foldsize)\n train_ix <- setdiff(1:n, test_ix)\n \n if (is.matrix(result$x)) {\n xtrain <- result$x[train_ix,]\n xtest <- result$x[test_ix,]\n } else {\n xtrain <- result$x[train_ix]\n xtest <- result$x[test_ix]\n }\n nt <- length(train_ix)\n K <- result$kernel(xtrain, xtrain, l)\n \n return_value <- try(L <- chol(K + result$sigman * diag(nt)), silent = !verbose)\n if (inherits(return_value, \"try-error\")) {\n return(Inf)\n }\n \n alpha <- backsolve(L, backsolve(L, result$p[train_ix], transpose = T))\n \n ntest <- length(test_ix)\n ktest <- result$kernel(xtest, xtrain, l)\n \n integral <- result$kernel.integral(alpha, l, D)\n f <- abs(integral) * (ktest %*% alpha)\n f[f < 0] <- 0\n diff <- result$p[test_ix] - f\n sse[fi] <- sum(diff ^ 2)\n if (integral < 0) {\n # Heavily penalize negative integrals\n #sse[fi] <- sse[fi] * 1e10\n }\n \n }\n rmse <- sqrt(sum(sse) / n)\n \n if (verbose) {\n cat(c(\"l:\", l, \"sigman:\", result$sigman, \"rmse:\", rmse, \"\\n\"))\n }\n \n return(rmse)\n}\n\n#' Fit a Gaussian process density function.\n#'\n#' Fit a Gaussian process through the posterior density samples. The GP can optionally be normalized such that the predictive function integrates to 1.\n#' The GP assumes a zero mean, and can use either a squared exponential or Matern-type covariance function. A single length scale parameter is used, which is\n#' optimized by minimizing the RMSE in 5-fold cross validation.\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param p Probability density at the sample locations; does not have to be normalized. Note that the probabilities should not be log transformed.\n#' @param kernel Which kernel to use, can be \"se\" or \"matern32\".\n#' @param l If optimize == TRUE, this should be a vector of size two with the lower and upper bound for the length scale; if optimize == FALSE, this is the fixed length scale.\n#' @param optimize Boolean specifying whether l (and possibly sigman) should be optimized.\n#' @param normalize Boolean specifying whether to normalize the GP such that it integrates to 1.\n#' @param sigman Can be either a fixed sigman or, if optimize == TRUE, this can also be a vector of size two specifying the lower and upper bound, and in this case sigman will be optimized along with l.\n#' @param verbose Display progress during the optimization of l.\n#' @export\nfit.gp <- function(x, p, kernel, l = 1.0, optimize = T, normalize = T, sigman = 1e-12, verbose = F) {\n result <- list()\n result$type <- \"gp\"\n\n if (is.matrix(x)) {\n result$n <- nrow(x)\n } else {\n result$n <- length(x)\n }\n\n result$kernel.name <- kernel\n if (kernel == \"squared.exponential\" || kernel == \"se\") {\n result$kernel <- .kernel.squared.exponential\n result$kernel.integral <- .kernel.se.integral\n } else if (kernel == \"matern32\") {\n result$kernel <- .kernel.matern32\n result$kernel.integral <- .kernel.matern32.integral\n }\n\n result$x <- x\n result$p <- p\n result$log <- FALSE\n\n if (optimize) {\n stopifnot(length(l) > 1)\n options <- nloptr::nl.opts(list(ftol_rel = 1e-6))\n if (length(sigman) > 1) { \n opt <- nloptr::sbplx(c(mean(l), mean(sigman)), .gp.cv.optimize2, c(l[1], sigman[1]), c(l[2], sigman[2]), result = result, verbose = verbose, control=options)\n result$l <- opt$par[1]\n result$sigman <- opt$par[2]\n } else {\n result$sigman <- sigman\n # opt <- optimize(.gp.cv.optimize, l, result = result, verbose = verbose)\n # result$l <- opt$minimum\n opt <- nloptr::sbplx(mean(l), .gp.cv.optimize, l[1], l[2], result = result, verbose = verbose, control=options)\n result$l <- opt$par[1]\n }\n } else {\n result$l <- l\n result$sigman <- sigman\n }\n\n result$kxx <- result$kernel(result$x, result$x, result$l) + result$sigman * diag(result$n)\n L <- chol(result$kxx)\n result$alpha <- backsolve(L, backsolve(L, p, transpose = TRUE))\n\n if (normalize) {\n if (is.matrix(result$x)) {\n D <- ncol(result$x)\n } else {\n D <- 1\n }\n integral <- result$kernel.integral(result$alpha, result$l, D)\n result$s <- 1.0 / integral\n } else {\n result$s <- 1.0\n }\n\n return(structure(result, class = \"mvd.density\"))\n}\n\n#' Evaluate a Gaussian process density function\n#'\n#' description\n#' @param fit mvd.density object\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @export\nevaluate.gp <- function(fit, x, log) {\n stopifnot(fit$type == \"gp\")\n\n if (log) {\n if (fit$log) {\n kxsx <- fit$kernel(x, fit$x, fit$l)\n f <- kxsx %*% fit$alpha\n return(fit$s * f)\n } else {\n kxsx <- fit$kernel(x, fit$x, fit$l)\n f <- kxsx %*% fit$alpha\n p <- abs(fit$s) * f\n p[p < 0] <- 0\n return(log(p))\n }\n } else {\n if (fit$log) {\n kxsx <- fit$kernel(x, fit$x, fit$l)\n f <- kxsx %*% fit$alpha\n return(exp(fit$s * f))\n } else {\n kxsx <- fit$kernel(x, fit$x, fit$l)\n f <- kxsx %*% fit$alpha\n p <- abs(fit$s) * f\n p[p < 0] <- 0\n return(p)\n }\n }\n}\n", "meta": {"hexsha": "f92f63c112bafebf4ed247877ff381383a41d447", "size": 8243, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gp.r", "max_stars_repo_name": "bramthijssen/mvdens", "max_stars_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/gp.r", "max_issues_repo_name": "bramthijssen/mvdens", "max_issues_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-21T12:45:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T12:45:03.000Z", "max_forks_repo_path": "R/gp.r", "max_forks_repo_name": "NKI-CCB/mvdens", "max_forks_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0739299611, "max_line_length": 202, "alphanum_fraction": 0.5701807594, "num_tokens": 2526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7424875114569544}} {"text": "# Author: Luis, Brent Ian\r\n# Lab Section: CMSC 150 B-5L\r\n# December 1, 2016\r\n\r\n# implements Simplex method\r\nSimplex <- function(matrix, numberOfRows, numberOfColumns){\r\n iterations = 0\r\n hasNegative = TRUE\r\n\r\n while(hasNegative){\r\n # selects the pivot column\r\n pivotColumn = 0 \r\n for(i in seq(1, numberOfColumns-1)) {\r\n if(matrix[numberOfRows, i] < 0){ # checks negative elements in the last row\r\n if(pivotColumn == 0){ \r\n pivotColumn = i\r\n } else if(matrix[numberOfRows, i] < matrix[numberOfRows, pivotColumn]){\r\n pivotColumn = i\r\n }# else if\r\n }# if\r\n }# for\r\n\r\n # selects the pivot row\r\n pivotRow = 0\r\n for(i in seq(1, numberOfRows-1)) {\r\n if(matrix[i, pivotColumn] > 0) {\r\n if(pivotRow == 0){\r\n pivotRow = i\r\n } else if(matrix[i, numberOfColumns] / matrix[i, pivotColumn] >= 0 && matrix[i, numberOfColumns] / matrix[i, pivotColumn] < matrix[pivotRow, numberOfColumns] / matrix[pivotRow, pivotColumn]){ # computes test ratio: solution column divided by the pivot column\r\n pivotRow = i\r\n }# else if\r\n }# if\r\n }# if\r\n \r\n # normalizes pivot row\r\n pivotElement = matrix[pivotRow, pivotColumn]\r\n matrix[pivotRow, ] = matrix[pivotRow, ] / pivotElement\r\n \r\n # implements Gauss-Jordan Elimination\r\n for(i in seq(1, numberOfRows)) {\r\n # retains only pivot row\r\n if(i != pivotRow){\r\n matrix[i, ] = matrix[i, ] - (matrix[pivotRow, ] * matrix[i, pivotColumn])\r\n }# if\r\n }# for\r\n \r\n # checks last row if it has negative\r\n hasNegative = FALSE\r\n for(i in matrix[numberOfRows, ]) {\r\n if(i < 0){\r\n hasNegative = TRUE\r\n } # if\r\n }# for\r\n\r\n # prints each iteration\r\n iterations = iterations + 1\r\n cat(\"Iteration: \", iterations, \"\\n\")\r\n print(matrix)\r\n }# while\r\n}# Simplex\r\n\r\n# initializes the main function\r\nMain <- function () {\r\n # reads input file as a matrix\r\n input <- read.csv(file=\"C:\\\\Users\\\\Brent Ian Luis\\\\Desktop\\\\luis_project\\\\test cases\\\\test case 1.csv\", header=TRUE, sep=\",\")\r\n matrix <- as.matrix(input)\r\n\r\n # gets matrix dimensions\r\n numberOfRows = nrow(matrix)\r\n numberOfColumns = ncol(matrix)\r\n \r\n # prints initial tableau\r\n cat(\"Initial Tableau:\\n\")\r\n print((matrix))\r\n\r\n Simplex(matrix, numberOfRows, numberOfColumns)\r\n}# Main", "meta": {"hexsha": "21047abf7327342e38bdf623a5be658a206f94ce", "size": 2360, "ext": "r", "lang": "R", "max_stars_repo_path": "simplex-method.r", "max_stars_repo_name": "brentianluis/simplex-method", "max_stars_repo_head_hexsha": "1171b101e7036ee46450439a9b95ceae6d5272a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simplex-method.r", "max_issues_repo_name": "brentianluis/simplex-method", "max_issues_repo_head_hexsha": "1171b101e7036ee46450439a9b95ceae6d5272a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simplex-method.r", "max_forks_repo_name": "brentianluis/simplex-method", "max_forks_repo_head_hexsha": "1171b101e7036ee46450439a9b95ceae6d5272a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6493506494, "max_line_length": 267, "alphanum_fraction": 0.6025423729, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7424525290840239}} {"text": "#----------------------------------------------------------------------#\r\n# Function to calculate Fisher's Classification coefficients #\r\n# This code follows the formulas in Legendre and Legendre's Numerical Ecology (1998) #\r\n#----------------------------------------------------------------------#\r\nclassfunc.lda <- function(x, groups){\r\n x.lda <- lda(groups ~ ., as.data.frame(x))\r\n\r\n gr <- length(unique(groups)) ## groups might be factors or numeric\r\n v <- ncol(x) ## variables\r\n m <- x.lda$means ## group means\r\n\r\n w <- array(NA, dim = c(v, v, gr))\r\n\r\n tot.len <- nrow(x)\r\n subgr.len <- array(0, gr)\r\n\r\n for(i in 1:gr){\r\n tmp <- scale(subset(x, groups == unique(groups)[i]), scale = FALSE)\r\n w[,,i] <- t(tmp) %*% tmp\r\n subgr.len[i] <- nrow(tmp)\r\n }\r\n\r\n W <- w[,,1]\r\n for(i in 2:gr)\r\n W <- W + w[,,i]\r\n\r\n V <- W/(nrow(x) - gr)\r\n iV <- solve(V)\r\n\r\n class.func <- matrix(NA, nrow = v + 1, ncol = gr)\r\n\r\n colnames(class.func) <- rownames(m)\r\n rownames(class.func) <- c(\"constant\", colnames(m) )\r\n\r\n for(i in 1:gr) {\r\n ni <- subgr.len[i]\r\n class.func[1, i] <- -0.5 * t(m[i,]) %*% iV %*% (m[i,]) + log(ni / tot.len)\r\n class.func[2:(v+1) ,i] <- iV %*% (m[i,])\r\n }\r\n\r\n x.lda$class.func <- class.func\r\n\r\n return(x.lda)\r\n} \r\n", "meta": {"hexsha": "0f69533d3cf738fbe90f05d59516b48c5755ffab", "size": 1308, "ext": "r", "lang": "R", "max_stars_repo_path": "R.2020.1/mva/classFunc.r", "max_stars_repo_name": "tolkien/misc", "max_stars_repo_head_hexsha": "84651346a3a0053b6a2af31db26c227a34da33c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R.2020.1/mva/classFunc.r", "max_issues_repo_name": "tolkien/misc", "max_issues_repo_head_hexsha": "84651346a3a0053b6a2af31db26c227a34da33c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R.2020.1/mva/classFunc.r", "max_forks_repo_name": "tolkien/misc", "max_forks_repo_head_hexsha": "84651346a3a0053b6a2af31db26c227a34da33c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0666666667, "max_line_length": 89, "alphanum_fraction": 0.4587155963, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7423275887478318}} {"text": "=begin\n[(())] \n= Algebra::EuclidianRing\n\n((*(G.C.D.計算モジュール)*))\n\n((|divmod|)) から G.C.D(最大公約数)等を計算するモジュールです。\nこれは ((|Integer|)) や ((|Algebra::Polynomial|)) にインクルードされます。\n\n== ファイル名:\n* ((|euclidian-ring.rb|))\n\n== メソッド:\n\n--- gcd(other)\n ((|self|)) と ((|other|)) との最大公約数を返します。\n\n--- gcd_all(other0 [, other1[, ...]])\n ((|self|)) と ((|other0|)), ((|other1|)),... との最大公約数を返します。\n\n--- gcd_coeff(other)\n ((|self|)) と ((|other|)) との最大公約数と、それを表現する係数の\n 配列を返します。\n \n 例:\n require \"polynomial\"\n require \"rational\"\n P = Algebra.Polynomial(Rational, \"x\")\n x = P.var\n f = (x + 2) * (x**2 - 1)**2\n g = (x + 2)**2 * (x - 1)**3\n gcd, a, b = f.gcd_coeff(g)\n p gcd #=> 4x^3 - 12x + 8\n p a #=> -x + 2\n p b #=> x - 1\n p gcd == a*f + b*g #=> true\n\n--- gcd_ext(other)\n (()) と同じです。\n\n--- gcd_coeff_all(other0 [, other1[, ...]])\n ((|self|)) と ((|other0|)), ((|other1|)),... との最大公約数と、それ\n を表現する係数の配列を返します。\n\n 例:\n require \"polynomial\"\n require \"rational\"\n P = Algebra.Polynomial(Rational, \"x\")\n x = P.var\n f = (x + 2) * (x**2 - 1)**2\n g = (x + 2)**2 * (x - 1)**3\n h = (x + 2) * (x + 1) * (x - 1)\n gcd, a, b, c = f.gcd_coeff_all(g, h)\n p gcd #=> -8x^2 - 8x + 16\n p a #=> -x + 2\n p b #=> x - 1\n p c #=> -4\n p gcd == a*f + b*g + c*h #=> true\n\n--- gcd_ext_all(other)\n (()) と同じです。\n\n--- lcm(b)\n ((|self|)) と ((|other|)) との最小公倍数を返します。\n\n--- lcm_all(other0 [, other1[, ...]])\n ((|self|)) と ((|other0|)), ((|other1|)),... との最小公倍数を返します。\n\n=end\n", "meta": {"hexsha": "0a8462ea540e566c342fdabe65111f358672a78c", "size": 1615, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/euclidian-ring-ja.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "doc-ja/euclidian-ring-ja.rd", "max_issues_repo_name": "kunishi/algebra-ruby2", "max_issues_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc-ja/euclidian-ring-ja.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0714285714, "max_line_length": 61, "alphanum_fraction": 0.4637770898, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.742294855303332}} {"text": "tanident_1( 1*atan(1/2) + 1*atan(1/3) )\n## [1] TRUE\ntanident_1( 2*atan(1/3) + 1*atan(1/7))\n## [1] TRUE\ntanident_1( 4*atan(1/5) + -1*atan(1/239))\n## [1] TRUE\ntanident_1( 5*atan(1/7) + 2*atan(3/79))\n## [1] TRUE\ntanident_1( 5*atan(29/278) + 7*atan(3/79))\n## [1] TRUE\ntanident_1( 1*atan(1/2) + 1*atan(1/5) + 1*atan(1/8) )\n## [1] TRUE\ntanident_1( 4*atan(1/5) + -1*atan(1/70) + 1*atan(1/99) )\n## [1] TRUE\ntanident_1( 5*atan(1/7) + 4*atan(1/53) + 2*atan(1/4443))\n## [1] TRUE\ntanident_1( 6*atan(1/8) + 2*atan(1/57) + 1*atan(1/239))\n## [1] TRUE\ntanident_1( 8*atan(1/10) + -1*atan(1/239) + -4*atan(1/515))\n## [1] TRUE\ntanident_1(12*atan(1/18) + 8*atan(1/57) + -5*atan(1/239))\n## [1] TRUE\ntanident_1(16*atan(1/21) + 3*atan(1/239) + 4*atan(3/1042))\n## [1] TRUE\ntanident_1(22*atan(1/28) + 2*atan(1/443) + -5*atan(1/1393) + -10*atan(1/11018))\n## [1] TRUE\ntanident_1(22*atan(1/38) + 17*atan(7/601) + 10*atan(7/8149))\n## [1] TRUE\ntanident_1(44*atan(1/57) + 7*atan(1/239) + -12*atan(1/682) + 24*atan(1/12943))\n## [1] TRUE\ntanident_1(88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12943))\n## [1] TRUE\ntanident_1(88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12944))\n## [1] FALSE\n", "meta": {"hexsha": "078d9e48350fd2b9e081cb9df8cf65daca832acc", "size": 1303, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Check-Machin-like-formulas/R/check-machin-like-formulas-2.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Check-Machin-like-formulas/R/check-machin-like-formulas-2.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Check-Machin-like-formulas/R/check-machin-like-formulas-2.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2285714286, "max_line_length": 101, "alphanum_fraction": 0.5541059094, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7419586889790917}} {"text": "#Generate the sets\na = runif(10,min=0,max=1)\nb = runif(100,min=0,max=1)\nc = runif(1000,min=0,max=1)\nd = runif(10000,min=0,max=1)\n\n#Print out the set of 10 values\ncat(\"a = \",a)\n\n#Print out the Mean and Standard Deviations of each of the sets\ncat(\"Mean of a : \",mean(a))\ncat(\"Standard Deviation of a : \", sd(a))\ncat(\"Mean of b : \",mean(b))\ncat(\"Standard Deviation of b : \", sd(b))\ncat(\"Mean of c : \",mean(c))\ncat(\"Standard Deviation of c : \", sd(c))\ncat(\"Mean of d : \",mean(d))\ncat(\"Standard Deviation of d : \", sd(d))\n\n#Plotting the histogram of d\nhist(d)\n\n#Following lines error out due to insufficient memory\n\ncat(\"Mean of a trillion random values in the range [0,1] : \",mean(runif(10^12,min=0,max=1)))\ncat(\"Standard Deviation of a trillion random values in the range [0,1] : \", sd(runif(10^12,min=0,max=1)))\n", "meta": {"hexsha": "451112ed8398376fdf13cda188572e7c3b83f955", "size": 810, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Statistics-Basic/R/statistics-basic.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Statistics-Basic/R/statistics-basic.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Statistics-Basic/R/statistics-basic.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0, "max_line_length": 105, "alphanum_fraction": 0.6654320988, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7419140303845215}} {"text": "closest.pairs.bruteforce <- function(x, y=NULL)\n{\n\tif (!is.null(y))\n\t{\n\t\tx <- cbind(x,y)\n\t}\n\td <- dist(x)\n\tcp <- x[combn(1:nrow(x), 2)[, which.min(d)],]\n\tlist(p1=cp[1,], p2=cp[2,], d=min(d))\n}\n\nclosest.pairs.dandc <- function(x, y=NULL)\n{\n\tif (!is.null(y))\n\t{\n\t\tx <- cbind(x,y)\n\t}\n\tif (sd(x[,\"x\"]) < sd(x[,\"y\"]))\n\t{\n\t\tx <- cbind(x=x[,\"y\"],y=x[,\"x\"])\n\t\tswap <- TRUE\n\t}\n\telse\n\t{\n\t\tswap <- FALSE\n\t}\n\txp <- x[order(x[,\"x\"]),]\n\t.cpdandc.rec <- function(xp,yp)\n\t{\n\t\tn <- dim(xp)[1]\n\t\tif (n <= 4)\n\t\t{\n\t\t\tclosest.pairs.bruteforce(xp)\n\t\t}\n\t\telse\n\t\t{\n\t\t\txl <- xp[1:floor(n/2),]\n\t\t\txr <- xp[(floor(n/2)+1):n,]\n\t\t\tcpl <- .cpdandc.rec(xl)\n\t\t\tcpr <- .cpdandc.rec(xr)\n\t\t\tif (cpl$d 1)\n\t{\n\t\tfor (i in 1:(nys-1))\n\t\t{\n\t\t\tk <- i + 1\n\t\t\twhile (k <= nys && ys[i,\"y\"] - ys[k,\"y\"] < cp$d)\n\t\t\t{\n\t\t\t\td <- sqrt((ys[k,\"x\"]-ys[i,\"x\"])^2 + (ys[k,\"y\"]-ys[i,\"y\"])^2)\n\t\t\t\tif (d < cp$d) cp <- list(p1=ys[i,],p2=ys[k,],d=d)\n\t\t\t\tk <- k + 1\n\t\t\t}\n\t\t}\n\t}\n\tif (swap)\n\t{\n\t\tlist(p1=cbind(x=cp$p1[\"y\"],y=cp$p1[\"x\"]),p2=cbind(x=cp$p2[\"y\"],y=cp$p2[\"x\"]),d=cp$d)\n\t}\n\telse\n\t{\n\t\tcp\n\t}\n}\n\n# Test functions\ncat(\"How many points?\\n\")\nn <- scan(what=integer(),n=1)\nx <- rnorm(n)\ny <- rnorm(n)\ntstart <- proc.time()[3]\ncat(\"Closest pairs divide and conquer:\\n\")\nprint(cp <- closest.pairs.dandc(x,y))\ncat(sprintf(\"That took %.2f seconds.\\n\",proc.time()[3] - tstart))\nplot(x,y)\npoints(c(cp$p1[\"x\"],cp$p2[\"x\"]),c(cp$p1[\"y\"],cp$p2[\"y\"]),col=\"red\")\ntstart <- proc.time()[3]\ncat(\"\\nClosest pairs brute force:\\n\")\nprint(closest.pairs.bruteforce(x,y))\ncat(sprintf(\"That took %.2f seconds.\\n\",proc.time()[3] - tstart))\n", "meta": {"hexsha": "ae75a18e5690a86702b3b4a57c5a34a5743b606f", "size": 1782, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Closest-pair-problem/R/closest-pair-problem-5.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Closest-pair-problem/R/closest-pair-problem-5.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Closest-pair-problem/R/closest-pair-problem-5.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 20.0224719101, "max_line_length": 86, "alphanum_fraction": 0.507295174, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7419022712566813}} {"text": "#биномно разпределение - n независими опита с вероятност за успех на всеки p и за провал 1-p=q\n#dbinom - Р(X = x)\nx <- seq(0,50,by=1) \ny <- dbinom(x = x, size = 50, prob = 0.2) #вероятността да имаш x успешни опита от общо size опита с вероятност за усех prob\nplot(x,y)\ny <- dbinom(x = x, size = 50,prob = 0.5)\nplot(x,y)\n\n#pbinom - P(X <= x)\npbinom(q = 24, size = 50, prob = 0.5) #вероятността да имаш по-малко или равно на q успеха от общо size опита с вероятност за усех prob\npbinom(q = 25, size = 50, prob = 0.5, lower.tail = FALSE) #P(X>x) -> вероятността да имаш повече от q успеха от общо size опита с вероятност за усех prob\n\n#qbinom - по зададена вероятност намира колко успеха от size опита с вероятност за успех prob е имало (обратното на dbinom) \nqbinom(p = 0.4438624,size = 50, prob = 1/2)\nqbinom(p = 0.5561376,size = 50, prob = 0.5)\n\n#rbinom за генериране на n случайно разпределени величини от 0 до size с вероятноса за успех prob \nrbinom(n = 5, size = 10, prob = 0.2)\nrbinom(n = 5, size = 100,prob = 0.2)\n\n\n#отрицателно биномно разпределение - колко неусеха да получаване на фиксиран брй успехи \n#dnbinom - вероятността да има x неуспеха да получаването на size-тия успех с вероятност за успех prob\ndnbinom(x = c(1:10), size = 5, prob = 0.5) \n\n#pnbinom \npnbinom(q = 8, size = 3, prob = 0.2) #вероятността да има по-малко или равно на q неуспеха дo получаването на size-тия успех с вероятност за успех prob\npnbinom(q = 8, size = 3, prob = 0.2, lower.tail = FALSE) #повече от q неуспеха до получаването на size-тия успех с вероятност за успех prob\n\n#qnbinom и rnbinom аналогични на qbinom и rbinom\n\n\n#Хипергеометрично разпределение - N обекта, M от тях са маркирани, по случаен начин избираме n на брой. X - броят на маркираните, измежду тези които сме избрали случайно\n#функцията hyper() с префикси d,p,q,r за съответно плътност, разпределние, квантил и случайно разпределение(симулиране)\nsuccess=c(0:6)\ndhyper(x = success, m = 6, n = 30, k = 6)\n\n#Поасоново разпределение - биномно разпределение, което има много малка вероятност\n#n->inf, p->0, np = lamda\n#Функция pois() c префикси d,p,q,r за съответно плътност, разпределние, квантил и случайно разпределение(симулиране)\nppois(q = 16, lambda = 12)\n\n\n#-----------------------------------------------------\n\n#01\n#биномно разпределение n=79, k=29, p=1/2\nresult = choose(79,29) * 1/(2^29) * 1/(2^50) #choose смята биномен коефициент\nresult.binom = dbinom(x = 29, size = 79, prob = 1/2)\n\n#02\nnot.fixed = pbinom(q = 2, size = c(3,4,5,7,8), prob = 1/2) #по-малко или равно на size опита за изтегляне на 2 езита\nfixed = dbinom(x = 2, size = c(3,4,5,7,8), prob = 1/2) #точно size опита за изтегляне на 2 езита\n\nplot(x= c(3,4,5,7,8), y = not.fixed, type = \"l\", main = \"Dstribution of two ezi\", xlab = \"Number of tries\", ylab = \"Probability\")\nlines(x= c(3,4,5,7,8), y = fixed, type = \"p\", col = \"red\")\n\n#03\n#оцелването на тройка е биномно разпределена случайна величина с вероятност за успех p = 0.7\nn = qbinom(p = 1 - 0.18522, size = 3, prob = 0.7 ) + 3 #???\n\nx = qbinom(p = 0.18522, size = c(3:10), prob = 0.7 ) #с вероятност 0.18522 проверяваме от 3 до няколко(10) опита на кой опит ще е уцелил три пъти\nnames(x) = c(3:10)\nresult = as.numeric(names(x[x == 3])) \n# => на 5-ти и 6-ти опит ще е оцелил три тройки с вероятност 0.18522\n\n#04\n#вероятността да има <=35 жени в извадка от k = 100 човека, като жените са m = 40% от 600000 човека, а мъжете са n = 60% от 600000 човека\ntheoretical = phyper(q = 35, m = 0.4*600000, n = 0.6*600000, k = 100)\npop = rep(c(0,1),c(360000, 240000)) #симулираме 600000 човека -> 360000 нули за мъжете и 240000 единици за жените\nres=sapply(c(0:1000), function(x) sum(sample(pop,100))) # 1000 елементен вектор с резултатите за общия брой жени в случайна извадка от 100 човека\nempirical = sum(res<=35)/100\n\n#05\n#поасоново разпределение с ламда = 2 обаждания за минута\n# => поасоново разпределенеи с ламда = 2*5 = 10 обаждания за 5 минути\nexactly.2 = dpois(x = 2, lambda = 10) # P(X = 2)\nless.than.2 = ppois(q = 1, lambda = 10) # P(X <= 1) = P(X < 2)\nmore.than.2 = ppois(q = 1, lambda = 10, lower.tail = FALSE) # P(X > 1) = P(X >= 2)\n\n#06\n#отрицателно биномно разпределение с вероятност за успех 4/52 (4 аса от 52 карти)\n#търсим вероятността за 4 провала до първия успех => 5-тата изтеглена карта е асо\ndnbinom(x = 4, size = 1, prob = 4/52)\ndgeom(x = 4, prob = 4/52)\n", "meta": {"hexsha": "2619413dee85f0c55e032bf5397fa96c27ebf6c0", "size": 4352, "ext": "r", "lang": "R", "max_stars_repo_path": "week5-6.r", "max_stars_repo_name": "StelaN/Statistics-R", "max_stars_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-17T10:22:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-17T10:22:32.000Z", "max_issues_repo_path": "week5-6.r", "max_issues_repo_name": "StelaN/Statistics-R", "max_issues_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week5-6.r", "max_forks_repo_name": "StelaN/Statistics-R", "max_forks_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-06T13:38:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-06T13:38:34.000Z", "avg_line_length": 50.6046511628, "max_line_length": 169, "alphanum_fraction": 0.6829044118, "num_tokens": 2069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142217223021, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7418841814302344}} {"text": "# ......................................................................................\n# ..............................Exercise 4 - Random vector..............................\n# he content of this script is only as a supplementary illustration to the exercise, it is not necessary to know at the exam. It is important to be able to calculate manually.**\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# Example ####\n# \n# Random vector $Z =(Y;X)^T$ has a probability function specified by the table
\n# ![Image.png](attachment:image.png)\n# \n# * a) Determine the missing value of the combined probability function, ####\n# \n\n\ndata = c(0.01, 0.04, 0.12, \n 0.02, 0.16, 0.07, \n 0.03, 0, 0.06, \n 0.25, 0.05, 0.01)\nP = matrix(data , nrow=3, ncol=4) # possibly byrow=...\nX = c(3, 5, 7)\nY = c(1, 2, 3, 4)\ndimnames(P) = list(X,Y)\nP\n\nsum(P)\n\n# do not run this cell twice, otherwise you will set the value back to 0,\n# Do you know why?\np_5_3 = 1 - sum(P)\nP[\"5\",\"3\"] = p_5_3\nP\n\n# * b) Specify the distribution function ####\n# \n# **Attention! The vector Z is $(Y,X)^T$ so the first parameter is the value Y and the\n# second value X.**\n# \n\n\n# F(2.8; 7.1)\n# P(Y<2.8, X<7.1)\nP[X<7.1, Y<2.8]\nsum(P[X<7.1, Y<2.8])\n\nF = matrix(rep(0,4*5), nrow=4, ncol=5)\ndimnames(F) = list(c('(-inf,3>', '(3,5>', '(5,7>', '(7,inf)'),\n c('(-inf,1>', '(1,2>', '(2,3>', '(3,4>', '(4,inf)'))\nF\n\n# we go through the rows and columns, we always take one value\n# from the relevant row or column\nx_vals = c(3,5,7,8)\ny_vals = c(1,2,3,4,5)\nfor(i in 1:4){\n for(j in 1:5){\n x = x_vals[i]\n y = y_vals[j]\n F[i,j] = sum(P[X2.1|X<5.3)\n# P(Y>2.1 ∧ X<5.3)/P(X<5.3)\nsum(P[X<5.3, Y>2.1])\nsum(P[X<5.3,])\nsum(P[X<5.3, Y>2.1])/sum(P[X<5.3,])\n\n# P(X=5|Y=1)\n# P(X=5 ∧ Y=1)/P(Y=1)\nP['5','1']/sum(P[,'1'])\nP['5','1']/sum(P_y['1'])\n\n# **$P(x|y)=\\frac{P(X=x,Y=y)}{P_Y(y)}$**\n# \n\n\nP_xy = P # it's the same size, so we'll steal the formatting\nX_lab = c('3', '5', '7')\nY_lab = c('1', '2', '3', '4')\nfor(x in X_lab){\n for(y in Y_lab){\n P_xy[x, y] = P[x, y]/P_y[y]\n }\n}\nP_xy\ncolSums(P_xy)\n\n# **$P(y|x)$**\n# \n\n\nP_yx = P # it's the same size, so we'll steal the formatting\nfor(x in X_lab){\n for(y in Y_lab){\n P_yx[x, y] = P[x, y]/P_x[x]\n }\n}\nP_yx\nrowSums(P_yx)\n\n# * e) basic characteristics of random variables X and Y ####\n# \n\n\nE_X = sum(X*P_x)\nE_X\nE_XX = sum(X*X*P_x)\nD_X = E_XX - E_X^2\nD_X\n\nE_Y = sum(Y*P_y)\nE_Y\nE_YY = sum(Y*Y*P_y)\nD_Y = E_YY - E_Y^2\nD_Y\n\n# * f) conditional mean E(X|Y=2) ####\n# \n\n\n# P(x|Y=2)\nP_xy[,'2']\nE_X_Y2 = sum(X*P_xy[,'2'])\nE_X_Y2\n\n# * g) covariance and correlation ####\n# \n\n\nX_Y = P # matrix where in each column is the value x * y\nfor(x in X){\n for(y in Y){\n X_Y[toString(x), toString(y)] = x*y \n }\n}\nX_Y\n\n# or we can use matrix multiplication \nX %*% t(Y)\n\n# mean value of E(X * Y)\nE_XY = sum(X_Y*P)\nE_XY\n\n# covariance\ncov_XY = E_XY-E_X*E_Y\ncov_XY\n\n# correlation\ncov_XY/sqrt(D_X*D_Y)\n\n\n\n", "meta": {"hexsha": "ed3be460126dbbe0101f6ffbd9ed97d350515ce6", "size": 3513, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 4/T6_random_vector.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise 4/T6_random_vector.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise 4/T6_random_vector.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 19.625698324, "max_line_length": 177, "alphanum_fraction": 0.5246228295, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7418225972415413}} {"text": "func <- function(x,y)\r\n{\r\n func1 <- (-5*y) + 5*x^2 + 2*x\r\n}\r\n\r\n\r\nEuler <- function (x0, y0, h, n )\r\n{\r\n x <- x0\r\n y <- y0\r\n \r\n for ( i in 1 : n )\r\n {\r\n y0 <- y0 + h * func ( x0, y0 )\r\n x0 <- x0 + h\r\n x <- c ( x, x0 )\r\n y <- c ( y, y0 )\r\n }\r\n \r\n return ( data.frame ( x = x, y = y ) )\r\n}\r\n\r\n\r\nEuler(0, 1/3, 0.1 ,10)", "meta": {"hexsha": "ea397a680ea34d39f042698793a151e4fec596d5", "size": 335, "ext": "r", "lang": "R", "max_stars_repo_path": "Lab-09/Lab-09(Task 1).r", "max_stars_repo_name": "hassaninamdar/legendesk", "max_stars_repo_head_hexsha": "f0487ac60167de97570bbe4d816cf434d1df6e39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab-09/Lab-09(Task 1).r", "max_issues_repo_name": "hassaninamdar/legendesk", "max_issues_repo_head_hexsha": "f0487ac60167de97570bbe4d816cf434d1df6e39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab-09/Lab-09(Task 1).r", "max_forks_repo_name": "hassaninamdar/legendesk", "max_forks_repo_head_hexsha": "f0487ac60167de97570bbe4d816cf434d1df6e39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9583333333, "max_line_length": 41, "alphanum_fraction": 0.352238806, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7417169455281156}} {"text": "#' @title calcCbw\n#'\n#' @description Calculates the waterline block coefficient (\\code{Cbw})\n#' (dimensionless) using actual draft.\n#'\n#' @param Cb Maximum block coefficient (vector of numericals, dimensionless)\n#' (see \\code{\\link{calcCb}})\n#' @param actualDraft Actual draft (vector of numericals, m)\n#' @param maxDraft Maximum summer load line draft (vector of numericals, m)\n#'\n#' @details\n#' The block coefficient is the ratio of the vessel's displacement and its\n#' volume, defined by its waterline length (\\code{lwl}), breadth, and draft:\n#' \\deqn{Cb=\\frac{displacement}{lwl*breadth*draft}}{Cb=displacement/(lwl*breadth*draft)}\n#'\n#' This function returns the waterline block coefficient (\\code{Cbw}), which\n#' represents a loaded condition estimation using actual draft using the\n#' Riddlesworth method. Actual draft is typically obtained from sources such as\n#' AIS messages or ship records.\n#'\n#' NOTE: Technically, no block coefficient can be greater than 1. Even a\n#' waterline block coefficient of 1 itself is extremely improbable and can cause\n#' numerical errors elsewhere in the model. Therefore, the upper bound of the\n#' waterline block coefficient is fixed at 0.99 in this function.\n#'\n#' @return \\code{Cbw} (vector of numericals, dimensionless)\n#'\n#' @references\n#'\\href{https://www.man-es.com/marine/products/propeller-aft-ship}{MAN Energy\n#' Solutions. 2011. \"Basic Principles of Propulsion.\"}\n#'\n#' @seealso \\code{\\link{calcCb}}\n#'\n#' @examples\n#' calcCbw(c(0.82,0.66),c(12.48,11.09),c(13.57,11.49))\n#' calcCbw(0.82,12.48,13.57)\n#'\n#' @export\n\ncalcCbw <- function(Cb,actualDraft,maxDraft){\n\n\n #ensure that: actualDraft < maxDraft\n actualDraft<-pmin(actualDraft,\n maxDraft)\n\n Cbw<- pmin(0.99,\n 1-(1-pmin(0.99,\n Cb\n )\n )*((maxDraft/actualDraft)^(1/3))\n )\n return(Cbw)\n}\n", "meta": {"hexsha": "7df4b61929944355efb0021a285e1755ad856177", "size": 1888, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcCbw.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipPowerModel/R/calcCbw.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipPowerModel/R/calcCbw.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 34.3272727273, "max_line_length": 88, "alphanum_fraction": 0.6859110169, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7416895383359395}} {"text": "#\n# University: Universidad de Valladolid\n# Degree: Grado en Estadística\n# Subject: Análisis de Datos\n# Year: 2017/18\n# Teacher: Miguel Alejandro Fernández Temprano\n# Author: Sergio García Prado (garciparedes.me)\n# Name: Análisis de Componentes Principales - Práctica 02\n#\n#\n\nrm(list = ls())\n\nlibrary(ggplot2)\nlibrary(MASS)\n\n#\n# 1)\n# Importar los datos a SAS desde el fichero Olympic2016 v2.txt;\n#\n\nDATA <- read.csv('./../../../datasets/olympic-2016-v2.txt', header=TRUE)\n\nA <- DATA[,1:10]\nrownames(A) <- DATA[,12]\n\n#\n# 2)\n# Efectuar mediante un ACP normado con los datos de las 10 pruebas.\n#\n\n\nX <- t((t(A) - colMeans(A)) / apply(A, 2, sd))\nX_n <- dim(X)[1]\nX_p <- dim(X)[2]\n\nX_star <- (t(X) %*% X) / (X_n-1)\n\nX_eig <- eigen(X_star)\nX_lambda <- X_eig$values\nX_u <- X_eig$vectors\n\n#\n# 3)\n# Calcular los scores en las 10 componentes y comprobar que tienen media 0\n# y varianza igual al autovalor correspondiente.\n#\n\n\nF <- X %*% X_u\n\nggplot(as.data.frame.matrix(F), aes(x=V1, y=V2)) +\n geom_point() +\n geom_text(label=rownames(F))\n\n\n0 == round(colMeans(F), digits=4)\nround(X_lambda, digits=4) == round(apply(F, 2, sd) ^ 2, digits=4)\nsum(X_lambda)\n\n#\n# 4)\n# Calcular las contribuciones absolutas y relativas de los puntos a las\n# componentes y hacer la representación gráfica correspondiente.\n#\n\n\nX_ca <- t(t(F^2) / rowSums(t(F ^ 2)))\nX_re <- (F^2) / rowSums(F ^ 2)\n\nprint(round(X_ca, digits = 4))\nprint(round(X_re, digits = 4))\n\n#\n# 5)\n# Considerar ahora la nube de los puntos columna y calcular los autovalores y\n# autovectores correspondientes. Comprobar las relaciones con los resultados\n# de la nube de puntos fila.\n#\n\nX_v <- t(t(F) / sqrt(X_lambda * (X_n - 1)))\n\nprint(round(X_v, digits = 4))\n\nG <- t(X) %*% X_v\n\nprint(G)\n\nX_u_2 <- t(t(G) / sqrt(X_lambda * (X_n - 1)))\n\n\nround(X_u_2, digits = 4) == round(X_u, digits = 4)\n\n\nggplot(as.data.frame.matrix(G), aes(x=V1, y=V2)) +\n geom_point() +\n geom_text(label=rownames(G))\n\n#\n# 6)\n# Calcular las proyecciones de las variables (scores) en los nuevos ejes.\n# Calcular sus medias, sus varianzas y la suma de sus cuadrados (dividida por n-1).\n#\n\n# Medias (nada)\nround(colMeans(G), digits=4)\n\n# Varianzas (Nada)\nround(apply(G, 2, sd) ^ 2, digits=4)\n\n# Suma de cuadrados dividida entre n-1 (lambdas o autovalores)\nround(colSums(G^2)/(X_n -1), digits=4)\n\n#\n# 7)\n# Reconstruir la matriz de datos original a partir de los autovalores y\n# autovectores.\n#\n\n# Reconstrucción de la matriz de covarianzas\nX_u %*% diag(X_lambda) %*% ginv(X_u)\n\n# Reconstrucción de la matriz de datos\nX\n(X_v %*% diag(sqrt(X_lambda * (X_n -1))) %*% t(X_u))\n\n#\n# 8)\n# Reconstruir la matriz con las dos primeras componentes principales y valorar\n# la pérdida.\n#\n\n# Ratio de distorsión por la reducción de dimensiones\n1-sum(X_lambda[1:2]) / sum(X_lambda)\n\n# Reconstrucción de la matriz de covarianzas\nX_u[,1:2] %*% diag(X_lambda[1:2]) %*% ginv(X_u[,1:2])\n\n# Reconstrucción de la matriz de datos\nX_v[,1:2] %*% diag(sqrt(X_lambda[1:2] * (X_n -1))) %*% t(X_u[,1:2])\n", "meta": {"hexsha": "06232917ad9727d4779606e43242210e52fa787e", "size": 2982, "ext": "r", "lang": "R", "max_stars_repo_path": "data-analysis/principal-component-analysis/practice-02/practice-02.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "data-analysis/principal-component-analysis/practice-02/practice-02.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "data-analysis/principal-component-analysis/practice-02/practice-02.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1489361702, "max_line_length": 83, "alphanum_fraction": 0.672702884, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.7905303211371899, "lm_q1q2_score": 0.7416154728020997}} {"text": "\r\n# Examples 07 EM Algorithm\r\n# ------------------------\r\n\r\n\r\n# MLE\r\n# ---\r\n\r\n# This script estimates the allelic freq from genotype freq\r\n# using Maximum Likelihood Estimation\r\n\r\nnAA<-12\r\nnAB<-35\r\nnA0<-21\r\nnBB<-15\r\nnB0<-30\r\nn00<-9\r\nn<-nAA+nAB+nA0+nBB+nB0+n00 \r\n\r\np<-(nAA+nA0/2+nAB/2)/n\r\nq<-(nBB+nB0/2+nAB/2)/n\r\nr<-(n00+nA0/2+nB0/2)/n\r\np;q;r\r\n\r\n\r\n# EM Algorithm\r\n# ------------\r\n\r\n# This script estimates the allelic freq from phenotype freq\r\n# using EM Algorithm\r\n\r\nnA<-33 # nAA and nA0 unknown: nA=nAA+nA0\r\nnB<-45 # nBB and nB0 unknown: nB=nBB+nB0\r\nnAB<-35 # nAB known\r\nn0<-9 # n00=n0 known\r\n\r\nn<-nA+nB+nAB+n0\r\n\r\n# STEP 1\r\n\r\n# Parameters' vector par=(p,q). Note that r=1-p-q\r\n\r\n# HYP 1 - Uniform Distribution\r\np<-1/3\r\nq<-1/3\r\nr<-1/3\r\n\r\n# HYP 2 - Bernstein\r\np<-1-sqrt((n0+nB)/n)\r\nq<-1-sqrt((n0+nA)/n)\r\nr<-sqrt(n0/n)\r\np;q;r\r\n\r\n# STEP 2 (E)\r\n\r\n# Calculate approximate values for nAA, nA0, nBB, nB0\r\nexpected<-function(p,q,r){\r\nnAA<-nA*p/(p+2*r)\r\nnA0<-nA*2*r/(p+2*r)\r\nnBB<-nB*q/(q+2*r)\r\nnB0<-nB*2*r/(q+2*r)\r\nc(nAA,nA0,nBB,nB0)\r\n}\r\nexpected(p,q,r)\r\n\r\n# STEP 3 (M) \r\n\r\n# Update p, q and r\r\nparam<-function(nAA,nA0,nBB,nB0){\r\np<-(2*nAA+nA0+nAB)/(2*n)\r\nq<-(2*nBB+nB0+nAB)/(2*n)\r\nr<-(2*n0+nA0+nB0)/(2*n)\r\nc(p,q,r)\r\n}\r\nparam(nAA,nA0,nBB,nB0)\r\n\r\n# STEP 4 e 5\r\n\r\n# EM ALGORITHM - iterative procedure\r\n\r\ni<-0\r\ner<-1\r\nerro<-10^(-5)\r\n\r\nwhile(sum(er>=erro)>0)\r\n{\r\n # Step E\r\n e<-expected(p,q,r)\r\n # Step M\r\n par<-param(e[1],e[2],e[3],e[4])\r\n # STOP criteria\r\n er<-abs(c(p,q,r)-c(par[1],par[2],par[3]))\r\n i<-i+1\r\n p<-par[1]; q<-par[2]; r<-par[3]\r\n cat(i,p,q,r,\"\\n\") # print all the values obtained in each iterate.\r\n}\r\n\r\ncat(\"\\nObtained solution after \",i,\" iterations:\\n\r\np* =\",p,\r\n\"\\nq* =\",q,\r\n\"\\nr* =\",r,\"\\n\")\r\n\r\n\r\n# Example of Application - nudge\r\n# ------------------------------\r\n\r\n# Download the datafiles from the web\r\n\r\n# http://bioinf.wehi.edu.au/limma/\r\n# go to the end of the webpage\r\n# download the Zebrafish data - zip.file\r\n# working directory - swirl\r\n# Chip: 4x4 blocks, 22 rows and 24 col, each\r\n\r\n# Change directory to folder 'Swirl'\r\n# install and load package limma in order to read the data\r\nsource(\"http://bioconductor.org/biocLite.R\")\r\nbiocLite(\"limma\")\r\nlibrary(limma)\r\n\r\n# Don't forget to download the data, as described previously\r\nswirl <- readTargets(\"SwirlSample.txt\")\r\nswirl\r\nRG <- read.maimages(swirl$FileName, source=\"spot\")\r\nRG\r\nRG$genes <- readGAL(\"fish.gal\")\r\n# Get some information about the files\r\nhead(RG$genes)\r\nRG$printer <- getLayout(RG$genes)\r\nRG$printer\r\nshow(RG)\r\nsummary(RG$R)\r\n\r\n# Create the data matrix\r\nlr <- matrix(nrow=8448,ncol=4)\r\nlr[,1] <- log2(RG$R[,1])-log2(RG$G[,1])\r\nlr[,2] <- log2(RG$G[,2])-log2(RG$R[,2])\r\nlr[,3] <- log2(RG$R[,3])-log2(RG$G[,3])\r\nlr[,4] <- log2(RG$G[,4])-log2(RG$R[,4])\r\nli <- log2(RG$R)+log2(RG$G)\r\n\r\n# Install and load package nudge\r\nbiocLite(\"nudge\")\r\nlibrary(nudge)\r\n\r\n# Run packade nudge\r\nresult <- nudge1(logratio = lr,logintensity = li, dye.swap = T)\r\n\r\nnames(result)\r\nresult$mu\r\nresult$sigma\r\nresult$mixprob\r\nresult$a\r\nresult$b\r\nresult$iter\r\n\r\n# Top 20 genes with the highest probability of being DE\r\ns <- sort(result$pdiff, decreasing = T, index.return = T)\r\nrownames(lr) <- RG$genes$Name\r\ncbind(rownames(lr)[s$ix[1:20]], round(s$x[1:20], 2))\r\n\r\n# number of genes with a probability of DE, greater than 0.5\r\nthresh <- 0.5\r\nsum(result$pdiff >= thresh)\r\n", "meta": {"hexsha": "528463e77aedd7a6b8bea061d88c13d5481fe781", "size": 3327, "ext": "r", "lang": "R", "max_stars_repo_path": "pages/Day_2/Script_Examples_07 Expectation Maximization.r", "max_stars_repo_name": "GTPB/ABSTAT18", "max_stars_repo_head_hexsha": "b988354ee0a83de0b119dde49219124b08dd17f9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pages/Day_2/Script_Examples_07 Expectation Maximization.r", "max_issues_repo_name": "GTPB/ABSTAT18", "max_issues_repo_head_hexsha": "b988354ee0a83de0b119dde49219124b08dd17f9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pages/Day_2/Script_Examples_07 Expectation Maximization.r", "max_forks_repo_name": "GTPB/ABSTAT18", "max_forks_repo_head_hexsha": "b988354ee0a83de0b119dde49219124b08dd17f9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1636363636, "max_line_length": 68, "alphanum_fraction": 0.6089570183, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7415079434427682}} {"text": "## Fibonacci word/fractal 2/20/17 aev\n## Create Fibonacci word order n\nfibow <- function(n) {\n t2=\"0\"; t1=\"01\"; t=\"\";\n if(n<2) {n=2}\n for (i in 2:n) {t=paste0(t1,t2); t2=t1; t1=t}\n return(t)\n}\n## Plot Fibonacci word/fractal:\n## n - word order, w - width, h - height, d - segment size, clr - color.\npfibofractal <- function(n, w, h, d, clr) {\n dx=d; x=y=x2=y2=tx=dy=nr=0;\n if(n<2) {n=2}\n fw=fibow(n); nf=nchar(fw);\n pf = paste0(\"FiboFractR\", n, \".png\");\n ttl=paste0(\"Fibonacci word/fractal, n=\",n);\n cat(ttl,\"nf=\", nf, \"pf=\", pf,\"\\n\");\n plot(NA, xlim=c(0,w), ylim=c(-h,0), xlab=\"\", ylab=\"\", main=ttl)\n for (i in 1:nf) {\n fwi=substr(fw, i, i);\n x2=x+dx; y2=y+dy;\n segments(x, y, x2, y2, col=clr); x=x2; y=y2;\n if(fwi==\"0\") {tx=dx; nr=i%%2;\n if(nr==0) {dx=-dy;dy=tx} else {dx=dy;dy=-tx}}\n }\n dev.copy(png, filename=pf, width=w, height=h); # plot to png-file\n dev.off(); graphics.off(); # Cleaning\n}\n\n## Executing:\npfibofractal(23, 1000, 1000, 1, \"navy\")\npfibofractal(25, 2300, 1000, 1, \"red\")\n", "meta": {"hexsha": "9e570f1a45e4712c5f97c759ea60f8a3506de7d9", "size": 1024, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Fibonacci-word-fractal/R/fibonacci-word-fractal.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Fibonacci-word-fractal/R/fibonacci-word-fractal.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Fibonacci-word-fractal/R/fibonacci-word-fractal.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 31.0303030303, "max_line_length": 72, "alphanum_fraction": 0.56640625, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7413608818783769}} {"text": "alpha=0.025\r\npie=0.5\r\nE=0.03\r\nz.alpha=qnorm(1-alpha)\r\n# sample size necessary to achieve this accuracy\r\nn=((z.alpha^2)*pie*(1-pie))/E^2\r\nprint(ceiling(n))\r\n# 1,068 programs would need to be tested in order to be 95% confident that\r\n#the estimate of pie is within .03 of the actual value of pie\r\n\r\npie=0.8\r\nn=((z.alpha^2)*pie*(1-pie))/E^2\r\nprint(n)\r\n# if the designer was fairly certain that the actual value of pie was at least .80,\r\n#then the required sample size can be greatly reduced.", "meta": {"hexsha": "ad942cd3665f36111aa2d22b58acc09aa2b0c619", "size": 490, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.4/Ex10_4.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.4/Ex10_4.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.4/Ex10_4.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 32.6666666667, "max_line_length": 85, "alphanum_fraction": 0.7040816327, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210673, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7413608780036169}} {"text": "findfactors <- function(n) {\n a <- NULL\n if (n > 1) {\n while (n %% 2 == 0) {\n a <- c(a, 2)\n n <- n %/% 2\n }\n k <- 3\n while (k * k <= n) {\n while (n %% k == 0) {\n a <- c(a, k)\n n <- n %/% k\n }\n k <- k + 2\n }\n if (n > 1) a <- c(a, n)\n }\n a\n}\n", "meta": {"hexsha": "7a2f2575f8cb9b14c96a53dc12d1bceca56b767a", "size": 301, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Prime-decomposition/R/prime-decomposition-3.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Prime-decomposition/R/prime-decomposition-3.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Prime-decomposition/R/prime-decomposition-3.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.05, "max_line_length": 28, "alphanum_fraction": 0.26910299, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7413608637309982}} {"text": "# Problemas y post-estimation: multicolinealidad perfecta, \n# heteroskedasticidad, no linearidad, outliers, no normalidad de residuos, auto-correlación\n\n#################################################################\ncat(\"\\014\")\nrm(list=ls())\ngraphics.off()\n\n#################################################################\n# Motivacion\n#################################################################\n# (1) Los modelos lineales deben ser...bueno, \"lineales.\" Es decir, \n# OLS asume que la relacion entre \"X\" e \"Y\" puede ser representada\n# por una linea recta. Podemos \"desafiar\" este concepto de \"linea recta\"?\n\n# (2) Los modelos lineales asumen \"varianza constante entre los errores\". \n# Como podemos checkear ese supuesto? Como lo podemos arreglar? Como lo podemos\n# derivar matematicamente? Que relacion tiene con los outliers?\n# Var Constante: Homoesquedasticidad.\n# Var no-const: Heteroskedasticity.\n\n# (3) Como podemos detectar outliers? Como podemos solucionar este problema? \n\n# (4) Por que el aporte de una variable independiente en la dependiente\n# podria NO SER lineal, es decir, curvilinea? Este punto es importante. Que cosas\n# en la sociedad NO SON LINEALES?\n\n#################################################################\n# Linearidad y no Linearidad\n#################################################################\nlibrary(car)\ndata(Prestige) \n\noptions(scipen = 100000)\n\nmodelo.lineal <- lm(prestige ~ income + education + women, data=Prestige) \nsummary(modelo.lineal)\n\n\n# Plotear errores: manera \"artesanal\"\nplot(modelo.lineal$fitted.values, modelo.lineal$residuals)\n\n# Plotiemos los betas (uno por uno), y veamos:\n## (1) Cuanto error aportan al modelo.\n## (2) Cuan lineal es la relacion existe entre X e Y.\n\n\ncrPlot(modelo.lineal, \"income\") # Problema.\ncrPlot(modelo.lineal, \"education\") # no es exactamente lineal, pero es super tolerable.\ncrPlot(modelo.lineal, \"women\") # no hay relacion, pero no hay problemas con los residuos.\n\n# (1) El \"aporte\" de cada variable independiente debe ser lineal, es decir, una \n# linea recta. Esto es la parte del \"componente\" (en azul).\n\n# (2) El error de cada parte del \"componente\" debe ser lineal y normalmente\n# distribuido. Esta es la parte del \"residuo\" (en morado).\n\n\n\n\n\n\n# Estimemos una regresion no lineal\nmodelo.no.lineal = lm(prestige ~ poly(income, 3) + poly(education, 2) + women, data = Prestige)\nsummary(modelo.no.lineal)\n\n# crPlot con el polynomial\ncrPlot(modelo.no.lineal, \"poly(income, 3)\") \nhist(modelo.no.lineal$residuals)\nmean(modelo.no.lineal$residuals)\n# Ahora ya no hay problema con esta variable. Ademas, hemos mejorado nuestro error total.\n\n\n# Comparemos los errores\n## (1) Que modelo tendra menos errores y por que?\n\n# resumamos los residuos\nsummary(summary(modelo.lineal)$residuals)\nsummary(summary(modelo.no.lineal)$residuals)\n# Una distribucion normal (como se supone que debieran ser los errores): media = mediana = moda = 0. Y ESTE NO ES EL CASO. (MEDIA ES DIFERENTE DE MEDIANA).\n\n\n# grafiquemos los residuos\nlibrary(lattice)\nxyplot(modelo.lineal$residuals ~ modelo.lineal$fitted.values, type=c(\"smooth\", \"p\")) # mal.\nxyplot(modelo.no.lineal$residuals ~ Prestige$prestige, type=c(\"smooth\", \"p\")) # algo mejor.\n\n# Grafiquemos el \"aporte\" NO LINEAL de las variables independientes\nlibrary(effects)\nplot(effect(\"poly(income, 3)\", modelo.no.lineal)) # es el menos lineal de todos\nplot(effect(\"poly(education, 2)\", modelo.no.lineal)) # es el mas lineal.\n\n\n# El punto es que nuestros modelos estan disenados para ser LINEALES.\n# Aunque hemos usado polinomios para calzar mejor los datos, seguimos teniendo residuos heteroesquedasticos.\n# La manera en que podemos solucionar este tipo de problemas, es recurriendo\n# a transformaciones. \n\n# Nuestro problema es el siguiente: debemos estimar un modelo lineal, pero \n# la relacion entre X e Y no es lineal. Entonces, como podemos estimar modelos \n# lineales cuando tenemos relaciones no lineales?\n\n\n#################################################################\n# Linearidad y no Linearidad: Resolviendo el problema via transformaciones\n#################################################################\n\n# (1) Box-Tidwell Test\n## Estimar usando este test a cuanto tenemos que elevar nuestras variables \n## problematicas, en este caso ingresos (income).\n\nboxTidwell(prestige ~ income, ~ education + women, data=Prestige)\n# OK. Sugiere que debemos elevar income al \"0.08073\"\n\n# estimemos un modelo nuevo, pero con \"income\" transformado\nPrestige$income.transformado = Prestige$income^0.08073 # transformemos income\n\n# veamos como se ve income \"normal\" y \"transformado\"\nxyplot(Prestige$prestige ~ Prestige$income, type=c(\"smooth\", \"p\")) # el \"normal\" esta mal porque no es lineal.\nxyplot(Prestige$prestige ~ Prestige$income.transformado, type=c(\"smooth\", \"p\")) # el transformado arregla el problema porque ahora si que tenemos una relacion lineal entre Y y X.\n\n\n# OK. Ahora estimemos un nuevo modelo ocupando nuestro \"income\" transformado, y\n# veamos si soluciona el problema de fondo (es decir, no tener varianza constante en los errores).\n# Al final del dia, ese es el problema de no tener linearidad entre uno de los Xs y nuestra Y.\n\n# modelo con \"ingresos\" (income) transformado\nmodelo.no.lineal.box.tid = lm(prestige ~ income.transformado + education + women, data=Prestige) \n\n# interpretacion\nplot(effect(\"income.transformado\", modelo.no.lineal.box.tid)) # es el menos lineal de todos\n\n\n# Hagamos un scatter entre los residuos y cada una de las x (transformada y normal)\nxyplot(modelo.no.lineal.box.tid$residuals ~ modelo.no.lineal.box.tid$fitted.values, type=c(\"smooth\", \"p\")) # bien.\nxyplot(modelo.lineal$residuals ~ modelo.lineal$fitted.values, type=c(\"smooth\", \"p\")) # mal.\n\n# Resumen de los residuos: modelo con \"income\" transformado y normal.\nsummary(summary(modelo.no.lineal.box.tid)$residuals) # Mucho mejor residuos.\nsummary(summary(modelo.lineal)$residuals) # No bien.\n\n# graficar la densidad (integral) de los residuos\nlibrary(lattice)\ndensityplot((modelo.no.lineal.box.tid)$residuals) # bien\ndensityplot((modelo.lineal)$residuals) # mas o menos no mas...\n\n# (2) Tomar el log de la variable no lineal (en este caso, \"ingresos\" o \"income\")\nPrestige$log.income = log(Prestige$income)\n\n## veamos como se ve cada variable\nlibrary(lattice)\ndensityplot(Prestige$income)\ndensityplot(Prestige$log.income)\n\n# modelo\nmodelo.log.income = lm(prestige ~ log.income + education + women, data=Prestige) \n\n# resumen del modelo\nsummary(modelo.log.income)\n# (1) Como interpretamos este tipo de modelos (con una X logeada)?\n\n# Hagamos un scatter entre los residuos y cada una de las x (transformada y normal)\nxyplot(modelo.log.income$residuals ~ modelo.log.income$fitted.values, type=c(\"smooth\", \"p\")) # bien.\nxyplot(modelo.lineal$residuals ~ modelo.lineal$fitted.values, type=c(\"smooth\", \"p\")) # mal.\n\n# Resumen de los residuos: modelo con \"income\" transformado y normal.\nsummary(summary(modelo.log.income)$residuals)\nsummary(summary(modelo.lineal)$residuals) # OK---hemos mejorado algo.\n\n#################################################################\n# Outliers\n#################################################################\n\n# Parte del motivo de que algunas veces tenemos varianza no constante en los \n# residuos, es por la presencia de outliers (\"observaciones inusuales\").\n\n# Que podemos hacer respecto a esto? \n## (1) Borrar los outliers?\n## (2) Como detectamos los outliers? \n\n\n# Existen dos tipos de outliers: leverage e influence.\n\n#################################################################\n# Influence: observaciones que tiran la linea de regresion hacia arriba/abajo\n#################################################################\n\n# Demostrar ejemplo en la pizarra.\n\nlibrary(foreign) # significa \"foraneo\"\nload(url(\"https://github.com/hbahamonde/OLS/raw/master/Datasets/data.rdata\"))\ndat = data_reg\n\n# veamos como se ven los datos\nhead(dat)\n\n# estimemos modelo 3 de la tarea # 5\nm3 = lm(y3 ~ x3, dat)\n\n# veamos como se ven los problemas de \"influence\"\nlibrary(lattice)\nxyplot(m3$residuals ~ m3$fitted.values, type=c(\"smooth\", \"p\")) # residuos no tienen varianza constante.\n# Pero en especial, hay un punto con mucha \"influencia\"\n\n# Una ruta es la inspeccion visual. Tratemos de hacer algo mas sistematico. \n# Calculemos el \"Cook's Distance\" que es una medida de cuantificar cuanta \"influencia\"\n# tiene cada punto. \n\noptions(scipen=100000000) # increases threshold for scientific notation (it's got very small numbers).\n\ndat$cooks.d <- cooks.distance(m3) \n\n# veamos que es el Cook's D.\ndat # Por cada dato (o punto), tenemos un Cook's D. Fijate que la observacion numero 3 tiene mucho Cook's D. \n# ESE ES NUESTRO OUTLIER.\n\n# grafiquemos los Cooks'D\n# install.packages(\"olsrr\")\nlibrary(olsrr)\nols_plot_cooksd_chart(m3)\n\n# Ver el error\ndat$residuals = as.vector(m3$residuals)\ndat\n\n# El punto de quiebre es 4/n. \n4/nrow(dat) # Lo que esta arriba de 0.3636364 (arriba de la linea roja, es influence).\n\n#################################################################\n# Leverage: observaciones que tiran la linea de regresion hacia el lado izq/der\n#################################################################\n\n# Demostrar ejemplo en la pizarra.\n\n# Estimemos un modelo con leverage\nautos <- lm(mpg ~ wt, data = mtcars)\nsummary(autos)\n\n# ahora, grafiquemos lo que vemos vs. lo que predecimos\nplot(autos$fitted, mtcars$mpg) # Donde esta el problema? \n\n# Dado que SI tenemos un problema, nuestro error debiera seguir algun patron.\n# Es decir, debieramos NO ver una nube dispersa, y la linea debiera ser curva. Veamos.\nxyplot(autos$residuals ~ autos$fitted.values, type=c(\"smooth\", \"p\")) # residuos no tienen varianza constante.\n\n# Ocupemos una funcion de R para detectar observaciones con leverage.\nols_plot_resid_stud_fit(autos) # OK. Son las mismas 3 observaciones que habiamos visto (17, 18 y 20)\n\n\n# armemos una base de datos, solo para ver que observaciones/marcas son...\ndata.frame(\n res = autos$residuals,\n marca = rownames(mtcars),\n fila = 1:nrow(mtcars)\n )\n\n#################################################################\n# Errores Estandard Inflados: Multicolinearidad (\"imperfecta\") y Multicolinearidad Perfecta\n#################################################################\n\n# Apagar not scient.\noptions(scipen = 100000)\n\n# Inventemos las variables independientes\nset.seed(2020)\nx1 = rnorm(1000, 10)\nx2 = rnorm(1000, 20) \nx3 = (x2*x2)/1000 # x3 es una combinacion lineal de x2\n\n# Definamos que, como debiera ser, el error tiene promedio cero.\ne = rnorm(1000, 0)\n\n# Establecer el valor real de los betas: conocemos con exactitud los valores,\n# porque nosotros los creamos!\nb1 = 1\nb2 = -100\nb3 = 500\n\n# modelo verdadero (\"true model\").\ny = b1*x1 + b2*x2 + b3*x3 + e\n\n# Modelo completo\nmodelo.completo = lm(y ~ x1 + x2 + x3)\nsummary(modelo.completo)\n\n# Modelo incompleto\nmodelo.incompleto = lm(y ~ x1 + x2)\nsummary(modelo.incompleto)\n\n# Si Variance Inflation Factor (VIF) > 4....multicollinearity\nlibrary(car)\nvif(modelo.completo) \nvif(modelo.incompleto)\n\n# Ver como se \"inflan las varianzas\". Y como nosotros creamos estos datos,\n# sabemos que no es debido a \"error de medicion\". Sabemos exactamente cual es el\n# problema: x3 es una combinacion lineal de x2.\n\n# Ejemplo real: hay muchas cosas que en la sociedad estan correlacionadas, por ej?\n\n### Ejemplo Extremo\n\nej.extremo = lm(y ~ x1 + x2 + x2)\nsummary(ej.extremo)\n\nx2.prima = x2\nej.extremo.2 = lm(y ~ x1 + x2 + x2.prima)\nsummary(ej.extremo.2)\n", "meta": {"hexsha": "5cf83758e225c2c19bbc0cf7d19306c2ffd4c698", "size": 11497, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Clase17/Clase17.r", "max_stars_repo_name": "hbahamonde/OLS", "max_stars_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/Clase17/Clase17.r", "max_issues_repo_name": "hbahamonde/OLS", "max_issues_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Clase17/Clase17.r", "max_forks_repo_name": "hbahamonde/OLS", "max_forks_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2071197411, "max_line_length": 178, "alphanum_fraction": 0.6822649387, "num_tokens": 3105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7412913482777473}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Non parametric Tests - Exercise 14\n\nrm(list = ls())\n\nx <- c(9.8, 10.1, 9.7, 9.9, 10.0, 10.0, 9.8, 9.7, 9.8, 9.9)\n\n(s.x <- (x - 10)[x != 10])\n# -0.199999999999999 0.0999999999999996 -0.300000000000001 -0.0999999999999996\n# -0.199999999999999 -0.300000000000001 -0.199999999999999 -0.0999999999999996\n\nsum(duplicated(s.x))\n# 4\n\n(n.s.x <- length(s.x))\n# 8\n\n(V.x <- sum((s.x > 0) * rank(abs(s.x))))\n# 2\n\n(V.x.mean <- n.s.x * (n.s.x + 1) / 4)\n# 18\n\n(V.x.var <- n.s.x * (n.s.x + 1) * (2 * n.s.x + 1) / 24)\n# 51\n\n### H0 median == 10\n### H1 median != 10\n\n## Asymptotic pvalue (with continuity correction, without tie correction)\n2 * (1 - pnorm(abs(V.x + 0.5 - V.x.mean) / sqrt(V.x.var)))\n# 0.0299739735865558\n\n## Asymptotic pvalue (with continuity correction, with tie correction\n# TODO\n\n## Exact pvalue (not valid with ties)\n2 * (1 - psignrank(V.x, n.s.x, lower.tail = V.x.mean < V.x))\n# 0.0234375\n\nwilcox.test(x - 10, alternative = \"two.sided\", exact = FALSE)\n# Wilcoxon signed rank test with continuity correction\n#\n# data: x - 10\n# V = 2, p-value = 0.02818\n# alternative hypothesis: true location is not equal to 0\n\n\ny <- c(9.83, 10.09, 9.72, 9.87, 10.04, 9.95, 9.82, 9.73, 9.79, 9.90)\n\n(s.y <- (y - 10)[y != 10])\n# -0.17 0.0899999999999999 -0.279999999999999 -0.130000000000001 0.0399999999999991\n# -0.0500000000000007 -0.18 -0.27 -0.210000000000001 -0.0999999999999996\n\nsum(duplicated(s.y))\n# 0\n\n(n.s.y <- length(s.y))\n# 10\n\n(V.y <- sum((s.y > 0) * rank(abs(s.y))))\n# 4\n\n(V.y.mean <- n.s.y * (n.s.y + 1) / 4)\n# 27.5\n\n(V.y.var <- n.s.y * (n.s.y + 1) * (2 * n.s.y + 1) / 24)\n# 96.25\n\n### H0 median == 10\n### H1 median != 10\n\n## Asymptotic pvalue (with continuity correction)\n2 * (1 - pnorm(abs(V.y + 0.5 * sign(V.y.mean - V.y) - V.y.mean) / sqrt(V.y.var)))\n# 0.0190588916017305\n\n## Exact pvalue\n2 * (1 - psignrank(V.y - (V.y.mean < V.y), n.s.y, lower.tail = V.y.mean < V.y))\n# 0.013671875\n\nwilcox.test(y - 10, alternative = \"two.sided\", exact = TRUE)\n# Wilcoxon signed rank test\n#\n# data: y - 10\n# V = 4, p-value = 0.01367\n# alternative hypothesis: true location is not equal to 0\n\n\n\n\n", "meta": {"hexsha": "4b6e2de96b77f5cc165705c9a1061f0cdb4801cd", "size": 2149, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/non-parametric/exercise-14.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/non-parametric/exercise-14.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/non-parametric/exercise-14.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6153846154, "max_line_length": 83, "alphanum_fraction": 0.6072591903, "num_tokens": 903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7412913369332985}} {"text": "#\n# University: Universidad de Valladolid\n# Degree: Grado en Estadística\n# Subject: Análisis de Datos\n# Year: 2017/18\n# Teacher: Miguel Alejandro Fernández Temprano\n# Author: Sergio García Prado (garciparedes.me)\n# Name: Análisis de Correspondencias - Práctica 03\n#\n#\n\nrm(list = ls())\n\nlibrary(ca)\n\n#\n# 1) Importar los datos a R desde el fichero oscar.csv\n#\n\nN <- read.csv(\n './../../../datasets/oscar.csv',\n header=TRUE,\n row.names = 1)\nN\n\n\n\n#\n# 2) Efectuar un análisis de correspondencias múltiples con el paquete ac con\n# solo las variables médicas como activas a partir de la matriz de binaria, a\n# partir de la matriz de Burt y con un análisis de correspondencias conjunto y\n# comparar los resultados.\n#\n\nN_medicas <- N[,-c(1,2,3,4)]\nN_medicas_mca1 <- mjca(N_medicas, lambda=\"indicator\")\nN_medicas_mca2 <- mjca(N_medicas, lambda=\"Burt\")\nN_medicas_mca3 <- mjca(N_medicas, lambda=\"JCA\")\n\nsummary(N_medicas_mca1)\nsummary(N_medicas_mca2)\nsummary(N_medicas_mca3)\n\nplot(N_medicas)\n\n#\n# 3) ¿Cuál es la categoría peor representada en el plano definido por los 2\n# primeros factores? ¿Y cuál es la mejor representada?\n#\n\n# La categoría peor representada en todos los casos es la aparicion.subita,\n# mientras que la mejor representada es vacunado.temporada.anterior\n\n\n#\n# 4) Incluir las variables demográficas edad y sexo como suplementarias. Para\n# ello categorizar edad en 4 categorías de la siguiente forma: 1 para menores de\n# 18, 2 entre 18 y 35, 3 entre 36 y 65, 4 más de 65 años. Rehacer el análisis a\n# partir de la matriz de Burt mediante correspondencias simples.\n#\n\nN_copy <- N[,-c(1,2,4)]\nN_copy[N_copy[,1] < 18,1] = 1\nN_copy[N_copy[,1] >= 18 & N_copy[,1] <= 35,1] = 2\nN_copy[N_copy[,1] >= 36 & N_copy[,1] < 65,1] = 3\nN_copy[N_copy[,1] >= 65,1] = 4\nN_copy[,1]\n\nN_copy_mca1 <- (mjca(N_copy, lambda=\"Burt\", colsup=c(1)))\nsummary(N_copy_mca1)\nN_copy_mca1$Burt\nN_copy_mca1$sv\nsummary(ca(N_copy_mca1$Burt))\n\n#\n# 5) ¿Cuánto vale la inercia recogida por las variables suplementarias en el\n# primer factor?\n#\n\n#\n# Las variables suplementarias no contribuyen a la generación de los factores,\n# por tanto, no generan inercia en el análisis.\n#\n\n\n#\n# 6) Efectuar una representación conjunta de las proyecciones de filas y\n# columnas e interpretar los factores y el resultado del análisis.\n#\n\nplot(N_copy_mca1, what = c(\"none\",\"all\"))\n", "meta": {"hexsha": "cc313f38f727c6686a821dd3121ad33f8ca8531a", "size": 2338, "ext": "r", "lang": "R", "max_stars_repo_path": "data-analysis/correspondence-analysis/practice-03/practice-03.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "data-analysis/correspondence-analysis/practice-03/practice-03.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "data-analysis/correspondence-analysis/practice-03/practice-03.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4130434783, "max_line_length": 80, "alphanum_fraction": 0.7271171942, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7412448228008061}} {"text": "## Dale W.R. Rosenthal, 2018\n## You are free to distribute and use this code so long as you attribute\n## it to me or cite the text.\n## The legal disclaimer in _A Quantitative Primer on Investments with R_\n## applies to this code. Use or distribution without these comment lines\n## is forbidden.\n\nprincipal.start <- 30e6 # pool principal\nn.peryr <- 12 # monthly = 12 payments per year\nT <- 30 # 30-year mortgage\nr <- 0.0625 # 6.25%\nt <- 1:(n.peryr*T)\n\n## calculate level monthly payment\npmt.level <- principal.start*r/(n.peryr*(1-1/(1+r/n.peryr)^(n.peryr*T)))\n\n## 100% PSA prepayment: rate up to 6% annual at 30 months\npsa.speed <- 100 # 100% PSA\nmax.rate <- psa.speed/100*0.06\nseasoned.month <- 30 # at 30 months, PSA says mortgages are seasoned\nprepay.rate <- c(seq(max.rate/seasoned.month, max.rate, max.rate/seasoned.month),\n rep(max.rate, n.peryr*T-seasoned.month))\nprepay.monthly.survival <- (1-prepay.rate)^(1/n.peryr)\nprepay.monthly.rate <- 1-prepay.monthly.survival\n\n## In production code, this would be more elegant; however,\n## a for loop shows the intuition better than other approaches\nnum.pmts <- n.peryr*T\nprincipal.left <- c(principal.start, rep(0,num.pmts-1))\npmt.perperiod <- c(pmt.level, rep(0,num.pmts-1))\npmt.interest <- rep(0, num.pmts)\npmt.principal <- rep(0, num.pmts)\npmt.prepays <- rep(0, num.pmts)\nfor (i in 1:num.pmts) {\n pmt.interest[i] <- principal.left[i]*r/n.peryr\n pmt.principal[i] <- pmt.perperiod[i] - pmt.interest[i]\n if (pmt.principal[i] > principal.left[i]) {\n ## do not repay more than principal remaining\n pmt.principal[i] <- principal.left[i]\n ## stop the loop; pool is paid off!\n break\n } else {\n ## do not prepay more than principal remaining after normal payment\n pmt.prepays[i] <- (principal.left[i]-pmt.principal[i])*prepay.monthly.rate[i]\n if ((pmt.principal[i] + pmt.prepays[i]) > principal.left[i]) {\n pmt.prepays[i] <- principal.left[i] - pmt.principal[i]\n ## stop the loop; pool is paid off!\n break\n }\n }\n if (i < num.pmts) {\n principal.left[i+1] <- principal.left[i] - pmt.principal[i] - pmt.prepays[i]\n pmt.perperiod[i+1] <- pmt.perperiod[i]*prepay.monthly.survival[i]\n }\n}\n\nareaplot(t,data.frame(pmt.interest, pmt.principal, pmt.prepays),\n ylim=c(0,pmt.level+max(pmt.prepays)), col=c(\"red\",\"blue\",\"orange\"),\n border=FALSE)\n", "meta": {"hexsha": "d98cdc785fe1e1bbe021906f6edca13d2ce09123", "size": 2440, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch23-pools.r", "max_stars_repo_name": "bmoretz/Quantitative-Investments", "max_stars_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-26T05:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T21:50:54.000Z", "max_issues_repo_path": "Quantitative Primer/samples/ch23-pools.r", "max_issues_repo_name": "bmoretz/Quantitative-Investments", "max_issues_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quantitative Primer/samples/ch23-pools.r", "max_forks_repo_name": "bmoretz/Quantitative-Investments", "max_forks_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-03T09:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:50:55.000Z", "avg_line_length": 40.6666666667, "max_line_length": 85, "alphanum_fraction": 0.6508196721, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7410743681251065}} {"text": "# ST3068/ST2054 -- tutorial -- 30 September 2016\n# Question 4 \n\ngame = c('car', 'goat1', 'goat2')\nwin = c('car')\nswitch = TRUE\n\nhost_strategy = function(x, w) {\n # x is the list of options for the host\n # w is the winning option in the game -- the car \n # the host has to follow the rule \"never reveal the car\"\n\n y = setdiff(x, w);\n # if y has length 1 then the host must take this option\n # otherwise the host can choose between options at random\n \n if (length(y) > 1) {y = sample(x, 1, replace=FALSE)};\n return(y)\n}\n\nplayer_strategy = function (x, y, b) {\n # b is a Boolean variable\n # if b is TRUE then y is replaced with x\n\n if (b) {y = x};\n return(y)\n}\n\nwin_count = 0;\ngame_count = 1000;\n\nfor (i in 1:game_count) {\n\n player_choice = sample(game, 1, replace=FALSE);\n\n host_game = setdiff(game, player_choice);\n\n host_choice = host_strategy(host_game, win); \n\n player_game = setdiff(host_game, host_choice);\n\n outcome = player_strategy(player_game, player_choice, switch);\n \n if (outcome == win) {win_count = win_count + 1}\n\n}\n\nif (switch) {\nprint(paste('The outcome of the switch strategy:', win_count, 'wins out of', game_count, 'games.'))\n} else {\nprint(paste('The outcome of the non-switch strategy:', win_count, 'wins out of', game_count, 'games.'))\n} \n", "meta": {"hexsha": "0871bee35cae505c5ab905bf4def89dcc59efbfc", "size": 1282, "ext": "r", "lang": "R", "max_stars_repo_path": "Simulation_MontyHallProblem.r", "max_stars_repo_name": "mashenkaulm/ST2054-ST3068", "max_stars_repo_head_hexsha": "9e8fb604aca623ed908c9c8679bd4c2dd018dfc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Simulation_MontyHallProblem.r", "max_issues_repo_name": "mashenkaulm/ST2054-ST3068", "max_issues_repo_head_hexsha": "9e8fb604aca623ed908c9c8679bd4c2dd018dfc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simulation_MontyHallProblem.r", "max_forks_repo_name": "mashenkaulm/ST2054-ST3068", "max_forks_repo_head_hexsha": "9e8fb604aca623ed908c9c8679bd4c2dd018dfc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1886792453, "max_line_length": 103, "alphanum_fraction": 0.6677067083, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7409415748818317}} {"text": "# ......................................................................................\n# ..................Exercise 1 - Brief introduction to R, Combinatorics.................\n# ......................................................................................\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# Combinatorics ####\n\n\n# * r-permutations ####\n# \n# P(n, k) - r-permutations, the first argument will be the total number of entities, the\n# second argument the size of the selection\n# \n\n\n# the function is created by the fucntion command, it is an object whose name is given by a variable\n# to which I will assign this object\nr_permutation = function(n,k) # here I enter the number of parameters and their names\n{ # the whole body of the function is enclosed in parentheses {...}\n numerator = factorial(n) # the factorial in the original R exists so we will use it\n denominator = factorial(n-k)\n return(numerator/denominator) # what the function returns is given in the return(...) statement\n}\n\n# P*(n, k) - r-permutations with repetition\n# \n\n\nr_permutation_repetition = function(n,k)\n{\n return(n^k)\n}\n\n# * Permutation ####\n# \n# P(n)=P(n, n) - permutation\n# \n\n\npermutation = function(n)\n{\n return(r_permutation(n,n))\n}\n\n# P*(n1, n2, n3,...., nk) - permutation with repetition, input will be a vector with\n# individual numbers of unique entities\n# \n\n\npermutation_repetition = function(vec_n) # vec_n is the vector of values eg: vec_n=c(2,2,2,4,3)\n{\n n = sum(vec_n) # we calculate how many values we have in total\n res_temp=factorial(n) # their factorial=value in the numerator\n # a simple loop starts with the for statement, then the iterator name follows in parentheses\n # and what list will be taken as iterable object\n for(count in vec_n) # count is an iterator and will gradually take values from the vector vec_n\n {\n # we gradually divide by the factorial of each number of unique entities\n res_temp=res_temp/factorial(count) \n }\n return(res_temp)\n}\n\n# * Combination ####\n# \n# C(n, k) - combination\n# \n\n\ncombinations = function(n,k)\n{\n return(choose(n,k)) # the function for combination already exists in R and is called choose\n}\n\n# C*(n, k) - combination with repetition\n# \n\n\ncombinations_repetition = function(n,k)\n{\n return(choose(n+k-1,k)) # we use a known formula\n}\n\n# Exercise tasks ####\n# \n# * Example 1. ####\n# \n# There are three types of locks available in the store. To open the first lock, it is\n# necessary to press four of the ten buttons marked with numbers 0 to 9.(The order does\n# not matter - the buttons remain pressed.) The second lock will open if we press six of\n# the ten buttons. To open the third lock, it is necessary to set the correct\n# combination on the four discs. Which of these locks best protects against thieves?\n# \n\n\nz1=combinations(10,4)\nz2=combinations(10,6)\nz3=r_permutation_repetition(10,4)\npaste(\"count of possible passwords: \",z1,\",\",z2,\",\",z3)\npaste(\"probability od random opening: \",1/z1,\",\",1/z2,\",\",1/z3)\n\n# * Example 2. ####\n# \n# The store offers two types of briefcase locking. The first briefcase is locked with a\n# six-digit cipher. The second case is locked with two locks that open at the same time.\n# The cipher of each of them consists of three digits. Determine for each briefcase the\n# probability of opening by a thief on the first attempt. Which type of lock is safer?\n# \n\n\nz1=r_permutation_repetition(10,6);\nz2=r_permutation_repetition(10,3)*r_permutation_repetition(10,3);\nz2_v2=r_permutation_repetition(10,3)+r_permutation_repetition(10,3);\npaste(\"count combinations: \",z1,\",\",z2,\",second variant - \",z2_v2)\n\n# * Example 3. ####\n# \n# There are 40 balls in the urn - 2 red and 38 white. We randomly pull 2 balls out of\n# the urn. How likely are they both to be red?\n# \n\n\nall_combinations=combinations(40,2);\ncombinations_valid=combinations(2,2);\nprob=combinations_valid/all_combinations;\npaste(\"probability is: \",prob)\n\n# * Example 4. ####\n# \n# The student had to prepare answers to 40 questions for the exam. He could not answer\n# the two questions the examiner asked him, so he said, “I'm unlucky! These are the only\n# two questions I can't answer. ”How likely is he to tell the truth?\n# \n\n\n\n\n# * Example 5. ####\n# \n# A student passes a chemistry test if he underlines the only two aldehydes on the list\n# of 40 chemical compounds. What is the probability that a student who underlines the\n# compounds at random will pass the test?\n# \n\n\n\n\n# * Example 6. ####\n# \n# A group of 40 tourists returned from abroad, including 2 smugglers. At the border,\n# customs officer called for a personal search of two passengers and it turned out that\n# both were smugglers. The remaining tourists responded: \"The customs officer was really\n# lucky!\", \"Someone reported the smugglers!\",.... How to deal with these statements? Is\n# there a legitimate suspicion that someone reported the smugglers?\n# \n\n\n\n\n# * Example 7. ####\n# \n# From the urn with three balls, two red and one white, two balls will be selected at\n# the same time. The student and the teacher place a bet. If both balls are of the same\n# color, the student wins. If the balls have different colors, the teacher wins. Is the\n# game fair? What are the probabilities of a teacher and a student winning?\n# \n\n\n# the combn function produces combinations of the specified size - the first parameter is a vector of values, the second the size of the selection\ncombn(c('red','red','white'),2)\n\n# * Example 8. ####\n# \n# The game described in Example 7 was not fair. What ball(red or white) do we need to\n# add to the urn to make the game fair?\n# \n\n\ncombn(c('red','red','white','white'),2)\ncombn(c('red','red','white', 'red'),2)\n\n# * Example 9. ####\n# \n# You want to play \"Man, don't be angry\" (a board game requiring a dice), but all the\n# dices are lost. How can a dice be replaced if you have playing cards(a deck of 32\n# cards) and 4 different colored balls?\n# \n\n\n\n\n# * Example 10. ####\n# \n# You want to play Man, don't be angry, but the dice is lost. How can one replace a dice\n# if he has only 3 different colored balls?\n# \n\n\n\n\n# * Example 11. ####\n# \n# They have a sales event in the Škoda car dealership in February. In addition to the\n# standard equipment, they offer 3 items from the above-standard equipment free of\n# charge. Extra equipment includes 7 items:\n# \n# - cruise control, seat heating, rear airbags, xenon headlights, sunroof, gearbox lock,\n# and special durable metallic paint. \n# \n# How many options does the customer have to choose 3 items from the above-standard\n# equipment?\n# \n\n\ncombinations(7,3)\n\n# * Example 12. ####\n# \n# During the exam, 12 students will be sitting in the 5th row. The examiner wants to\n# determine himself where every student will be sitting.\n# \n# - How many ways to organize those 12 students?\n# \n# - Student Brahý asks to be able to sit on aisle seat and leave earlier to catch the\n# train. How many options are there for deploying students if the examiner wants to meet\n# Brahý's request?\n# \n# - How many opportunities are there to organize the students if Pažout and Horáček are\n# not allowed to sit next to each other?\n# \n\n\n# a\npermutation(12)\n# b\n1*permutation(11)+permutation(11)*1\n# c\ntogether=permutation(11)+permutation(11)\npermutation(12)-together\n\n# * Example 13. ####\n# \n# How many anagrams can be created from the word STATISTICS?\n# \n\n\n# 3S,3T,1A,2I,1C \nSTATISTICS=c(3,3,1,2,1)\npermutation_repetition(STATISTICS)\n\n# * Example 14. ####\n# \n# They got new goods in Tesco - boys' T-shirt in 6 different colors. They have at least\n# 7 pieces of each color. The mother wants to buy 4 T-shirts for her son. How many\n# options are there to choose from\n# \n# - if they have to be all to be different?\n# \n# - if they can all be the same?\n# \n\n\n# a\ncombinations(6,4)\n# b\ncombinations_repetition(6,4)\n\n# * Example 15. ####\n# \n# How many passwords of length 5 can we create from alphabetic characters\n# \n# - if case insensitive?\n# \n# - if case sensitive?\n# \n\n\n# a\nr_permutation_repetition(26,5)\n# b\nr_permutation_repetition(52,5)\n\n\n\n# Bonus Exercise tasks ####\n# \n# * Bonus Example 1. ####\n# \n# Which password is more secure?\n# \n# * An eight-character password consisting of numbers only.\n# \n# * A five-character password composed only of letters of the English alphabet.\n# \n\n\n# password 1\nh1 = r_permutation_repetition(n = 10, k = 8)\n# password 2\nh2 = r_permutation_repetition(n = 26, k = 5)\nh1/h2\n\n# * Bonus Example 2. ####\n# \n# How long would it take to solve a business traveler's problem for n=10 cities by brute\n# force if the evaluation of the length of each of the possible journeys takes 1 µs?\n# \n\n\nn = 10\ncount = permutation(n-1)/2\ntime = count/1000000\ntime\n\n# * Bonus Example 3. ####\n# \n# How to divide the booty between 2 robbers to get both items of the same value(or as\n# close as possible). I.e. can I divide N numbers into two groups so that the sum of the\n# numbers in each group is the same?\n# \n# **How many options would have to be tried if we solved the problem with brute force?**\n# \n\n\nN = 10\nL = 4\nr_permutation_repetition(n = L, k = N)\n\n# * Bonus Example 4. ####\n# \n# How many anagrams of the word \"AUTO\" can we create? How many anagrams of the word\n# \"AUTOMOBILKA\" can we create? How many of them start with \"K\"?\n# \n\n\npermutation(4)\nvec = c(2,1,1,2,1,1,1,1,1)\nsum(vec)\npermutation_repetition(vec)\n\nvec = c(2,1,1,2,1,1,1,1)\nsum(vec)\npermutation_repetition(vec)\n\n# * Bonus Example 5. ####\n# \n# They have 6 types of colored cups in the shop.\n# \n# - How many different ways can we buy 4 different-colored mugs?\n# \n# - How many different options can we buy 5 cups(if we don't mind more of the same\n# color)?\n# \n# - How will the situation change if they have only 4 pieces of each(and we don't mind\n# more of the same color)?\n# \n\n\ncombinations(6,4)\ncombinations_repetition(6,5)\ncombinations_repetition(6,5) - 6\n\n# * Bonus Example 6. ####\n# \n# There are 5 different pairs of socks in the package (the left and right socks are\n# always the same).\n# \n# - How many different pairs of socks can be chosen?\n# \n# - How many different ways can I wear it? (i.e. it is important what sock is on which\n# leg)\n# \n\n\ncombinations_repetition(n = 5,k = 2)\nr_permutation_repetition(n=5,k=2)\ncombinations_repetition(n = 5,k = 2)*2 - 5\n\n# * Bonus Example 7. ####\n# \n# I have 12 weights weighing 1,2,..., 12 kg.\n# \n# - How many ways can I divide them into 2 piles?\n# \n# - How many ways can I divide them into 3 piles?\n# \n# - How many ways can I divide them into 3 piles if they all have the same number of\n# weights?\n# \n# - How many ways can I divide them into 3 piles of the same number of weights, if the\n# weight of none of the pile can exceed 40 kg?\n# \n\n\nr_permutation_repetition(2,12)\nr_permutation_repetition(3,12)\n(r_permutation_repetition(3,12)-3)/permutation(3)+1\n(r_permutation_repetition(3,12)-(r_permutation_repetition(2,12)-2)*3-3)/permutation(3)\ncombinations(12,4)*combinations(8,4)/permutation(3)\npermutation(12)/(permutation(4)*permutation(4)*permutation(4)*permutation(3))\ncombinations(12,4)*combinations(8,4)/permutation(3)-combinations(8,4)\n\n# * Bonus Example 8. ####\n# \n# I have 20 seeds from each of the three vegetables(carrots, radishes, celery).\n# Unfortunately, they are mixed up and unrecognizable from each other.\n# \n# - I will plant 5 random seeds in the box. What is the probability that there will be\n# at least three radishes among them?\n# \n# - I'll plant 5 random seeds in the box. What is the probability that there will be\n# more carrots than celery among them?\n# \n\n\n(combinations(20,3)*combinations(40,2)+combinations(20,4)*combinations(40,1)+combinations(20,5))/combinations(60,5)\n\n", "meta": {"hexsha": "4ca0ff3467460d4dcb3e0f2ce82fb3e4ae783cc8", "size": 11961, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 1/T2_combinatorics.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise 1/T2_combinatorics.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise 1/T2_combinatorics.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 28.3436018957, "max_line_length": 146, "alphanum_fraction": 0.6874843241, "num_tokens": 3285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132747, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7408656940269975}} {"text": " \r\nybar = 390 # sample mean \r\nmu0 = 380 # hypothesized value \r\nsigma = 35.2 # population standard deviation \r\nn = 50 # sample size \r\nz = (ybar- mu0)/(sigma/sqrt(n))\r\n # test statistic\r\n\r\np_value=1-pnorm(z)\r\nprint(p_value)\r\nalpha=0.01\r\nif(p_value>alpha){\r\n print(\"we fail to reject H0\")\r\nprint(\" data do not support the research hypothesis.\")\r\n }else{\r\n print(\"reject H0\")\r\n }\r\n", "meta": {"hexsha": "ab925424b61deda77e41c0ee2fe0ac45055b2cee", "size": 428, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.12/Ex5_12.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.12/Ex5_12.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.12/Ex5_12.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 23.7777777778, "max_line_length": 55, "alphanum_fraction": 0.5771028037, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.74086568687005}} {"text": "#' @export\n#' @title compute.oxygen.saturation\n#' @description This function determines the percentage of Dissolved oxygen in solution at a given temperature and salinity given a known saturation amount. formula attributed to Weiss DSR 17, 721-735, 1970\n#' @param \\code{t.C} = temperature in Celsius\n#' @param \\code{sal.ppt} = salinity in ppt\n#' @param \\code{oxy.ml.l} = oxygen saturation in ml/L\n#' @return \\code{DO} = saturation percentage\n#' @examples\n#' compute.oxygen.saturation(0, 25, 8.2)\n#' [1] 95.19575\n#' @family physical and chemical properties\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\n compute.oxygen.saturation = function(t.C, sal.ppt, oxy.ml.l) {\n warning('MMM - 2016-06-17 - Please ensure this works correctly - I was unable to replicate values from online calculators')\n t.K = t.C + 273.15\n o.ml.l.saturated = exp( -173.4292 + 249.6339 * (100/t.K) \n + 143.3483*( log(t.K/100) ) \n - 21.8492*(t.K/100) \n + sal.ppt * (-0.033096 + 0.014259 * (t.K/100) - 0.0017*(t.K/100)^2 ) ) \n \n# o.mg.l.saturated = o.ml.l.saturated * 32/22.414\n \n DO = oxy.ml.l / o.ml.l.saturated * 100\n return(DO)\n }\n\n\n", "meta": {"hexsha": "e2a859ee95f195cf0e41e76b517dd46b712eb0b7", "size": 1164, "ext": "r", "lang": "R", "max_stars_repo_path": "R/compute.oxygen.saturation.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/compute.oxygen.saturation.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/compute.oxygen.saturation.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1379310345, "max_line_length": 206, "alphanum_fraction": 0.6546391753, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7408189461529492}} {"text": "#la media entre 2 muestras de la misma poblacion\r\n#immer es un dataframe don y1 y y2 del rendimiento de cebada entre los a??os 1931 y 1932\r\n\r\n#Assuming that the data in immer follows the normal distribution, find the \r\n#95% confidence interval estimate of the difference between the mean barley \r\n#yields between years 1931 and 1932.\r\n\r\n#usamos t.test para obtener el intervalo estimado entra la diferencia de medias poblacionales\r\n\r\nlibrary(MASS)\r\nhead(immer)\r\n\r\nt.test(immer$Y1,immer$Y2,paired = TRUE)\t\r\n\r\n#Paired t-test\r\n\r\n#data: immer$Y1 and immer$Y2\r\n#t = 3.324, df = 29, p-value = 0.002413\r\n#alternative hypothesis: true difference in means is not equal to 0\r\n#95 percent confidence interval:\r\n# 6.121954 25.704713\r\n#sample estimates:\r\n# mean of the differences \r\n#15.91333 \r\n", "meta": {"hexsha": "7e0f98c207ee2e3815f0099608dc92c7b0cfeece", "size": 785, "ext": "r", "lang": "R", "max_stars_repo_path": "Parcial/3. Inferencia entre poblaciones/PopulationMeanTwoMatchedSamples.r", "max_stars_repo_name": "jchudb93/Exp-Numerica", "max_stars_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Parcial/3. Inferencia entre poblaciones/PopulationMeanTwoMatchedSamples.r", "max_issues_repo_name": "jchudb93/Exp-Numerica", "max_issues_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Parcial/3. Inferencia entre poblaciones/PopulationMeanTwoMatchedSamples.r", "max_forks_repo_name": "jchudb93/Exp-Numerica", "max_forks_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4, "max_line_length": 94, "alphanum_fraction": 0.7401273885, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.74081894529687}} {"text": "alpha=0.05\r\nm=4 #comparisons\r\nalpha_l=alpha/m\r\nF_aplha_l_1_25=qf(1-alpha_l,df1 = 1,df2 = 25)\r\nprint(F_aplha_l_1_25)\r\n# We would then reject H0 if SSCi/MSError >=F_alpha_l_1_25\r\nF1 = 13.71 # computed in 9.5\r\nF2 = 8.48\r\nF3 = 0.24\r\nF4 = 1.42\r\n# we would declare contrast l1 and l2 significantly different from 0 because their F ratios are greater than 7.24.\r\n", "meta": {"hexsha": "fb39cbb75dd105b35ac023d283ac675f81ce5e6a", "size": 357, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH9/EX9.6/Ex9_6.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH9/EX9.6/Ex9_6.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH9/EX9.6/Ex9_6.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 29.75, "max_line_length": 116, "alphanum_fraction": 0.7198879552, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7408189369361146}} {"text": "## ----echo=FALSE---------------------------------------------------------------\nrequire(Hmisc)\nknitrSet('survintro')\n\n\n## ----fun-example,bty='l',echo=FALSE,cap='Survival function'-------------------\ntt <- c(seq(.0001,.002,by=.001),seq(.002,.02,by=.001),\n seq(.02,1,by=.01))\n# Note: bb,dd not stated in usual Weibull form\naa <- .5\nbb <- -.5\ncc <- 10\ndd <- 4\ncumhaz <- (aa/(bb+1))*tt^(bb + 1) + (cc/(dd+1))*tt^(dd + 1)\nsurvival <- exp(-cumhaz)\nhazard <- ifelse(tt>.001, aa*tt^bb + cc*tt^dd, NA)\nplot(tt, survival, type=\"l\", xlab=expression(t), ylab=expression(S(t)))\n\n## ----cumhaz-example,bty='l',echo=FALSE,cap='Cumulative hazard function'-------\nplot(tt, cumhaz, type=\"l\", xlab=expression(t),\n ylab=expression(Lambda(t)))\n\n## ----hazard-example,bty='l',echo=FALSE,cap='Hazard function'------------------\nplot(tt, hazard, type=\"l\", xlab=expression(t), ylab=expression(lambda(t)))\n\n\n## ----weibull-shapes,bty='l',echo=FALSE,cap='Some Weibull hazard functions with $\\\\alpha=1$ and various values of $\\\\gamma$.'----\ntt <- seq(1e-5, 1.2, length=100)\nplot(tt, rep(0,100), ylim=c(0,7), type=\"n\", xlab=expression(t), ylab=\"\")\na <- 1\ni <- 0\nfor(b in c(.5,1,2,4)) {\n i <- i + 1\n lines(tt, a*b*tt^(b-1), lty=i)\n}\nlegend(.4, 6, c(\".5\",\"1\",\"2\",\"4\"), lty=1:4, cex=.9, bty=\"n\")\n\n\n## ----km-example,bty='l',cap='Kaplan--Meier product--limit estimator with $0.95$ confidence bands. The Altschuler--Nelson--Aalen--Fleming--Harrington estimator is depicted with the dotted lines.',scap='Kaplan--Meier and Nelson--Aalen estimates'----\nrequire(rms)\ntt <- c(1,3,3,6,8,9,10)\nstat <- c(1,1,1,0,0,1,0)\nS <- Surv(tt, stat)\nsurvplot(npsurv(S ~ 1), conf=\"bands\", n.risk=TRUE,\n xlab=expression(t))\nsurvplot(npsurv(S ~ 1, type=\"fleming-harrington\",\n conf.int=FALSE), add=TRUE, lty=3)\n\n\n## ----eval=FALSE---------------------------------------------------------------\n## require(rms)\n## units(y) <- \"Month\"\n## # Default is \"Day\" - used for axis labels, etc.\n## npsurv(Surv(y, event) ~ svar1 + svar2 + ... , data, subset,\n## type=c(\"kaplan-meier\", \"fleming-harrington\", \"fh2\"),\n## error=c(\"greenwood\", \"tsiatis\"), se.fit=TRUE,\n## conf.int=.95,\n## conf.type=c(\"log\",\"log-log\",\"plain\",\"none\"), ...)\n\n\n## ----eval=FALSE---------------------------------------------------------------\n## f <- npsurv(...)\n## print(f) # print brief summary of f\n## summary(f, times, censored=FALSE) # in survival\n\n\n## ----eval=FALSE---------------------------------------------------------------\n## f <- npsurv(Surv(futime, event) ~ sex)\n## summary(f, seq(30, 180, by=30))\n\n\n## ----eval=FALSE---------------------------------------------------------------\n## units(y) <- \"Year\"\n## f <- npsurv(Surv(y, stat) ~ treatment)\n## survplot(f, ylab=\"Fraction Pain-Free\")\n\n\n## ----eval=FALSE---------------------------------------------------------------\n## cph(Survobject ~ predictor)\n\n", "meta": {"hexsha": "59249bc12d2c1b1667f1e86cd98aab35dabaf1d8", "size": 2896, "ext": "r", "lang": "R", "max_stars_repo_path": "RMScode/17_survival_intro.r", "max_stars_repo_name": "fabarrios/Regression", "max_stars_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-01T18:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T18:27:09.000Z", "max_issues_repo_path": "RMScode/17_survival_intro.r", "max_issues_repo_name": "fabarrios/Regression", "max_issues_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-23T23:59:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T23:59:10.000Z", "max_forks_repo_path": "RMScode/17_survival_intro.r", "max_forks_repo_name": "fabarrios/Regression", "max_forks_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-24T03:43:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T03:43:53.000Z", "avg_line_length": 35.7530864198, "max_line_length": 250, "alphanum_fraction": 0.5120856354, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7407348339988493}} {"text": "library(reshape2)\nlibrary(Rcpp)\nlibrary(ggplot2)\n\n\ncppFunction('\n List sirc(double beta, double gamma, double N, double S0, double I0, double R0, double tf){\n double t = 0;\n double S = S0;\n double I = I0;\n double R = R0;\n std::vector ta;\n std::vector Sa;\n std::vector Ia;\n std::vector Ra;\n do{\n ta.push_back(t);\n Sa.push_back(S);\n Ia.push_back(I);\n Ra.push_back(R);\n double pf1 = beta*S*I;\n double pf2 = gamma*I;\n double pf = pf1+pf2;\n double dt = rexp(1,pf)[0];\n t += dt;\n double r = runif(1)[0];\n if(r0));\n return List::create(_[\"time\"] = ta, _[\"S\"] = Sa, _[\"I\"] = Ia, _[\"R\"]=Ra);\n }'\n)\n\nset.seed(42)\n\nsir_out_list <- sirc(0.1/1000,0.05,1000,999,1,0,200)\n\nsir_out <- as.data.frame(sir_out_list)\n\nif(dim(sir_out)[1]==1){\n sir_out_list <- sirc(0.1/1000,0.05,1000,999,1,0,200)\n sir_out <- as.data.frame(sir_out_list)\n}\n\nhead(sir_out)\n\nsir_out_long <- melt(sir_out,\"time\")\n\n# Plot\nggplot(sir_out_long,aes(x=time,y=value,colour=variable,group=variable)) +\n geom_line(lwd=2) + xlab(\"Time\") + ylab(\"Number\")\n", "meta": {"hexsha": "8291e0d911dc858c8546c73fafa3f3fc185012fe", "size": 1258, "ext": "r", "lang": "R", "max_stars_repo_path": "models/simple_stochastic_models/continuous_t_sir/ssir_rcpp.r", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_stochastic_models/continuous_t_sir/ssir_rcpp.r", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_stochastic_models/continuous_t_sir/ssir_rcpp.r", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 21.6896551724, "max_line_length": 93, "alphanum_fraction": 0.5627980922, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7406245570063981}} {"text": "#!/usr/bin/env Rscript\n\n# eg.1 总体均值mu的区级估计\nweight = scan(\"res/noodle.TXT\")\nsummary(weight)\nresult = t.test(weight, con =.95)\nprint(result$con)\n\n# eg.2 两个总体均值之差估计(mu1 - mu2)\nv = read.table(\"res/expend.txt\", header=T)\nv1 = v[v[, 2] == 1, 1]\nv2 = v[v[, 2] == 2, 1]\n\nm1 = mean(v1)\nm2 = mean(v2)\n\ndiff = m1 - m2\nprint(diff)\n\nsd(v1)\nsd(v2)\n\nt.test(v1, con=.95)$con\nt.test(v2, con=.95)$con\n\nt.test(v1, v2, con=.90)$conf\n\n\n", "meta": {"hexsha": "04d4ee4209845aefcce2799fe14472a0cad8c5a0", "size": 415, "ext": "r", "lang": "R", "max_stars_repo_path": "R/learn/Wuxizhi/class5.r", "max_stars_repo_name": "qrsforever/workspace", "max_stars_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-07T03:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-07T09:14:26.000Z", "max_issues_repo_path": "R/learn/Wuxizhi/class5.r", "max_issues_repo_name": "qrsforever/workspace", "max_issues_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/learn/Wuxizhi/class5.r", "max_forks_repo_name": "qrsforever/workspace", "max_forks_repo_head_hexsha": "53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.3103448276, "max_line_length": 42, "alphanum_fraction": 0.6072289157, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7405870618547774}} {"text": "## let L(D|theta) be a likelihood > 0 for all thera.\n## let Y = [L(D|theta)]^2\n## then the prior pi(theta) induces a measure on the space Y\n\n### Binomial\n\nn <- 10\nx <- 3\n\nap <- 2\nbp <- 2\n\np.samples <- rbeta(n = 1e6, shape1 = ap, shape2 = bp)\n\nX <- dbinom(x = x, size = n, prob = p.samples)\n\nhist(X, main = \"Binomial\")\n\nY <- X^2\n\nhist(Y, main = \"Binomial\")\n\n###############\n\n#### Normal, fixed variance\n\nx <- -1\ns <- .1\n\n\nmu.samples <- rnorm(n = 1E6)\n\nX <- dnorm(x = x, mean = mu.samples, sd = s)\n\nhist(X, main = \"Gaussian\")\n\nY <- X^2\n\nhist(Y, main = \"Gaussian\")\n\n###############\n\n#### Beta with fixed shape1\n\npsi <- .5\ns1 <- 2\n\ns2.samples <- rgamma(n = 1E6, shape = 2, rate = 1)\n\nX <- dbeta(x = psi, shape1 = s1, shape2 = s2.samples)\n\nhist(X, main = \"Beta\")\n\nY <- X^2\n\nhist(Y, main = \"Beta\")\n\n", "meta": {"hexsha": "e15f05313c4647b61bb8c37c02bec3caac0f8f53", "size": 793, "ext": "r", "lang": "R", "max_stars_repo_path": "code/extra/test_g(y).r", "max_stars_repo_name": "maxbiostat/propriety_power_priors", "max_stars_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/extra/test_g(y).r", "max_issues_repo_name": "maxbiostat/propriety_power_priors", "max_issues_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-29T19:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-29T15:58:08.000Z", "max_forks_repo_path": "code/extra/test_g(y).r", "max_forks_repo_name": "maxbiostat/propriety_power_priors", "max_forks_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.6724137931, "max_line_length": 60, "alphanum_fraction": 0.5384615385, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7404357337164872}} {"text": "zeckendorf <- function(number) {\n\n # Get an upper limit on Fibonacci numbers needed to cover number\n indexOfFibonacciNumber <- function(n) {\n if (n < 1) {\n 2\n } else {\n Phi <- (1 + sqrt(5)) / 2\n invertClosedFormula <- log(n * sqrt(5)) / log(Phi)\n ceiling(invertClosedFormula)\n }\n }\n\n upperLimit <- indexOfFibonacciNumber(number)\n\n # Return the sequence as digits, sorted descending\n fibonacciSequenceDigits <- function(n) {\n fibGenerator <- function(f, ...) { c(f[2], sum(f)) }\n fibSeq <- Reduce(fibGenerator, 1:n, c(0,1), accumulate=TRUE)\n\n fibNums <- unlist(lapply(fibSeq, head, n=1))\n\n # drop last F0 and F1 and reverse sequence\n rev(fibNums[-2:-1])\n }\n\n digits <- fibonacciSequenceDigits(upperLimit)\n\n isInNumber <- function(digit) {\n if (number >= digit) {\n number <<- number - digit\n 1\n } else {\n 0\n }\n }\n\n zeckSeq <- Map(isInNumber, digits)\n\n # drop leading 0 and convert to String\n gsub(\"^0+1\", \"1\", paste(zeckSeq, collapse=\"\"))\n}\n\nprint(unlist(lapply(0:20, zeckendorf)))\n", "meta": {"hexsha": "bee9d99ecbbddb5ae5f5eff98341b41fe6be460c", "size": 1061, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Zeckendorf-number-representation/R/zeckendorf-number-representation.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Zeckendorf-number-representation/R/zeckendorf-number-representation.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Zeckendorf-number-representation/R/zeckendorf-number-representation.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 23.5777777778, "max_line_length": 66, "alphanum_fraction": 0.6173421301, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7404357295303563}} {"text": "\n## Author: Sergio García Prado\n\nrm(list = ls())\n\ny <- c(7, 6, 8, 16, 13)\nk <- length(y)\nn <- sum(y)\n\n\n\n\nLogLikelihood <- function(p, y, k) {\n sum(y[1:(k - 1)] * log(p)) + y[k] * log(1 - sum(p))\n}\n\n\nNegativeLogLikelihood <- function(...) {\n - LogLikelihood(...)\n}\n\np.hat.initial <- rep(1 / k, k - 1)\nopt <- optim(p.hat.initial[1:(k - 1)], NegativeLogLikelihood, y = y, k = k, hessian = TRUE)\n\n(p.hat <- opt$par)\n# 0.139976175373378 0.120217883250931 0.159986995019396 0.319854212163691\n\n(p.hat.var <- solve(opt$hessian))\n# 0.0024070858\t-0.0003370446\t-0.0004477195\t-0.0008948212\n# -0.0003370446\t0.0021183563\t-0.0003852716\t-0.0007700115\n# -0.0004477195\t-0.0003852716\t0.0026874471\t-0.0010228592\n# -0.0008948212\t-0.0007700115\t-0.0010228592\t0.0043497380\n\n## a)\n####\n\nLogLikelihood1H0 <- function(theta, y, k) {\n LogLikelihood(c(theta[1], theta[1], theta[1], theta[2]), y, k)\n}\n\n\nNegativeLogLikelihood1H0 <- function(...) {\n - LogLikelihood1H0(...)\n}\n\nopt1.hzero <- optim(c(0.1, 0.1), NegativeLogLikelihood1H0, y = y, k = k, hessian = TRUE)\n\n(LRT1 <- 2 * (LogLikelihood(p.hat, y, k) - LogLikelihood1H0(opt1.hzero$par, y, k)))\n# 0.286670914555231\n\n(LRT1.pvalue <- 1 - pchisq(LRT1, df = (k - 1) - 3))\n# 0.59236182742952\n\n\n## b)\n####\n\ng1 <- function(p) {\n c(p[1] - p[2],\n p[1] - p[3],\n p[1] + p[2] + p[3] + 2 * p[4] - 1)\n}\n\n\ng1.derivative <- function(p) {\n matrix(c(1, -1, 0, 0,\n 1, 0, -1, 0,\n 1, 1, 1, 2),\n 3, 4, byrow = TRUE)\n}\n\n(g1.hat <- g1(p.hat))\n# 0.0197582921224479 -0.0200108196460179 0.059889477971087\n\n(g1.hat.var <- g1.derivative(p.hat) %*% p.hat.var %*% t(g1.derivative(p.hat)))\n# 5.199531e-03\t2.806578e-03\t-2.333792e-05\n# 2.806578e-03\t5.989972e-03\t2.394155e-05\n# -2.333792e-05\t2.394155e-05\t1.152100e-02\n\n(W1 <- t(g1.hat - rep(0, 3)) %*% solve(g1.hat.var) %*% (g1.hat - rep(0, 3)))\n# 0.6002303\n\n(W1.pvalue <- 1 - pchisq(W1, df = (k - 1) - 3))\n# 0.4384902\n\n## c)\n####\n\n\nLogLikelihood2H0 <- function(theta, y, k) {\n LogLikelihood(c(theta[1], 2 * theta[1], theta[2], theta[2]), y, k)\n}\n\n\nNegativeLogLikelihood2H0 <- function(...) {\n - LogLikelihood2H0(...)\n}\n\nopt2.hzero <- optim(c(0.1, 0.1), NegativeLogLikelihood2H0, y = y, k = k, hessian = TRUE)\n\n(LRT2 <- 2 * (LogLikelihood(p.hat, y, k) - LogLikelihood2H0(opt2.hzero$par, y, k)))\n# 5.01968859661113\n\n(LRT2.pvalue <- 1 - pchisq(LRT2, df = (k - 1) - 2))\n# 0.0812808938285899\n\n\n## d)\n####\n\ng2 <- function(p) {\n c(p[2] - 2 * p[1],\n p[3] - p[4])\n}\n\n\ng2.derivative <- function(p) {\n matrix(c(-2, 1, 0, 0,\n 0, 1, -1, 0),\n 2, 4, byrow = TRUE)\n}\n\n(g2.hat <- g2(p.hat))\n# -0.120217883250931 -0.159867217144294\n\n(g2.hat.var <- g2.derivative(p.hat) %*% p.hat.var %*% t(g2.derivative(p.hat)))\n# 0.013094878\t0.002282278\n# 0.002282278\t0.005576347\n\n(W2 <- t(g2.hat - rep(0, 2)) %*% solve(g2.hat.var) %*% (g2.hat - rep(0, 2)))\n# 5.314512\n\n(W2.pvalue <- 1 - pchisq(W2, df = (k - 1) - 2))\n# 0.07014043\n", "meta": {"hexsha": "7290fac7c8f37fd1bcf428ca78fc171deaaec664", "size": 2914, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/likelihood/exercise-07.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/likelihood/exercise-07.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/likelihood/exercise-07.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5851851852, "max_line_length": 91, "alphanum_fraction": 0.5823610158, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7403266538918936}} {"text": "#' Generate a damped random walk power spectrum.\n#'\n#' \\deqn{PSD(f) = \\frac{\\tau^2 SF_\\infty^2}{1 + (2 \\pi f \\tau)^2}}\n#'\n#' @param N Number of frequencies (must be even).\n#' @param freq.max Value of largest frequency.\n#' @param tau Characteristic timescale.\n#' @param SF Value of structure function over long time scales.\n#' @param sd Standard deviation.\n#'\n#' @return Frequencies and power spectral density.\n#'\n#' @examples\n#' damped.random.walk(100) # 100 samples with default options\n#' damped.random.walk(100, freq.max = 50) # provide maximum frequency\n#' damped.random.walk(100, sd = 2.0) # provide standard deviation\n#' damped.random.walk(100, tau = 2.0) # provide characteristic timescale\n#' damped.random.walk(100, SF = 2.0) # provide value of structure function\n#'\n#' @export\ndamped.random.walk <- function(N, freq.max = 1/(2*pi),\n tau = 1.0, SF = 1.0, sd = 1.0) {\n f <- freq(N, freq.max = freq.max)\n freq.pos <- f$freq.pos\n freq <- f$freq\n\n # compute the mean values of the power spectrum's absolute value\n mean.power <- tau * SF * (1 + (2*pi * freq.pos*tau)^2)^-0.5\n\n # generate a noisy power spectrum in complex form\n z <- noisy.power.spectrum(mean.power, sd = sd)\n # include negative frequencies in the final spectrum, with opposite phase\n z <- mirror.complex(z)\n\n # return the power spectrum along with the frequencies\n rbind(freq, z)\n}\n", "meta": {"hexsha": "45d2e3f0a372b32b7c4b6037ae64c7f0da2c9728", "size": 1444, "ext": "r", "lang": "R", "max_stars_repo_path": "R/damped.random.walk.r", "max_stars_repo_name": "dwysocki/random-noise-generation", "max_stars_repo_head_hexsha": "97bb8392faa4c25399b44b52bc471a95cb44ec7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-24T05:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-24T05:46:19.000Z", "max_issues_repo_path": "R/damped.random.walk.r", "max_issues_repo_name": "dwysocki/random-noise-generation", "max_issues_repo_head_hexsha": "97bb8392faa4c25399b44b52bc471a95cb44ec7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/damped.random.walk.r", "max_forks_repo_name": "dwysocki/random-noise-generation", "max_forks_repo_head_hexsha": "97bb8392faa4c25399b44b52bc471a95cb44ec7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0, "max_line_length": 79, "alphanum_fraction": 0.6454293629, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816422, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7401616974172}} {"text": "# Sampling from easy distributions\n# with the method of inversion\n#\n# author: Alberto Lumbreras\n######################################\npar(mfrow=c(1,1))\n\n# demo 1: logistic distribution\n# demo 2: exponential distribution\ndemo <- 1\n\n# Logistic distribution\n###########################\nif(demo==1){\n \n # Plot density and cdf\n x <- seq(-10,10, by=0.1)\n plot(x, dlogis(x), type='l', lwd=3, col=\"black\", ylim=c(0,1)) # density\n lines(x, plogis(x), lwd=3, col=\"red\") # cdf\n title(\"Inverse method (Logistic distribution)\")\n\n # Inverse CDF\n cdf_inv <- function(x, loc=0, scale=10){\n log(x/(1-x))\n }\n\n}\n\n# Exponential distribution\n###########################\nif(demo==2){\n \n # Plot density and cdf\n x <- seq(0,10, by=0.1)\n plot(x, dexp(x), type='l', lwd=3, col=\"black\", ylim=c(0,1)) # density\n lines(x, pexp(x), lwd=3, col=\"red\") # cdf\n title(\"Inverse method (Exponential distribution)\")\n \n # Inverse CDF\n cdf_inv <- function(x){\n -log(1-x)\n }\n}\n\n\n# Sampling by the inverse method\n#################################\nnsamples <-100000\nsamples <- rep(NA,nsamples)\nfor (i in 1:nsamples){\n x <- runif(1)\n samples[i] <- cdf_inv(x)\n}\n\n# Plot samples\nhist(samples, breaks=100, add=TRUE, probability = TRUE)\n\n", "meta": {"hexsha": "e8e172722aa5a0b10751fa9a6461a55614b79ee6", "size": 1220, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/simple.r", "max_stars_repo_name": "alumbreras/MCMC_intro", "max_stars_repo_head_hexsha": "a07022fb09b0cc65b7c4741917ee02364ec4c6b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/simple.r", "max_issues_repo_name": "alumbreras/MCMC_intro", "max_issues_repo_head_hexsha": "a07022fb09b0cc65b7c4741917ee02364ec4c6b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/simple.r", "max_forks_repo_name": "alumbreras/MCMC_intro", "max_forks_repo_head_hexsha": "a07022fb09b0cc65b7c4741917ee02364ec4c6b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-16T18:13:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-16T18:13:26.000Z", "avg_line_length": 21.0344827586, "max_line_length": 73, "alphanum_fraction": 0.5704918033, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.7401586120663509}} {"text": "library(markovchain)\n\nset.seed(1)\nStates <- c(\"Rainy\",\"Cloudy\",\"Sunny\")\nTransMat <- matrix(c(0.30,0.50,0.20,0.25,0.4,0.35,0.1,0.2,0.70),nrow = 3, byrow = TRUE,dimnames = list(States,States))\n\nMarkovChainModel <- new(\"markovchain\",transitionMatrix=TransMat, states=States, byrow = TRUE, name=\"MarkovChainModel\") \nMarkovChainModel\n\nstates(MarkovChainModel)\ndim(MarkovChainModel)\n\nstr(MarkovChainModel)\nMarkovChainModel@transitionMatrix\n\nlibrary(diagram)\n\nplot(MarkovChainModel,package=\"diagram\")\n\n\ntransitionProbability(MarkovChainModel, \"Sunny\", \"Rainy\")\n\n\nStartState<-c(0,0,1)\n\nPred3Days <- StartState * (MarkovChainModel ^ 3)\nprint (round(Pred3Days, 3))\nPred1Week <- StartState * (MarkovChainModel ^ 7)\nprint (round(Pred1Week, 3))\n\nsteadyStates(MarkovChainModel)\n\nYearWeatherState <- rmarkovchain(n = 365, object = MarkovChainModel, t0 = \"Sunny\")\nYearWeatherState[1:40]\n\n\n\n\n\n", "meta": {"hexsha": "55b48bfe3ad8b2a3155b2c4032bb32d57ae0139b", "size": 876, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter03/WheatherForecasting.r", "max_stars_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_stars_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-01-19T06:32:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T06:37:07.000Z", "max_issues_repo_path": "Chapter03/WheatherForecasting.r", "max_issues_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_issues_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter03/WheatherForecasting.r", "max_forks_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_forks_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-12-25T17:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T13:19:18.000Z", "avg_line_length": 21.9, "max_line_length": 119, "alphanum_fraction": 0.7511415525, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.7398869441541822}} {"text": "# Bayesian approach:\ngibbs1 = function(iters,y,alpha){\n x<-array(0,c(iters+1,3))\n beta = 0.0446\n x[1,1] = 8.625 # initial lamda value.\n x[2,2] = (0.20 * sum(y)) # OD initial value.\n temp = c()\n \n # Posterior Distribution is gamma distribution for parameter lamda. \n total_probability = function(lamda,X){\n a = 0\n for (i in 1:8){\n xp = (exp(-lamda)*lamda^(X[i]))/factorial(X[i])\n a = a + xp\n }\n return(mean(a))\n }\n \n for (t in 2: (iters+1)){\n \n x[t,1] = rgamma(1, (x[t,2] + (sum(y) - x[t,2]) + alpha), 8 + beta)\n z = c(9,16,6,8,15,8,2,5) # these are the units failed in a hourly basis in the sample dataset.\n # total probability of failure occurance.\n p = total_probability(x[t,1],z)\n x[t,3] = (0.20 * p) # this gives the probability of units failed beacuse of Other Defects.\n x[t,2] = rbinom(1,69,0.20 * p)\n }\n\n par(mfrow=c(1,2))\n plot(1:length(x[,1]),x[,1], type='l', lty=1, xlab='t', ylab='lambda')\n plot(1:length(x[,2]),x[,2], type='l', ylim=c(0,20), lty=1, xlab='t', ylab='OD')\n \n return(x)\n }\nset.seed(123)\ny=rpois(8, 8.625)\n\n\noutput = gibbs1(1000, y, 1)\noutput\n\n# Lamda value.\nabsence<-(output[,1]) \nabsent<-(absence [101:1000])\nmean(absent) # posterior estimate for lambda.\nvar(absent) # variance associated with lamda.\n# Posterior lamda distribution graph.\npar(mfrow=c(1,1))\nhist(absent,\n breaks=25, \n freq=F, \n main=\"Total Defects\",\n xlab=\"Rate parameter(Units failed)\",\n ylab=\"Density\")\n\n# Number of Other Defects caused.\nOD <- (output[,2]) \nmean(OD) # mean number of Other defect occurance.\n\n# Probibility sample of Other Defects occurance.\nother_defect <- (output[,3]) \nother_defect_mean <- mean(other_defect) # mean probability of Other Defects Occurance. \n\n\n\n\n", "meta": {"hexsha": "72d861fe845d31db052fbfd703553db1e47353cd", "size": 1818, "ext": "r", "lang": "R", "max_stars_repo_path": "StressTestTimingOptimization[Bayesian-Weibull-Model]/EST_Optimization(OD).r", "max_stars_repo_name": "Josh-repository/Bayesian-Model", "max_stars_repo_head_hexsha": "2cc7aaff3d3ec8a339b5d2422e0f9988652c0112", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StressTestTimingOptimization[Bayesian-Weibull-Model]/EST_Optimization(OD).r", "max_issues_repo_name": "Josh-repository/Bayesian-Model", "max_issues_repo_head_hexsha": "2cc7aaff3d3ec8a339b5d2422e0f9988652c0112", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StressTestTimingOptimization[Bayesian-Weibull-Model]/EST_Optimization(OD).r", "max_forks_repo_name": "Josh-repository/Bayesian-Model", "max_forks_repo_head_hexsha": "2cc7aaff3d3ec8a339b5d2422e0f9988652c0112", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1343283582, "max_line_length": 98, "alphanum_fraction": 0.598459846, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7397654351210964}} {"text": "# Example : 3 Chapter : 6.6 Page No: 357\n# Pascals matrix and its inverse are similar\nA<-matrix(c(1,1,1,1,0,1,2,3,0,0,1,3,0,0,0,1),ncol=4)\nA1<-solve(A)\nAev<-eigen(A)$values\nA1ev<-eigen(A1)$values\nprint(\"Both pascal matrix and its inverse have same eigen values\")\nprint(Aev)\nprint(A1ev)", "meta": {"hexsha": "58eccd09f88ced4c3d2fc60314d106504f6190b3", "size": 291, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.6.a/Ex6_6.6A.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.6.a/Ex6_6.6A.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.6.a/Ex6_6.6A.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 32.3333333333, "max_line_length": 66, "alphanum_fraction": 0.6907216495, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7395167789025149}} {"text": "# Chapter 3 Lab: Linear Regression\n\nlibrary(MASS)\nlibrary(ISLR)\n\n# Simple Linear Regression\n\nfix(Boston)\nnames(Boston)\nlm.fit=lm(medv~lstat)\nlm.fit=lm(medv~lstat,data=Boston)\nattach(Boston)\nlm.fit=lm(medv~lstat)\nlm.fit\nsummary(lm.fit)\nnames(lm.fit)\ncoef(lm.fit)\nconfint(lm.fit)\npredict(lm.fit,data.frame(lstat=(c(5,10,15))), interval=\"confidence\")\npredict(lm.fit,data.frame(lstat=(c(5,10,15))), interval=\"prediction\")\nplot(lstat,medv)\nabline(lm.fit)\nabline(lm.fit,lwd=3)\nabline(lm.fit,lwd=3,col=\"red\")\nplot(lstat,medv,col=\"red\")\nplot(lstat,medv,pch=20)\nplot(lstat,medv,pch=\"+\")\nplot(1:20,1:20,pch=1:20)\npar(mfrow=c(2,2))\nplot(lm.fit)\nplot(predict(lm.fit), residuals(lm.fit))\nplot(predict(lm.fit), rstudent(lm.fit))\nplot(hatvalues(lm.fit))\nwhich.max(hatvalues(lm.fit))\n\n# Multiple Linear Regression\n\nlm.fit=lm(medv~lstat+age,data=Boston)\nsummary(lm.fit)\nlm.fit=lm(medv~.,data=Boston)\nsummary(lm.fit)\nlibrary(car)\nvif(lm.fit)\nlm.fit1=lm(medv~.-age,data=Boston)\nsummary(lm.fit1)\nlm.fit1=update(lm.fit, ~.-age)\n\n# Interaction Terms\n\nsummary(lm(medv~lstat*age,data=Boston))\n\n# Non-linear Transformations of the Predictors\n\nlm.fit2=lm(medv~lstat+I(lstat^2))\nsummary(lm.fit2)\nlm.fit=lm(medv~lstat)\nanova(lm.fit,lm.fit2)\npar(mfrow=c(2,2))\nplot(lm.fit2)\nlm.fit5=lm(medv~poly(lstat,5))\nsummary(lm.fit5)\nsummary(lm(medv~log(rm),data=Boston))\n\n# Qualitative Predictors\n\nfix(Carseats)\nnames(Carseats)\nlm.fit=lm(Sales~.+Income:Advertising+Price:Age,data=Carseats)\nsummary(lm.fit)\nattach(Carseats)\ncontrasts(ShelveLoc)\n\n# Writing Functions\n\nLoadLibraries\nLoadLibraries()\nLoadLibraries=function(){\n library(ISLR)\n library(MASS)\n print(\"The libraries have been loaded.\")\n }\nLoadLibraries\nLoadLibraries()\n", "meta": {"hexsha": "671df7ff6c35c5631a8f17b065f425c12a5f8eb7", "size": 1687, "ext": "r", "lang": "R", "max_stars_repo_path": "islr/r_code/chap3.r", "max_stars_repo_name": "AtmaMani/pyChakras", "max_stars_repo_head_hexsha": "e58a4e244d65858049914cf98dcb454ef009362a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "islr/r_code/chap3.r", "max_issues_repo_name": "AtmaMani/pyChakras", "max_issues_repo_head_hexsha": "e58a4e244d65858049914cf98dcb454ef009362a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T01:01:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:01:42.000Z", "max_forks_repo_path": "islr/r_code/chap3.r", "max_forks_repo_name": "AtmaMani/pyChakras", "max_forks_repo_head_hexsha": "e58a4e244d65858049914cf98dcb454ef009362a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-09T02:11:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T19:34:32.000Z", "avg_line_length": 20.0833333333, "max_line_length": 69, "alphanum_fraction": 0.7409602845, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.739139197329487}} {"text": "# Hypothesis Testing or one-tailed test \r\n \r\nybar = 573 # sample mean \r\n mu0 = 520 # hypothesized value \r\n sigma = 124 # population standard deviation \r\n n = 36 # sample size \r\n z = (ybar- mu0)/(sigma/sqrt(n))\r\n print(z) # test statistic\r\n \r\n # We then compute the critical value at .025 significance level.\r\n # For alpha= .025, reject the null hypothesis if lies more than 1.96 \r\n alpha = .025 \r\n z.alpha = qnorm(1-alpha) \r\n print(z.alpha)\r\n ", "meta": {"hexsha": "658626d50dcc0a1765554f257e7f9e6195e774d0", "size": 499, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.5/Ex5_5.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.5/Ex5_5.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.5/Ex5_5.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 33.2666666667, "max_line_length": 72, "alphanum_fraction": 0.5911823647, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7389717986019342}} {"text": "library(MASS)\r\n\r\nwhite <- 10\r\nred <- 4\r\ngreen <- 7\r\n\r\ntotal <- green + red + white\r\npr_total <- choose(total, 3)\r\n\r\n# Richiesta 1: tre rosse\r\n\r\ntrerosse <- fractions(choose(red, 3)/pr_total)\r\nprint(trerosse)\r\n\r\n# Richiesta 2: tre bianche\r\n\r\ntrebianche <- fractions(choose(white, 3)/pr_total)\r\nprint(trebianche)\r\n\r\n# Richiesta 3: 2 rosse e 1 bianca\r\n\r\nduerosseunabianca <- fractions((choose(red, 2)*choose(white, 1))/pr_total)\r\nprint(duerosseunabianca)\r\n\r\n# Richiesta 4: almeno una sia bianca\r\n\r\nalmenounabianca <- fractions(1 - choose(red+green, 3)/pr_total)\r\nprint(almenounabianca)\r\n\r\n# Richiesta 5: tutte di colori diversi\r\n\r\ntrecolori <- fractions((red*green*white)/pr_total)\r\nprint(trecolori)\r\n\r\n# Richiesta 6: ordine rosso, bianco, verde\r\n\r\nfinal <- fractions(red/total * white/(total-1) * green/(total-2))\r\nprint(final)\r\n\r\n", "meta": {"hexsha": "06cac524db6e9d7176461e76f96bbcd6fb744b93", "size": 829, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 15.r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio 15.r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio 15.r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.725, "max_line_length": 75, "alphanum_fraction": 0.6911942099, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358094, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7389262972772459}} {"text": "# ......................................................................................\n# ........Exercise 10. Introduction to the hypothesis testing, one-sample tests ........\n# ..........................Michal Béreš, Martina Litschmannová.........................\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# From interval estimates to hypothesis tests ####\n# \n# * What is a statistical hypothesis test? ####\n# \n# Let's have the following:\n# \n# - random variable X (for example men's height)\n# - selection from a random variable (height measurement of 30 men)\n# \n# Statistical testing of hypotheses decides the validity of statistical statement\n# (hypothesis) based on the data obtained:\n# \n# - $H_0$ - null hypotheses\n# - $H_A$ - alternative hypotheses\n# \n# For example:\n# \n# $H_0$: $\\mu_X = 175$\n# \n# $H_A$: $\\mu_X > 175$\n# \n# Since this is a statistical decision, it will always be tied to some level of\n# significance $\\alpha$. We can always reach only 2 different decisions:\n# \n# - I reject $H_0$ in favor of $H_A$\n# - this means that I claim that $H_0$ does not apply\n# - this decision is with the maximum error $\\alpha$(significance level, type I\n# error) - this means that we are able to influence the size of this error\n# - I don't reject $H_0$\n# - this means that I claim that due to the obtained data(selection) it is not\n# possible to reject $H_0$\n# - this decision is with error $\\beta$(type II error), this error is not directly\n# controllable and depends on the type of test used\n# \n# How hypothesis tests relate to interval estimates and how the level of significance\n# enters them will be shown in the next section.\n\n\n# * Interval estimation and significance level ####\n# \n\n\ndata = readxl::read_excel(\"data/uvod.xlsx\")\nhead(data)\n\noptions(repr.plot.width = 12) # width of graphs in Jupyter\npar(mfrow = c(1, 2)) # graph graph matrices 1x2\n\nboxplot(data$data)\nhist(data$data)\n\nmoments::skewness(data$data) # oblique\nmoments::kurtosis(data$data) - 3 # sharpness\n\nshapiro.test(data$data)$p.value # normality test\n\n\nlength(data$data)\nmean(data$data)\nsd(data$data)\n\n# We make a 95% interval estimate of the mean using a t-test:\n# \n\n\nt.test(data$data, alternative = \"two.sided\", conf.level = 0.95)$conf.int\n\n# Now imagine that we want to test the hypothesis:$H_0$: $\\mu = 100$$H_A$: $\\mu\n# \\neq 100$What would be the decision with respect to the calculated IO and so the\n# significance level $\\alpha = 0.05$?\n# \n# Well, confidence interval covers the value 100 with maximal error of 5% (confidence\n# 95%). Therefore, we can say we cannot reject this hypothesis at significance value 5%.\n\n\n# Let's further imagine that we want to test the hypothesis:$H_0$: $\\mu =\n# 105$$H_A$: $\\mu \\neq 105$What would be the decision with respect to the\n# calculated IO and so the significance level $\\alpha = 0.05$?\n# \n# Well, now its a different case: confidence interval does not cover the value 105 with\n# maximal error of 5% (confidence 95%). Therefore, we can say we can reject this\n# hypothesis at significance value 5%.\n\n\n# **What we just did is called a classic test.**\n# \n# We will show you more classic tests for one-sided alternatives.$H_0$: $\\mu =\n# 105$$H_A$: $\\mu > 105$\n# \n\n\nt.test(data$data, alternative = \"greater\", conf.level = 0.95)$conf.int\n\n# $H_0$: $\\mu = 105$$H_A$: $\\mu < 105$\n# \n\n\nt.test(data$data, alternative = \"less\", conf.level = 0.95)$conf.int\n\n# Note that the first of these one-sided alternatives led to a \"rejection\" of $H_0$.\n# This is because of the comparison of the unlikely $H_0$ with the even less likely\n# $H_A$.\n# \n# *** P-values and connection with CI ####\n# \n# An alternative to the classical test(where we create CI) is the so-called pure\n# significance test:\n\n\n# H_0: mu=105\n# H_A: mu<>105\nt.test(data$data, mu = 105, alternative = \"two.sided\")\n\nt.test(data$data, mu = 105, alternative = \"two.sided\")$p.value\n\n# The pure significance test results in a p-value. Based on it, we decide whether or not\n# to reject $H_0$.\n# \n# p-value can be understood as the highest possible level of significance, such that our\n# decision is - I do not reject. Thus, the CI/field of acceptance would contain the\n# examined value:\n\n\n# H_0: mu=105\n# H_A: mu<>105\n\np.hod = t.test(data$data, mu = 105, alternative = \"two.sided\")$p.value\np.hod\n\nt.test(data$data, alternative = \"two.sided\", conf.level = 1 - p.hod)$conf.int\n\n# H_0: mu=105\n# H_A: mu>105\n\np.hod = t.test(data$data, mu = 105, alternative = \"greater\")$p.value\np.hod\n\nt.test(data$data, alternative = \"greater\", conf.level = 1 - p.hod)$conf.int\n\n# H_0: mu=105\n# H_A: mu<105\n\np.hod = t.test(data$data, mu = 105, alternative = \"less\")$p.value\np.hod\n\nt.test(data$data, alternative = \"less\", conf.level = 1 - p.hod)$conf.int\n\n# * Overwiev of tests for one sample ####\n# \n# ** Position measures ####\n# \n# By position measures we mean the data that determines the position of the data. For\n# data from the normal distribution we can estimate the mean value, for others the\n# median.\n# \n# *** a) student's t-test ####\n# \n# - we test the mean value\n# - the data must come from a normal distribution\n# - exploratory: skewness and sharpness lie in(-2,2)\n# - exploratory: The QQ graph has points approximately on the line\n# - exact: using a statistical test, eg Shapiro-Wilk test(shapiro.test(data))\n\n\n# H_0: mu=100\n# H_A: mu<>100\nt.test(data$data, mu = 100, alternative = 'two.sided')$p.value\n\n# H_0: mu=100\n# H_A: mu>100\nt.test(data$data, mu = 100, alternative = 'greater')$p.value\n\n# H_0: mu=100\n# H_A: mu<100\nt.test(data$data, mu = 100, alternative = 'less')$p.value\n\n# *** b) Wilcoxn test ####\n# \n# - we test the median\n# - the data must come from a symmetric distribution\n# - exploratory: skewness lies in(-2,2)\n# - exploratory: histogram looks approximately symmetrical\n\n\n# H_0: X_0.5=100\n# H_A: X_0.5<>100\nwilcox.test(data$data, mu = 100, alternative = 'two.sided')$p.value\n\n# H_0: X_0.5=100\n# H_A: X_0.5>100\nwilcox.test(data$data, mu = 100, alternative = 'greater')$p.value\n\n# H_0: X_0.5=100\n# H_A: X_0.5<100\nwilcox.test(data$data, mu = 100, alternative = 'less')$p.value\n\n# *** c) sign test test ####\n# \n# - we test the median\n# - larger range selection(>10)\n# - requires \"BSDA\" library\n# - as the most robust test, it can also be used for discontinuous data\n\n\n# H_0: X_0.5=100\n# H_A: X_0.5<>100\nBSDA::SIGN.test(data$data, md = 100, alternative = 'two.sided')$p.value\n\n# H_0: X_0.5=100\n# H_A: X_0.5>100\nBSDA::SIGN.test(data$data, md = 100, alternative = 'greater')$p.value\n\n# H_0: X_0.5=100\n# H_A: X_0.5<100\nBSDA::SIGN.test(data$data, md = 100, alternative = 'less')$p.value\n\n# ** Variability measures ####\n# \n# By measures of variability we mean the data determining the dispersion/variability of\n# the data. For data from the normal distribution, we can estimate the standard\n# deviation.\n# \n# *** standard deviation test ####\n# \n# - we test the standard deviation\n# - the data must come from a normal distribution\n# - exploratory: skewness and kurtosis lie in(-2,2)\n# - Explosive: The QQ graph has points approximately on the line\n# - exact: using a statistical test, eg Shapiro-Wilk test(shapiro.test(data))\n# - requires \"EnvStats\" package\n# - function in R, compares variance !!!\n\n\n# H_0: sigma=10\n# H_A: sigma<>10\nEnvStats::varTest(data$data, sigma.squared = 10*10, \n alternative = 'two.sided')$p.value\n\n# H_0: sigma=10\n# H_A: sigma>10\nEnvStats::varTest(data$data, sigma.squared = 10*10, \n alternative = 'greater')$p.value\n\n# H_0: sigma=10\n# H_A: sigma<10\nEnvStats::varTest(data$data, sigma.squared = 10*10, \n alternative = 'less')$p.value\n\n# * Probability ####\n# \n# *** Test of probability ####\n# \n# - We test the probability\n# - We require sufficient data: $n>\\frac{9}{p(1-p)}$\n# - Clopper's - Pearson's estimate(binom.test)\n# - does not take data as a parameter, but the number of successes and the number of\n# observation\n\n\npi = 0.3\ndata_bin = runif(n = 100, min = 0, max = 1) < pi\n\nn = length(data_bin)\nx = sum(data_bin)\nn\nx\n\n# H_0: pi=0.2\n# H_A: pi<>0.2\nbinom.test(x = x, n = n, p = 0.2, alternative = 'two.sided')$p.value\n\n# H_0: pi=0.2\n# H_A: pi>0.2\nbinom.test(x = x, n = n, p = 0.2, alternative = 'greater')$p.value\n\n# H_0: pi=0.2\n# H_A: pi<0.2\nbinom.test(x = x, n = n, p = 0.2, alternative = 'less')$p.value\n\n# Examples ####\n\n\nlibrary(dplyr)\nlibrary(rstatix)\n\n# \n# * Example 1. ####\n# \n# We have a selection of 216 patients and we measured their protein serum(file\n# testy_jednovyberove.xlsx sheet bilk_serum). Verify that the average protein\n# serum(Albumin) of all patients of this type(population average µ) differs\n# statistically significantly from 35 g/l.\n\n\n# Reading data from xlsx file(using readxl package)\nalbumin = readxl::read_excel(\"data/testy_jednovyberove.xlsx\",\n sheet = \"bilk_serum\")\nhead(albumin)\n\ncolnames(albumin)=\"value\"\n\n# Exploratory analysis\nboxplot(albumin$value)\nsummary(albumin$value)\n\nlength(albumin$value) # sd is rounded to 3 valid digits\nsd(albumin$value) # sd and position measures are rounded to the nearest thousandth\n\n# **Position measurement test**\n# \n\n\n# Verification of normality - exploratory\nmoments::skewness(albumin$value) # skew\nmoments::kurtosis(albumin$value)-3 # sharpness\n\noptions(repr.plot.width = 12) # width of graphs in Jupyter\npar(mfrow = c(1, 2)) # matrix of 1x2 graphs\n\nqqnorm(albumin$value)\nqqline(albumin$value)\nhist(albumin$value)\n\n# We will use the normality test for the final decision on data normality.\n\n# The presumption of normality is verified by the Shapir - Wilk test.\n# H0: Data is a selection from the normal distribution.\n# Ha: Data is not a selection from the normal distribution.\nshapiro.test(albumin$value)\n# p-value>0.05 ->Na hl. significance of 0.05, the assumption of normality cannot be rejected.\n\n\n# normal OK ->t.test\n\n# H0: mu=35 g/l\n# Ha: mu<>35 g/l\n\nt.test(albumin$value, mu=35, alternative = \"two.sided\")\n\n# p-value<0.05 ->at significance level of 0.05 we reject the null hypothesis\n# in favor of the alternative hypothesis\n# The mean albumin value differs statistically significantly from 35 g/l.\n\n# * Example 2. ####\n# \n# Survival times for 100 lung cancer patients treated with the new drug are listed in\n# the tests_jednovyberove.xlsx sheet \"preziti\". It is known from previous studies that\n# the average survival of such patients without the administration of a new drug is 22.2\n# months. Can these data suggest that the new drug prolongs survival?\n# \n\n\n# Reading data from xlsx file(using readxl package)\npreziti = readxl::read_excel(\"data/testy_jednovyberove.xlsx\",\n sheet = \"preziti\") \nhead(preziti)\n\ncolnames(preziti)=\"value\"\n\n# # Exploratory analysis\npar(mfrow = c(1, 2)) # graph matrix 1x2\n\nboxplot(preziti$value)\nhist(preziti$value)\n\n# **Data contains outliars -> we can delete them. Or note that this is probably an\n# exponential distribution and the outliars are not actually there(the distribution\n# simply behaves this way.)**\n# \n\n\n# Data contains outliars. We can list them with the help of f-ce boxplot.\npreziti$ID = seq(1,length(preziti$value))\noutliers = preziti %>% identify_outliers(value)\noutliers\n# if we decided to remove outliers, then\npreziti$value_no_outliars = ifelse(preziti$ID %in% outliers$ID,NA,preziti$value)\n\n# Exploratory analysis for data without remote observations\nboxplot(preziti$value_no_outliars)\n\nlength(na.omit(preziti$value_no_outliars)) # sd is rounded to 3 valid digits\nsd(preziti$value_no_outliars,na.rm=TRUE) # sd and position measurements round. to tenths\n\n# **Position measure(mean/median) test**\n# \n\n\n# Verification of normality - exploratory\nmoments::skewness(preziti$value_no_outliars,na.rm=TRUE)\nmoments::kurtosis(preziti$value_no_outliars,na.rm=TRUE)-3\n\npar(mfrow = c(1, 2)) # graph matrix 1x2\n\nqqnorm(preziti$value_no_outliars)\nqqline(preziti$value_no_outliars)\nhist(preziti$value_no_outliars)\n\n# QQ - graph and history show that the choice of truth. is not a choice of standards. distribution.\n# Slanting and pointing corresponds to standards. distribution.\n# we will use the normality test.\n\n\n# We verify the assumption of normality by the Shapirs. Wilkov's test.\nshapiro.test(preziti$value_no_outliars)\n# p-value<0.05 ->at significance 0.05, we reject the assumption of normality\n\n\n# exploratory assessment of symmetry - exponential distribution - no symmetry\n\n# normality rejected ->symmetry rejected ->Sign. test\n# H0: median=22.2 months\n# Ha: median>22.2 months\n\nBSDA::SIGN.test(preziti$value_no_outliars, md=22.2,\n alternative=\"greater\")\n\n# p-value>0.05 -> at significance of 0.05, the null hypothesis cannot be rejected\n# Median survival time is not statistically significantly greater than 22.2 months.\n\nmedian(preziti$value_no_outliars, na.rm = TRUE)\n\n# * Example 3. ####\n# \n# The machine produces piston rings of a given diameter. The manufacturer states that\n# the standard deviation of the ring diameter is 0.05 mm. To verify this information, 80\n# rings were randomly selected and their diameter was measured(file\n# testy_jednovyberove.xlsx sheet krouzky). Can the results obtained be considered\n# statistically significant in terms of improving the quality of production?\n\n\n# Reading data from xlsx file(using readxl package)\nkrouzky = readxl::read_excel(\"data/testy_jednovyberove.xlsx\",\n sheet = \"krouzky\") \nhead(krouzky)\n\ncolnames(krouzky)=\"value\"\n\n# # Exploratory analysis\nboxplot(krouzky$value)\n\n# Data contains outliars. We can list them with the help of f-ce boxplot.\nkrouzky$ID = seq(1,length(krouzky$value))\noutliers = krouzky %>% identify_outliers(value)\noutliers\n# if we decided to remove outliers, then\nkrouzky$value_no_outliars = ifelse(krouzky$ID %in% outliers$ID,NA,krouzky$value)\n\n# Exploratory analysis for data without remote observations\nsummary(krouzky$value_no_outliars,na.rm=TRUE)\nboxplot(krouzky$value_no_outliars)\n\nlength(na.omit(krouzky$value_no_outliars))# sd is rounded to 3 valid digits\nsd(krouzky$value_no_outliars,na.rm=TRUE) # sd and position measures round. per thousandths\n\n\n# Verification of normality - exploratory\nmoments::skewness(krouzky$value_no_outliars,na.rm=TRUE)\nmoments::kurtosis(krouzky$value_no_outliars,na.rm=TRUE)-3\n\npar(mfrow = c(1, 2)) # matrix of 1x2 graphs\n\nqqnorm(krouzky$value_no_outliars)\nqqline(krouzky$value_no_outliars)\nhist(krouzky$value_no_outliars)\n# Both skew and sharpness comply with standards. distribution.\n# We will use for the final decision on data normality\n\n\n# normality test.\n# We verify the assumption of normality by the Shapirs. Wilkov's test.\nshapiro.test(krouzky$value_no_outliars)\n# p-value>0.05 ->Na hl. significance of 0.05 cannot be assumed norms. reject\n\n\n# variability test ->variance test\n\n# H0: sigma=0.05 mm\n# Ha: sigma<0.05 mm\nEnvStats::varTest(krouzky$value_no_outliars, sigma.squared = 0.05^2,\n alternative = \"less\")\n\n# p-value<0.05 ->At the significance level of 0.05 we reject H0 in favor of Ha\n\n\n# How to find a 95% interval standard deviation estimate?\npom = EnvStats::varTest(krouzky$value_no_outliars,sigma.squared = 0.05^2,\n alternative = \"less\", conf.level=0.95)\n\nsqrt(pom$conf.int)\n\n# * Example 4. ####\n# \n# TT states that 1% of their resistors do not meet the required criteria. 15 unsuitable\n# resistors were found in the tested delivery of 1000 pieces. Is this result with\n# agreement with TT's assertion or can we reject it? \n\n\nn = 1000 # selection range\nx = 15 # number of \"successes\"\np = x/n # relative frequency(probability point estimate)\np \n\n# Verification of assumptions\n9/(p*(1-p))\n\n# Clopper - Pearson(exact) test\n# H0: pi=0.01\n# Ha: pi<>0.01\n\nbinom.test(x = x, n= n, p = 0.01, alternative=\"two.sided\")\n\n", "meta": {"hexsha": "3053b60fd9d229817c2545f46e4335a2df451b33", "size": 16035, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 10/T12_hypothesis_testing1.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise 10/T12_hypothesis_testing1.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise 10/T12_hypothesis_testing1.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 30.7183908046, "max_line_length": 99, "alphanum_fraction": 0.6965388213, "num_tokens": 4667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7386856960636661}} {"text": "\r\n(1-0.7*0.7)^2\r\n0.1*0.51*0.51*0.1\r\n1-0.9*0.9*(1-0.2601)\r\n\r\n\r\nf = function(x){return(6*x-x^2)}\r\ndolniMez = 0\r\nhorniMez = 6\r\n1/integrate(f, dolniMez, horniMez)$value\r\n\r\nx = 6\r\n3*x^2-x^3/3\r\nx = 0\r\n3*x^2-x^3/3\r\n1/36\r\n\r\nf.dens = function(x){\r\n res = 1/36*(6*x-x^2) # 1/4(6*x+8)\r\n res[x < 0] = 0 \r\n res[x > 6] = 0 \r\n return(res)\r\n}\r\n\r\nF.dist = function(x){\r\n res = 1/36*(3*x^2-x^3/3)\r\n res[x < 0] = 0 \r\n res[x > 6] = 1 \r\n return(res)\r\n}\r\n\r\nx = seq(from = -1, to = 7, by = 0.01) \r\nfx = f.dens(x) \r\nplot(x, fx, cex = 0.2, main=\"Graf hustoty\") \r\n\r\nFX = cumsum(fx)\r\nFX = F.dist(x)\r\nplot(x, FX, cex = 0.2, main=\"Distribuční funkce\") \r\n\r\n\r\n1-F.dist(2)\r\n\r\n\r\ndata_xlsx = readxl::read_excel(\"./ZK1/data_123.xlsx\", \r\n sheet = \"Vysledky mereni\", \r\n skip = 0)\r\n\r\ndata = data_xlsx[,-1] \r\ncolnames(data) = c(\"prez\",\"dist\",\"typ\")\r\n\r\nboxplot(data$prez~data$typ)\r\nzaokr = data %>% group_by(typ) %>%\r\n summarise (pocet = sum(!is.na(prez)),\r\n prumer = round(mean(prez, na.rm = TRUE),0),\r\n smer.odch = ceiling(sd(prez, na.rm = TRUE)*100)/100)\r\ncolnames(zaokr) = c('Výrobce','Počet záznamů','Průměr','Směrodatná odchylka')\r\nzaokr %>% print.data.frame()\r\n\r\nnormSymet = data %>% group_by(typ) %>%\r\n summarise( sikmost=round(moments::skewness(prez, na.rm=TRUE),1),\r\n spicatost=round(moments::kurtosis(prez, na.rm=TRUE)-3,1),\r\n SW=round(shapiro.test(prez)$p.value,3),\r\n symetrie=round(lawstat::symmetry.test(prez, boot=FALSE)$p.value,3))\r\ncolnames(normSymet) = c('Výrobce','Šikmost','Špičatost','Shapirův-Wilkův test (p-hodnota)','Test symetrie (p-hodnota)')\r\nnormSymet %>% print.data.frame()\r\n\r\nodhady = data %>% group_by(typ) %>%\r\n summarise( median = round(median(prez, na.rm=TRUE),2),\r\n smer.odch = round(mean(prez, na.rm = TRUE)*100)/100,\r\n interval = paste0('(',\r\n floor(wilcox.test(prez, alternative = 'greater',conf.int=T,conf.level=0.93)$conf.int[1]*10)/10, \" ; \", \r\n ceiling(wilcox.test(prez, alternative = 'greater',conf.int=T,conf.level=0.93)$conf.int[2]*10)/10\r\n ,')'),\r\n denni.ztrata = round(t.test(prez,mu=8,alternative=\"greater\",conf.level=0.90)$p.value,3),\r\n\r\n )\r\ncolnames(odhady) = c('Typ','Bodový odhad (median)','Bodový odhad (str. hodnota)','93% intervalový odhad levostrany (wilcox)', 'denni ztrata')\r\nodhady %>% print.data.frame()\r\n\r\nwilcox.test(data$prez, alternative = 'less',conf.int=T)$conf.int\r\n\r\n\r\nwilcox.test(data$prez[data$typ==\"ekonomicky\"], mu = 35, alternative = 'greater',conf.level=0.93)$p.value\r\n\r\n\r\nwilcox.test(x = data$prez[data$typ==\"technicky\"], y = data$prez[data$typ==\"ekonomicky\"], alternative = \"two.sided\",\r\n conf.level=0.93, conf.int = TRUE)\r\n\r\n\r\nround(kruskal.test(data$dist ~ data$typ)$p.value,3)\r\n\r\n\r\ndunn.test::dunn.test(data$dist, data$typ, method=\"bonferroni\",altp=TRUE)\r\n# seřadit podle efektů\r\n\r\n\r\n# počítání efektů\r\n# průměry ve skupinách\r\nefekty = data %>% group_by(typ) %>% \r\n summarize(median_skup = median(dist, na.rm=T))\r\n\r\n# efekty\r\nefekty$efekt = efekty$median_skup - median(data$dist, na.rm=T)# celkový průměr\r\n\r\n# vypsat setřízené\r\nefekty %>% arrange(desc(efekt)) %>% print.data.frame()\r\n\r\n# NEZAPOMENOUT NA TEORETICKOU ČÁST", "meta": {"hexsha": "6fcab7b6f6553337fb23aa7872ffe5e44ec0b3f6", "size": 3343, "ext": "r", "lang": "R", "max_stars_repo_path": "ZK1/pokus1.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ZK1/pokus1.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ZK1/pokus1.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9537037037, "max_line_length": 142, "alphanum_fraction": 0.5815136105, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7386856881266212}} {"text": "histplus <- function(x, breaks=NULL, distribution='normal', sided=2, alpha=0.05, pvalue=0.95, nsigma=2) {\r\n ## plot histogram and normal distribution\r\n ## distribution = normal or Weibull\r\n ## sided = -1 (lower), 1 (upper), or 2 sided interval\r\n ## alpha = 1 - confidence (used in confidence, prediction, and tolerance intervals)\r\n confidence <- 1-alpha\r\n ## pvalue = % of data to be covered (used in tolerance interval)\r\n ## nsigma = number of standard deviations for mean +/- nsigma * standard deviation\r\n\r\n #### debug\r\n ## x <- mtcars$mpg\r\n ## distribution <- 'normal'\r\n ## sided <- 2\r\n ## alpha <- 0.05\r\n ## confidence <- 1-alpha\r\n ## pvalue <- 0.95\r\n ## nsigma <- 2\r\n ## breaks <- NULL\r\n\r\n ## calculate limits\r\n if (distribution=='Weibull') {\r\n ## not sure how to figure out other intervals for Weibull since mean and sd do not make sense\r\n tol_out <- exttol.int(x, alpha = alpha, P=pvalue, side=abs(sided))\r\n shape <- tol_out$'shape.1'\r\n scale <- tol_out$'shape.2'\r\n if (sided==-1) {\r\n lower_conf_limit <- NA # not sure how to do this\r\n lower_sigma <- NA # N/A \r\n lower_pred_limit <- NA # not sure how to do this\r\n lower_tolerance_limit <- tol_out$'1-sided.lower'\r\n upper_conf_limit <- NA # N/A \r\n upper_sigma <- NA # N/A \r\n upper_pred_limit <- NA # N/A \r\n upper_tolerance_limit <- NA # N/A \r\n } else if (sided==1) {\r\n lower_conf_limit <- NA # N/A \r\n lower_sigma <- NA # N/A \r\n lower_pred_limit <- NA # N/A \r\n lower_tolerance_limit <- NA # N/A \r\n upper_conf_limit <- NA # not sure how to do this\r\n upper_sigma <- NA # N/A \r\n upper_pred_limit <- NA # not sure how to do this\r\n upper_tolerance_limit <- tol_out$'1-sided.upper'\r\n } else { \r\n lower_conf_limit <- NA # not sure how to do this\r\n lower_sigma <- NA # N/A \r\n lower_pred_limit <- NA # not sure how to do this\r\n lower_tolerance_limit <- tol_out$'2-sided.lower'\r\n upper_conf_limit <- NA # not sure how to do this\r\n upper_sigma <- NA # N/A \r\n upper_pred_limit <- NA # not sure how to do this\r\n upper_tolerance_limit <- tol_out$'2-sided.upper'\r\n } \r\n } else { # normal distribution (default)\r\n xmean <- mean(x)\r\n xsd <- sd(x)\r\n tol_out <- normtol.int(x, alpha = alpha, P=pvalue, side=abs(sided))\r\n if (sided==-1) {\r\n student_t <- abs(qt(alpha, length(x)-1))\r\n lower_conf_limit <- xmean - student_t*xsd*( 1/length(x))^0.5\r\n lower_sigma <- xmean - nsigma*xsd\r\n lower_pred_limit <- xmean - student_t*xsd*(1+1/length(x))^0.5\r\n lower_tolerance_limit <- tol_out$'1-sided.lower'\r\n upper_conf_limit <- NA\r\n upper_sigma <- NA\r\n upper_pred_limit <- NA\r\n upper_tolerance_limit <- NA\r\n } else if (sided==1) {\r\n student_t <- abs(qt(alpha, length(x)-1))\r\n lower_conf_limit <- NA\r\n lower_sigma <- NA\r\n lower_pred_limit <- NA\r\n lower_tolerance_limit <- NA\r\n upper_conf_limit <- xmean + student_t*xsd*( 1/length(x))^0.5\r\n upper_sigma <- xmean + nsigma*xsd\r\n upper_pred_limit <- xmean + student_t*xsd*(1+1/length(x))^0.5\r\n upper_tolerance_limit <- tol_out$'1-sided.upper'\r\n } else {\r\n student_t <- abs(qt(alpha/2, length(x)-1))\r\n lower_conf_limit <- xmean - student_t*xsd*( 1/length(x))^0.5\r\n lower_sigma <- xmean - nsigma*xsd\r\n lower_pred_limit <- xmean - student_t*xsd*(1+1/length(x))^0.5\r\n lower_tolerance_limit <- tol_out$'2-sided.lower'\r\n upper_conf_limit <- xmean + student_t*xsd*( 1/length(x))^0.5\r\n upper_sigma <- xmean + nsigma*xsd\r\n upper_pred_limit <- xmean + student_t*xsd*(1+1/length(x))^0.5\r\n upper_tolerance_limit <- tol_out$'2-sided.upper'\r\n }\r\n } \r\n \r\n ## generate distribution\r\n xmin <- min(x,lower_sigma,lower_pred_limit,lower_tolerance_limit, na.rm=TRUE)\r\n xmax <- max(x,upper_sigma,upper_pred_limit,upper_tolerance_limit, na.rm=TRUE)\r\n chuncks <- (xmax-xmin)/1000\r\n xhist <- seq(xmin,xmax,by=chuncks)\r\n if (distribution=='Weibull') {\r\n xdensity <- dweibull(xhist,shape=shape,scale=scale)\r\n } else {\r\n xdensity <- dnorm(xhist,xmean,xsd)\r\n }\r\n xdensitymax <- max(xdensity)\r\n\r\n ## make histogram\r\n if (is.null(breaks)) {\r\n ## hist(x, xlim=c(xmin,xmax), freq=FALSE) # specifying xlim messes up axes\r\n hist(x, freq=FALSE)\r\n } else {\r\n hist(x, breaks=breaks, freq=FALSE)\r\n }\r\n ## add distribution\r\n lines(x=xhist, y=xdensity, col='red', lty=1)\r\n ## add lines for mean and limits\r\n if (distribution=='normal') abline(v=xmean,col=\"red\")\r\n abline(v=lower_conf_limit ,col=\"blue\")\r\n abline(v=lower_sigma ,col=\"darkviolet\", lty=2)\r\n abline(v=lower_pred_limit ,col=\"darkviolet\")\r\n abline(v=lower_tolerance_limit ,col=\"black\")\r\n abline(v=upper_conf_limit ,col=\"blue\")\r\n abline(v=upper_sigma ,col=\"darkviolet\", lty=2)\r\n abline(v=upper_pred_limit ,col=\"darkviolet\")\r\n abline(v=upper_tolerance_limit ,col=\"black\")\r\n cat(sided,\"sided\", distribution,\"distribution intervals\\n\")\r\n cat(\"nsigma =\",nsigma,\"\\n\")\r\n cat(\"confidence = 1 - alpha =\",confidence,\"\\n\")\r\n cat(\"coverage = pvalue =\",pvalue,\"\\n\")\r\n if (distribution=='Weibull') {\r\n cat(\"shape =\",shape,\"\\n\")\r\n cat(\"scale =\",scale,\"\\n\")\r\n interval <- c(\"confidence\", \"prediction\", \"tolerance\")\r\n df <- data.frame(interval)\r\n df$lower <- c(lower_conf_limit, lower_pred_limit, lower_tolerance_limit)\r\n df$upper <- c(upper_conf_limit, upper_pred_limit, upper_tolerance_limit)\r\n } else { # assume normal\r\n cat(\"mean =\",xmean,\"\\n\")\r\n cat(\"standard deviation =\",xsd,\"\\n\")\r\n interval <- c(\"confidence\", \"mean +/- nsigma * sd\", \"prediction\", \"tolerance\")\r\n df <- data.frame(interval)\r\n df$lower <- c(lower_conf_limit, lower_sigma, lower_pred_limit, lower_tolerance_limit)\r\n df$upper <- c(upper_conf_limit, upper_sigma, upper_pred_limit, upper_tolerance_limit)\r\n ## cat(\"mean =\", xmean, \"\\n\")\r\n ## cat(sided, \"sided upper\", confidence, \"confidence limit =\", upper_conf_limit,\"\\n\")\r\n ## cat(nsigma, \"sigma upper limit =\", upper_sigma , \"\\n\")\r\n ## cat(sided, \"sided\", confidence,\"upper prediction limit =\", upper_pred_limit, \"\\n\")\r\n ## cat(sided, \"sided\", confidence,\"/\",pvalue,\"upper tolerance limit =\", upper_tolerance_limit, \"\\n\")\r\n }\r\n print(df)\r\n}\r\n# histplus(mtcars$mpg)\r\n\r\n#--------------------------------\r\n\r\n", "meta": {"hexsha": "0f21ebde43d1c3d43c577b243f6a9fe6307797f6", "size": 7707, "ext": "r", "lang": "R", "max_stars_repo_path": "modules/histplus.r", "max_stars_repo_name": "TECComputing/R-setup", "max_stars_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/histplus.r", "max_issues_repo_name": "TECComputing/R-setup", "max_issues_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/histplus.r", "max_forks_repo_name": "TECComputing/R-setup", "max_forks_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.7039473684, "max_line_length": 113, "alphanum_fraction": 0.5131698456, "num_tokens": 1894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7386327873900678}} {"text": "# Define the global variables\n# p represents π\n# a represents the counter in the Nilakantha Series\n# s determines whether to add or subtract\np <- 3\na <- 2\ns <- 1\n\n# Define the iteration function\niterate <- function() {\n # I had to use the <<- assignment operator since it is a global variable \n p <<- p + s * (4 / (a * (a * (a + 3) + 2)))\n a <<- a + 2\n s <<- -s\n}\n\n# Define counter variable\ni <- 0\n# Begin while loop\nwhile(i < 150000) {\n # Iterate Nilakantha Series\n iterate()\n # Increment counter variable\n i <<- i + 1\n}\n\n# I could have done a repeat loop, but while is easier.\n# What the repeat loop would be like:\n\"\nrepeat {\n iterate()\n if(i >= 150000) {\n break\n }\n i <<- i + 1\n}\n\"\n\n\n# Print result\nprint ( paste(\"pi =\", p))\n", "meta": {"hexsha": "3cd2afe7de083a50837363e497ad88b6611da358", "size": 743, "ext": "r", "lang": "R", "max_stars_repo_path": "r/main.r", "max_stars_repo_name": "amazinigmech2418/Pi-in-Many-Languages", "max_stars_repo_head_hexsha": "233fda961a90ad4f81926df1735a244c012f9766", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-06-19T04:45:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T22:31:58.000Z", "max_issues_repo_path": "r/main.r", "max_issues_repo_name": "amazinigmech2418/Pi-in-Many-Languages", "max_issues_repo_head_hexsha": "233fda961a90ad4f81926df1735a244c012f9766", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-23T16:19:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T16:19:45.000Z", "max_forks_repo_path": "r/main.r", "max_forks_repo_name": "amazinigmech2418/Pi-in-Many-Languages", "max_forks_repo_head_hexsha": "233fda961a90ad4f81926df1735a244c012f9766", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-08T12:37:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T12:37:44.000Z", "avg_line_length": 17.6904761905, "max_line_length": 75, "alphanum_fraction": 0.6123822342, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7386327751867947}} {"text": "\r\n\r\n# Goal: Joint distributions, marginal distributions, useful tables.\r\n\r\n# First let me invent some fake data\r\nset.seed(102) # This yields a good illustration.\r\nx <- sample(1:3, 15, replace=TRUE)\r\neducation <- factor(x, labels=c(\"None\", \"School\", \"College\"))\r\nx <- sample(1:2, 15, replace=TRUE)\r\ngender <- factor(x, labels=c(\"Male\", \"Female\"))\r\nage <- runif(15, min=20,max=60)\r\n\r\nD <- data.frame(age, gender, education)\r\nrm(x,age,gender,education)\r\nprint(D)\r\n\r\n# Table about education\r\ntable(D$education)\r\n\r\n# Table about education and gender --\r\ntable(D$gender, D$education)\r\n# Joint distribution of education and gender --\r\ntable(D$gender, D$education)/nrow(D)\r\n\r\n# Add in the marginal distributions also\r\naddmargins(table(D$gender, D$education))\r\naddmargins(table(D$gender, D$education))/nrow(D)\r\n\r\n# Generate a good LaTeX table out of it --\r\nlibrary(xtable)\r\nxtable(addmargins(table(D$gender, D$education))/nrow(D),\r\n digits=c(0,2,2,2,2)) # You have to do | and \\hline manually.\r\n\r\n# Study age by education category\r\nby(D$age, D$gender, mean)\r\nby(D$age, D$gender, sd)\r\nby(D$age, D$gender, summary)\r\n\r\n# Two-way table showing average age depending on education & gender\r\na <- matrix(by(D$age, list(D$gender, D$education), mean), nrow=2)\r\nrownames(a) <- levels(D$gender)\r\ncolnames(a) <- levels(D$education)\r\nprint(a)\r\n# or, of course,\r\nprint(xtable(a))\r\n\r\n", "meta": {"hexsha": "4864e6901410344fd5b3e88308a40f511959050a", "size": 1404, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p5.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p5.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p5.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8723404255, "max_line_length": 80, "alphanum_fraction": 0.665954416, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7385102858871452}} {"text": "## Dale W.R. Rosenthal, 2018\n## You are free to distribute and use this code so long as you attribute\n## it to me or cite the text.\n## The legal disclaimer in _A Quantitative Primer on Investments with R_\n## applies to this code. Use or distribution without these comment lines\n## is forbidden.\n\noz.per.year <- 10000\nrf <- 0.03 # 3% interest rates\nwacc <- 0.08 # 8% weighted average cost of capital\nnum.sims <- 100000 # 100,000 simulations\ns0 <- 1300 # gold price at t=0\nK <- 1000 # cost of extraction\nsigma <- 0.3 # volatility of gold log-returns\nlambda <- 1 # rate of mean reversion; 1 => half-life = ln(2) = 0.69 years\n\n## Annual extraction decisions at start of each year (t=0,...,9)\nT.list <- 1:9 # 1--9 year options; years 2:8 are 1 year fwd\ns.bar.list <- c(1300, rep(1200, 8)) # 1300/oz, then 1200/oz\n\n# gold price follows geometric Brownian motion\nsum.val <- (s0-K)/(1+wacc) # time t=0 decision\nfor (i in 1:9) {\n T <- T.list[i]\n z <- rnorm(num.sims) # simulated Z_T values\n s.sim <- s0*exp((rf-sigma^2/2)*T+sigma*sqrt(T)*z)\n if (T>1) s.sim <- s.sim*s.bar.list[i]/s0\n opt.terminal.val.sim <- pmax(s.sim - K, 0)\n opt.value <- mean(opt.terminal.val.sim)*exp(-rf*T)\n sum.val <- sum.val + opt.value/(1+wacc)\n}\nprint(sum.val*oz.per.year)\n\n## gold price follows Ornstein-Uhlenbeck mean reversion\nsum.val <- (s0-K)/(1+wacc)\nfor (i in 1:9) {\n T <- T.list[i]\n s.bar <- s.bar.list[i]\n s.meanrevert.sim <- s.bar + exp(-lambda*T)*(s0-s.bar) + sigma*s0*\n sqrt((1-exp(-2*lambda*T))/(2*lambda))*z\n opt.terminal.val.meanrevert.sim <- pmax(s.meanrevert.sim - K, 0)\n opt.meanrevert.value <- mean(opt.terminal.val.meanrevert.sim)*\n exp(-rf*T)\n sum.val <- sum.val + opt.meanrevert.value/(1+wacc)\n}\nprint(sum.val*oz.per.year)\n\n## Quarterly extract decisions at start of each quarter\nT.list <- (1:39)/4 # 1--39 quarter options\ns.bar.list <- c(rep(1300, 4), 1275, 1250, 1225, rep(1200, 32))\n\n# gold price follows geometric Brownian motion\nsum.val <- (s0-K)/(1+wacc)^0.25\nfor (i in 1:39) {\n T <- T.list[i]\n z <- rnorm(num.sims) # simulated Z_T values\n s.sim <- s0*exp(sigma*sqrt(T)*z)\n opt.terminal.val.sim <- pmax(s.sim - K, 0)\n opt.value <- mean(opt.terminal.val.sim)*exp(-rf*T)\n sum.val <- sum.val + opt.value/(1+wacc)^0.25\n}\nprint(sum.val*oz.per.year/4)\n\n# gold price follows Ornstein-Uhlenbeck mean reversion\nsum.val <- (s0-K)/(1+wacc)^0.25\nfor (i in 1:39) {\n T <- T.list[i]\n s.bar <- s.bar.list[i]\n s.meanrevert.sim <- s.bar + exp(-lambda*T)*(s0-s.bar) + sigma*s0*\n sqrt((1-exp(-2*lambda*T))/(2*lambda))*z\n opt.terminal.val.meanrevert.sim <- pmax(s.meanrevert.sim - K, 0)\n opt.meanrevert.value <- mean(opt.terminal.val.meanrevert.sim)*exp(-rf*T)\n sum.val <- sum.val + opt.meanrevert.value/(1+wacc)^0.25\n}\nprint(sum.val*oz.per.year/4)\n", "meta": {"hexsha": "db6678ff860bcc720c42309ddffd30af98e9bf17", "size": 2829, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch21-gold-mine-simulations.r", "max_stars_repo_name": "bmoretz/Quantitative-Investments", "max_stars_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-26T05:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T21:50:54.000Z", "max_issues_repo_path": "Quantitative Primer/samples/ch21-gold-mine-simulations.r", "max_issues_repo_name": "bmoretz/Quantitative-Investments", "max_issues_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quantitative Primer/samples/ch21-gold-mine-simulations.r", "max_forks_repo_name": "bmoretz/Quantitative-Investments", "max_forks_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-03T09:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:50:55.000Z", "avg_line_length": 37.2236842105, "max_line_length": 76, "alphanum_fraction": 0.6376811594, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7383386823010051}} {"text": "nm <- 1\ntemp <- 1\nsum <- 0\n\nwhile (nm < 4000000) {\n tp <- nm\n nm <- nm + temp\n temp <- tp\n if (nm %% 2 == 0) {\n sum <- nm + sum\n }\n}\n\nprint(sum)", "meta": {"hexsha": "9d9a9a99c1c2ed065825017a2a26608c4c75eb6c", "size": 166, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Problem2.r", "max_stars_repo_name": "nuhfurkan/projectEuler", "max_stars_repo_head_hexsha": "f29ca583154b15bdbe527152a2df3909ed0d3332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/Problem2.r", "max_issues_repo_name": "nuhfurkan/projectEuler", "max_issues_repo_head_hexsha": "f29ca583154b15bdbe527152a2df3909ed0d3332", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/Problem2.r", "max_forks_repo_name": "nuhfurkan/projectEuler", "max_forks_repo_head_hexsha": "f29ca583154b15bdbe527152a2df3909ed0d3332", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.8571428571, "max_line_length": 23, "alphanum_fraction": 0.3975903614, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7379994343253207}} {"text": "# Synthetic Data Project\r\n# Laplace probability functions\r\n\r\n# Author:\r\n# Version: 5/14/2017\r\n\r\n# Copyright 2017\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\r\n# associated documentation files (the \"Software\"), to deal in the Software without restriction, including\r\n# without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the\r\n# following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all copies or substantial\r\n# portions of the Software.\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\r\n# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n# density\r\ndlaplace <- function(x, m, lambda, log=F)\r\n # evaluate Laplace density (double-sided exponential)\r\n # f(x, m, lambda) =\r\n # x=m: lambda/2 * exp[-lambda*(x-m)]\r\n # note that, by custom, 1/lambda is used in the pdf definition\r\n if(!log) {\r\n exp(-abs(x-m)/lambda)/2/lambda\r\n } else {\r\n -log(2*lambda)-abs(x-m)/lambda\r\n }\r\n\r\n# cumulative density\r\nplaplace <- function(x, m, lambda) {\r\n # evaluate Laplace cumulative density (double-sided exponential)\r\n # F(x, m, lambda) =\r\n # x=m: 1/2+Fexp(m-x, lambda)/2 = 1/2+(1-exp[-lambda*(x-m)])/2\r\n # = 1/2*(1+1-exp[-lambda*(x-m)]) = (2-exp[-lambda*(x-m)])/2\r\n # note that, by custom, 1/lambda is used in the pdf definition\r\n i <- ifelse(x=m: -ln(2-2p)/lambda+m\r\n # note that, by custom, 1/lambda is used in the pdf definition\r\n i <- ifelse(p<.5, 1, -1)\r\n i*log(1-i+i*2*p)*lambda+m\r\n}\r\n\r\n# random Laplace quantiles\r\nrlaplace <- function(n, m, lambda)\r\n qlaplace(runif(n), m, lambda)\r\n", "meta": {"hexsha": "3ddb5fc192da9734364425728c60b84cf6655d61", "size": 2525, "ext": "r", "lang": "R", "max_stars_repo_path": "VerificationServer/LaplaceDistribution.r", "max_stars_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_stars_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VerificationServer/LaplaceDistribution.r", "max_issues_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_issues_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VerificationServer/LaplaceDistribution.r", "max_forks_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_forks_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0793650794, "max_line_length": 107, "alphanum_fraction": 0.6681188119, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.8723473730188543, "lm_q1q2_score": 0.737955676463873}} {"text": "# Normal Approximation to the Binomial\r\n# number of trails\r\nn<-1000\r\n# probability of success of single event\r\nz<-0.5\r\nMean<-n*z\r\ns<-sqrt(n*z*(1-z))\r\n # the probability of observing 460 or fewer\r\npnorm(460,mean=Mean,sd=s)\r\n", "meta": {"hexsha": "dd39b6520c6d4b905da3a8b909b7da5ff832d625", "size": 224, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.25/Ex4_25.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.25/Ex4_25.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.25/Ex4_25.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 22.4, "max_line_length": 46, "alphanum_fraction": 0.6964285714, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.737905366336891}} {"text": "par(mar=c(5.1, 4.1, 4.1, 7),xpd=TRUE)\n\n\n\nplot(0,type=\"n\",\n\n xlim=c(0,100),ylim=c(0,0.15),ann=FALSE)\n\n\n\np=c(0.1,0.3,0.5,0.7,0.9)\n\n\n\nfor (i in 1:length(p))\n\n{\n\n x=1:100\n\n y=dbinom(x,100,p[i])\n\n points(x,y,type=\"l\",col=rainbow(length(p))[i])\n\n}\n\n\ntitle(main=\"PMF of binom\",xlab=\"x\",ylab=\"p(x)\",cex.main=2,cex.lab=1.2)\n\nbox(\"outer\",col=\"gray\")\n\nlegend(\"topright\",inset=c(-0.23,0), legend=paste(\"p=\",p),col=rainbow(length(p)),lty=1)", "meta": {"hexsha": "00d5c758ad03a99ff1198e4d69d4a557d338d8e6", "size": 434, "ext": "r", "lang": "R", "max_stars_repo_path": "Programming/python/theory/binary_distribution.r", "max_stars_repo_name": "kwangjunechoi7/TIL", "max_stars_repo_head_hexsha": "99403791eb77fd9190d7d6f60ade67bb48122b33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Programming/python/theory/binary_distribution.r", "max_issues_repo_name": "kwangjunechoi7/TIL", "max_issues_repo_head_hexsha": "99403791eb77fd9190d7d6f60ade67bb48122b33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Programming/python/theory/binary_distribution.r", "max_forks_repo_name": "kwangjunechoi7/TIL", "max_forks_repo_head_hexsha": "99403791eb77fd9190d7d6f60ade67bb48122b33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.5625, "max_line_length": 86, "alphanum_fraction": 0.5783410138, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7377198596527753}} {"text": "#####\n# plots exponential decay curves \n# for the number of new child speakers of Mongolian \n# over the next 5 generations,\n# contrasting the observed rate of shift in the data\n# against a hypothetical faster rate\n# takes no inputs: data is coded into script\n####\n\nrm(list=ls())\nlibrary(ggplot2)\n\n# exponential decay constant λ\n# where p is the proportional decline per unit of time\n# p is positive\nlambda <- function(p){-log(1-p)}\n\n# exponential decay function \n# where t is time (generations)\ndecay <- function(p,t){exp(-lambda(p)*t)}\n\n# set two possible values for p:\n# observed p(B1,C2|B1) = 0.165\n # this comes from the actual data analysis\n# counterfactual p(B1,C2|B1) = 0.423\n # this comes from a hypothetical fake dataset\n # see Puthuval (2017) for explanation \nlowball <- function(x){decay(0.165, x)} # observed\nhighball <- function(x){decay(0.423, x)} # counterfactual\n\n# plot the curves\nbaseplot <-\n ggplot(data.frame(x=c(0,6)), aes(x=x)) + \n \tstat_function(fun=lowball, geom=\"path\", size=1.5) + \n ylim(0, 1) + xlim(0,5) +\n labs(x=\"Generations\", y=\"New child speakers of Mongolian\") +\n ggtitle(paste0(\"Decline in new child speakers over five generations,\",\n \"\\nassuming a constant rate of shift\"))\n# stat_function calculates at 101 points along x range by default\n \none <- baseplot +\n annotate(\"text\", x=3, y=.75, label=\"Rate of shift = 0.165\", size=5)\n\ntwo <- baseplot +\n stat_function(\n fun=highball, geom=\"path\", size=1.5, linetype=\"dotdash\") + \n annotate(\"text\", x=3, y=.75, \n \tlabel=\"Observed rate = 0.165\", size=5) +\n annotate(\"text\", x=2.5, y=.07, \n \tlabel=\"Counterfactual rate = 0.423\", size=5)\n\nplots <- c(\"one\", \"two\")\nprefix <- \"figures/expdecay_\"\nl <- mget(plots)\n\ninvisible(mapply(ggsave, \n\tfile=paste0(prefix, names(l), \".pdf\"), \n\twidth=6, height=4, units=\"in\", plot=l))\ninvisible(mapply(ggsave, \n\tfile=paste0(prefix, names(l), \".jpg\"), \n\twidth=6, height=4, units=\"in\", plot=l))\n", "meta": {"hexsha": "cb709fe4d4e7523d6f4c8d20c9b9425f5662cfae", "size": 1944, "ext": "r", "lang": "R", "max_stars_repo_path": "expdecay.r", "max_stars_repo_name": "saralakumari/lmsim", "max_stars_repo_head_hexsha": "802f013f72fc023728b1b8dad36f0dbd34b1cb9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "expdecay.r", "max_issues_repo_name": "saralakumari/lmsim", "max_issues_repo_head_hexsha": "802f013f72fc023728b1b8dad36f0dbd34b1cb9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "expdecay.r", "max_forks_repo_name": "saralakumari/lmsim", "max_forks_repo_head_hexsha": "802f013f72fc023728b1b8dad36f0dbd34b1cb9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3548387097, "max_line_length": 72, "alphanum_fraction": 0.6728395062, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7376646433298603}} {"text": "## Dale W.R. Rosenthal, 2018\n## You are free to distribute and use this code so long as you attribute\n## it to me or cite the text.\n## The legal disclaimer in _A Quantitative Primer on Investments with R_\n## applies to this code. Use or distribution without these comment lines\n## is forbidden.\n\n## empirical\nalpha <- 0.05 # probability mass in the loss tail\n# sort the data; grab the lowest alpha fraction of the data\nsorted.x.obs <- sort(x.obs)\nfrac.idx <- length(sorted.x.obs)*alpha\nleft.idx <- floor(frac.idx)\n\n# VaR is linearly interpolated between points\nrfrac <- 1-(frac.idx-left.idx)\nVaR.emp <- sorted.x.obs[left.idx:(left.idx+1)] %*% c(1-rfrac, rfrac)\n\n# ES is just the average of the observed data in the tail\nes.emp <- mean(sorted.x.obs[1:left.idx])\n\n## parametric\nVaR.norm <- mean.obs + sqrt(var.obs)*qnorm(alpha)\nes.norm <- mean.obs - sqrt(var.obs)*dnorm(qnorm(alpha))/alpha\n\n## from kernel density estimate\n# create the kernel density estimate\nkde <- density(x.obs, kernel=\"gaussian\", bw=\"SJ\")\n\n# now create numerical CDF\nint.kde <- cumsum(kde$y)/sum(kde$y)\n\n# Find where alpha is in loss tail\nleft.idx <- findInterval(alpha, int.kde)\n\n# linearly interpolate to find VaR\nrfrac <- (alpha-int.kde[left.idx])/(int.kde[left.idx+1]-int.kde[left.idx])\nVaR.kde <- kde$x[left.idx:(left.idx+1)] %*% c(1-rfrac, rfrac)\n\n# numerically integrate kernel density estimate to get ES (a bit hacky)\nes.kde <- kde$x[1:left.idx] %*% kde$y[1:left.idx]/sum(kde$y)/alpha\n\n## from Edgeworth expansion - exact\n# this function returns the \"CDF\" of the Edgeworth expansion\nint.left.edge <- function(q, mu, sigma, skew=0, exkurt=0) {\n z <- (q-mu)/sigma\n pnorm(z) - dnorm(z)*(skew*(z^2+1)/6 + exkurt*(z^3-3*z)/24\n + skew^2*(z^5-10*z^3+15*z)/72)\n}\n\n# returns the \"conditional expectation\" of the Edgeworth expansion\nexp.left.edge <- function(q, mu, sigma, skew=0, exkurt=0) {\n z <- (q-mu)/sigma\n mu - sigma/alpha*dnorm(z)*(1 + skew*(z^3)/6 + exkurt*(z^4-2*z^2-1)/24\n + skew^2*(z^6-9*z^4+9*z^2+3)/72)\n}\n\n# Find the point where the area under the left tail equals alpha\n# Do this by shifting the integral down by alpha to find where it\n# crosses zero (i.e. where the integral equals alpha)\nint.left.edge.shifted <- function(q) {\n int.left.edge(q, mean.obs, sqrt(var.obs), skew.obs, exkurt.obs) - alpha\n}\nfind.VaR <- uniroot(int.left.edge.shifted, check.conv = TRUE,\n lower=-1, upper=mean.obs)\n\n# The VaR is that point; the ES is the integral up to that point\nVaR.edge.exact <-find.VaR$root\nes.edge.exact <- exp.left.edge(VaR.edge.exact, mean.obs, sqrt(var.obs),\n skew.obs, exkurt.obs)\n\n## from Edgeworth expansion - numeric\n# Alternately, just use numeric integration on the Edgeworth\n# expansion points we got from the moments\n\n# create numeric \"CDF\"\nint.edge <- cumsum(edge.expand$approx)/sum(edge.expand$approx)\n\n# linearly interpolate to find VaR\nleft.idx <- which(int.edge>alpha)[1] - 1\nrfrac <- (alpha-int.edge[left.idx])/(int.edge[left.idx+1]-int.edge[left.idx])\nVaR.edge.num <- edge.expand$y[left.idx:(left.idx+1)] %*% c(1-rfrac, rfrac)\n\n# numerically integrate Edgeworth expansion to get ES\nes.edge.num <- edge.expand$y[1:left.idx] %*% edge.expand$approx[1:left.idx]/\n sum(edge.expand$approx)/alpha\n\n## from Cornish-Fisher expansion\nVaR.cornfish <- VaR(x.obs, p=0.05, method=\"modified\", mu=mean.obs, sigma=var.obs,\n m3=skew.obs, m4=exkurt.obs)\nes.cornfish <- ES(x.obs, p=0.05, method=\"modified\", mu=mean.obs, sigma=var.obs,\n m3=skew.obs, m4=exkurt.obs)\n\n## from EVT\nlibrary(evir)\n\n#evir package looks at upper tail, so flip returns\nx.neg.obs <- -x.obs\n\n# First, work with the generalized extreme value distribution\ngev.model <- gev(x.neg.obs, block=23)\nq.gev <- function(p) {\n -1*qgev(1-p, xi=gev.model$par.ests[[\"xi\"]],\n mu=gev.model$par.ests[[\"mu\"]],\n sigma=gev.model$par.ests[[\"sigma\"]])\n}\nVaR.gev <- q.gev(alpha) # use evir function\n# a bit hacky: numerically integrate CDF to get ES\nes.gev <- mean(q.gev(seq(0.001, alpha, 0.001)))\n\n# Next, work with the generalized Pareto distribution\ngpd.model <- gpd(x.neg.obs, nextremes=5)\nriskmeasures(gpd.model, c(0.95))\n\n## comparison\n# now create the exact CDF\nt.df <- 5\np.t <- function(q) {\n z1 <- (q+0.05)/desired.sd*t5.sd\n z2 <- (q-0.05)/desired.sd*t5.sd\n pt(z1, df=5)*3/5 + pt(z2, df=5)*2/5\n}\n\n# shift CDF down to find the point where alpha is in the loss tail\np.t.quantile <- uniroot(function(q) p.t(q)-alpha, check.conv=TRUE,\n lower=-1, upper=mean.obs)\nVaR.true <- p.t.quantile$root\n\n# function finds ES for a t-distribution to left of quantile q\nes.t <- function(q) {\n -dt(qt(q, df=t.df), df=t.df)/q*(t.df-2+qt(q, df=t.df)^2)/(t.df-1)\n}\n\n# ES calculation is crusty: we found point for alpha in loss tail.\n# Now find ES for both t-distributions; then find average of them\nq1 <- pt((VaR.true+0.05)/desired.sd*t5.sd, df=t.df)\nq2 <- pt((VaR.true-0.05)/desired.sd*t5.sd, df=t.df)\nes.true <- (3/5*es.t(q1) + 2/5*es.t(q2))*desired.sd/t5.sd - 0.01\n", "meta": {"hexsha": "3595d6e3267e34bffdff870b35b2f4b815e3c159", "size": 5103, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch8-examples-section-7.r", "max_stars_repo_name": "bmoretz/Quantitative-Investments", "max_stars_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-26T05:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T21:50:54.000Z", "max_issues_repo_path": "Quantitative Primer/samples/ch8-examples-section-7.r", "max_issues_repo_name": "bmoretz/Quantitative-Investments", "max_issues_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quantitative Primer/samples/ch8-examples-section-7.r", "max_forks_repo_name": "bmoretz/Quantitative-Investments", "max_forks_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-03T09:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:50:55.000Z", "avg_line_length": 36.7122302158, "max_line_length": 81, "alphanum_fraction": 0.6607877719, "num_tokens": 1611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7376377803463056}} {"text": "library(gmp)\n\nleft_factorial <- function(n) {\n\tif (n == 0) return(0)\n\tresult <- as.bigz(0)\n\n\tadder <- as.bigz(1)\t\n\tfor (k in 1:n) {\n\t\tresult <- result + adder\n\t\tadder <- adder * k\n\t}\n\tresult\n}\n\ndigit_count <- function(n) {\n\tnchar(as.character(n))\n}\n\nfor (n in 0:10) {\n\tcat(\"!\",n,\" = \",sep = \"\")\n\tcat(as.character(left_factorial(n)))\n\tcat(\"\\n\")\n}\nfor (n in seq(20,110,10)) {\n\tcat(\"!\",n,\" = \",sep = \"\")\n\tcat(as.character(left_factorial(n)))\n\tcat(\"\\n\")\n}\nfor (n in seq(1000,10000,1000)) {\n cat(\"!\",n,\" has \",digit_count(left_factorial(n)),\" digits\\n\", sep = \"\")\n}\n", "meta": {"hexsha": "080ad7853f8b38159d690c4e5a3b33bc5fbc15f2", "size": 562, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Left-factorials/R/left-factorials.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Left-factorials/R/left-factorials.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Left-factorials/R/left-factorials.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5625, "max_line_length": 73, "alphanum_fraction": 0.5658362989, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7375932639707442}} {"text": "library(deSolve)\nlibrary(reshape2)\nlibrary(ggplot2)\nlibrary(scales)\n\n\n#Anderson and May (1978) Model F eqn (19)-(21)\nHPL_ode <- function(times,init,parms){\n with(as.list(c(parms,init)), {\n # ODEs\n dH=(a-b)*H - alpha*P\n dP=(beta*L*H) - (mu+alpha+b)*P - (alpha*((P^2)/H)*((k+1)/k))\n dL=(lambda*P) - (gamma*L) - (beta*L*H)\n \n list(c(dH,dP,dL))\n })\n}\n\n# L= number of free-living (infective) stages (e.g. larvae)\n# H = number of hosts\n# P = number of parasites\n# a = host birth rate\n# b = host death rate\n# alpha = parasite impact on host mortality\n# beta*l = rate at which hosts pick up infecting stages\n# mu = parasite death rate\n# k = aggregation parameter\n# lambda*P = rate of production of new free-living stages (i.e. parasite fertility)\n# gamma = death rate of free-living stages\n\nparms <-c(b=1.05,a=1.4,alpha=0.0003,beta=0.01,mu=0.5,k=0.1,lambda=10.0,gamma=10.0)\n\ninit <- c(H=100,P=10,L=10)\ntimes <- seq(0,30,length.out=2001)\nHPL_out <- lsoda(init,times,HPL_ode,parms)\n\nHPL_out_long <- melt(as.data.frame(HPL_out),\"time\")\n\n#Visualisation\nggplot(HPL_out_long,aes(x=time,y=value,colour=variable,group=variable)) +\n geom_line(lwd=2) + xlab(\"Time\") + ylab(\"Number\") + scale_y_log10(breaks = trans_breaks(\"log10\", function(x) 10^x),\n labels = trans_format(\"log10\", math_format(10^.x)))\n", "meta": {"hexsha": "58049d6ef480f081edb9c3c602a769283221d14e", "size": 1306, "ext": "r", "lang": "R", "max_stars_repo_path": "models/microparasite_models/may_anderson_1978.r", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/microparasite_models/may_anderson_1978.r", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/microparasite_models/may_anderson_1978.r", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 30.3720930233, "max_line_length": 116, "alphanum_fraction": 0.6707503828, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644807, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7375932523379496}} {"text": "#----------------------------------------------------------------------------\n# frmAmpCorr -- Formant Amplitude Correction\n#\n# The amplitude of a resonator is proportional to both its frequency and\n# bandwidth. This function is designed to calculate a scaling factor that\n# will compensate both frequency and bandwidth factors to result in unit\n# amplitude at the resonator center frequency (i.e. amplitude = 1.0 at\n# the resonator characteristic frequency).\n#\n# The amplitude at the resonant frequency is inversely proportional to the\n# bandwidth plus a constant offset that is a nonlinear function of the\n# bandwidth. The latter function is approximated here via a 4th order\n# polynomial.\n#\n# See also: function formant() that calculates the discrete spectrum of the\n# resonator impulse response given the resonator frequency and bandwidth as\n# well as the bandwidth of the spectrum and the number of discrete spectral\n# bins. The formant function now also includes a scale argument that\n# defaults to FALSE for compatibility with previous versions of the function.\n# If scale=TRUE, the amplitude spectrum is scaled to have unit gain at the\n# resonator frequency.\n#\n# 12/23/19 -- htb\n#---------------------------------------------------------------------------\n#\nfrmAmpCorr <- function(freq, band) {\n coe <- c(-1.683882e-03,4.234928e-04,-1.231765e-07,2.421068e-11,-2.066097e-15)\n m <- 1.0 / band\n b <- coe[1] + coe[2]*band + coe[3]*band^2 + coe[4]*band^3 + coe[5]*band^4\n# cat(paste0(\"m = \",m,\"; b = \",b,\"\\n\"))\n amp <- m*freq + b\n return(amp)\n}\n", "meta": {"hexsha": "948611e494f37206e45edd090da7978757b0079a", "size": 1553, "ext": "r", "lang": "R", "max_stars_repo_path": "R/frmAmpCorr.r", "max_stars_repo_name": "NemoursResearch/FormantTracking", "max_stars_repo_head_hexsha": "7053e6add8672dc00aa70f6549d90ff935f96748", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:47:04.000Z", "max_issues_repo_path": "R/frmAmpCorr.r", "max_issues_repo_name": "NemoursResearch/FormantTracking", "max_issues_repo_head_hexsha": "7053e6add8672dc00aa70f6549d90ff935f96748", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/frmAmpCorr.r", "max_forks_repo_name": "NemoursResearch/FormantTracking", "max_forks_repo_head_hexsha": "7053e6add8672dc00aa70f6549d90ff935f96748", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-31T18:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T18:20:28.000Z", "avg_line_length": 45.6764705882, "max_line_length": 79, "alphanum_fraction": 0.6670959433, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.737524447686185}} {"text": "#' puntomedio() calcula el punto medio entre 2 puntos\n#'\n#' @param a vector\n#' @param b vector\n#'\n#' @return vector\n#' @export\n#'\n#' @examples\n#' puntomedio(c(1,1),c(2,2))\n#' # [1] 1,5 1,5\n#'\npuntomedio <- function(a,b){\n pmedio <- vector(\"numeric\",2)\n pmedio[1] <- (a[1]+b[1])/2\n pmedio[2] <- (a[2]+b[2])/2\n pmedio\n}\n", "meta": {"hexsha": "5682467e695bc54a3701007ce157ab233239512a", "size": 322, "ext": "r", "lang": "R", "max_stars_repo_path": "R/puntomedio.r", "max_stars_repo_name": "pruebaOrg2/pruebaGeoAnalitica", "max_stars_repo_head_hexsha": "a5a6229bbac877b400c0435869b552ee81ecb326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/puntomedio.r", "max_issues_repo_name": "pruebaOrg2/pruebaGeoAnalitica", "max_issues_repo_head_hexsha": "a5a6229bbac877b400c0435869b552ee81ecb326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/puntomedio.r", "max_forks_repo_name": "pruebaOrg2/pruebaGeoAnalitica", "max_forks_repo_head_hexsha": "a5a6229bbac877b400c0435869b552ee81ecb326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9473684211, "max_line_length": 53, "alphanum_fraction": 0.5652173913, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7375005057585782}} {"text": "##### 医学統計勉強会15第一回基本統計量 R code #####\n\nx <- c(0.684, 1.406, -0.663, -0.124, 0.849, -0.888, -0.492, -0.044, -0.188, 0.536, 2.063, -1.379, 0.920, 0.453, 1.239)\n\n## 数量的なデータの要約 ##\n\nsum(x)\t\t\t# x の要素の和\nlength(x)\t\t# x の長さ\nmean(x)\t\t\t# x の平均\nmedian(x)\t\t# x の中央値\nquantile(x)\t\t# x の四分位点.Five numbers summary\nquantile(x, 0.2)\t# x の20%パーセント点\nsummary(x)\t\t\t# Five numbers summary + 平均\n\nvar(x)\t\t\t# x の分散\nsd(x)\t\t\t# x の標準偏差\nsqrt(x)\t\t\t# x の平方根\nsqrt(var(x))\t# x の分散の平方根 = x の標準偏差\nIQR(x)\t\t\t# x の四分位点間距離\nquantile(x, 0.75) - quantile(x, 0.25)\t# 四分位点間距離の定義の確認\n\n## 視覚的なデータの要約 ##\n\nx <- rnorm(100)\t# ランダムなサンプルの生成\n\nhist(x)\t\t\t# ヒストグラム(頻度)\nhist(x, freq=F)\t# ヒストグラム(相対頻度)\n\nboxplot(x)\t\t# ボックスプロット\n\n# ヒストグラムとボックスプロット #\n\n# 二峰型 #\nx1 <- rnorm(100, mean=0)\nx2 <- rnorm(100, mean=4)\nx <- c(x1, x2)\nhist(x)\nboxplot(x)\n\n# 裾の重い分布 #\ny1 <- rnorm(100, sd=1)\ny2 <- rnorm(100, sd=4)\ny <- c(y1, y2)\nhist(y)\nboxplot(y)\n\n\n\n## 二標本問題 ##\nx1 <- c(8, 17, 9, 5, 14, 13, 13, 3, 9, 0)\nx2 <- c(19, 13, 13, 18, 21, 18, 11, 21, 20, 11)\n\nboxplot(x1, x2)\n\nt.test(x1, x2)\t\t# Welch's t test\nwilcox.test(x1, x2)\t# Mann-Whitney test, Wilcoxon’s rank sum test\n\n\n\n## 分散分析 ##\n\n# サンプルデータ #\nData <- data.frame(\n z = c(8, 16, 7, 18, 6, 11, 15, 11, 20, 7, 19, 20, 21, 19, 24), \n group = factor(c(rep(1,5), rep(2,5), rep(3,5)), label=c(\"placebo\", \"drugA\", \"drugB\")))\nprint(Data)\nboxplot(z ~ group, data=Data)\n\n# ANOVA #\nfit.aov <- aov(z ~ group, data=Data)\nsummary(fit.aov)\n\n# Kruskal-Wallis rank sum test #\nkruskal.test(z ~ group, data=Data)\n\n\n\n## 多重比較 ##\n\n# Tukey's method #\nlibrary(MASS)\nfit.mc <- TukeyHSD(fit.aov)\nprint(fit.mc)\nplot(fit.mc)\n\n# Dunnett's method (Dunnett post hoc test) #\ninstall.packages(\"multcomp\")\t# 最初の一回のみ実行\nlibrary(multcomp)\nfit.dunnett <- glht(fit.aov, linfct = mcp(group = \"Dunnett\"))\nconfint(fit.dunnett, level=0.95)\nsummary(fit.dunnett)\n\n# William's method #\nfit.williams <- glht(fit.aov, linfct = mcp(group = \"Williams\"))\nconfint(fit.williams, level=0.95)\nsummary(fit.williams)", "meta": {"hexsha": "cd68b19af0e0db1fd0c649115e9da1d02f1679e1", "size": 1935, "ext": "r", "lang": "R", "max_stars_repo_path": "MedicalStatisticsClass/2015/01/w1.r", "max_stars_repo_name": "shumez/stat", "max_stars_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MedicalStatisticsClass/2015/01/w1.r", "max_issues_repo_name": "shumez/stat", "max_issues_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MedicalStatisticsClass/2015/01/w1.r", "max_forks_repo_name": "shumez/stat", "max_forks_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.15625, "max_line_length": 118, "alphanum_fraction": 0.6149870801, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7374604374503648}} {"text": "setwd(\"C:\\\\Users\\\\Ashish Arora\\\\Desktop\\\\Time series Case Study\")\n\n#Loading the data file\nmydata<-read.csv(\"data.csv\")\nView(mydata)\n\nmyts <- ts(mydata[,-c(1,2)], start=c(1996, 1), end=c(2005, 4), frequency=4) \nplot(myts)\n\n#After looking at the graph it is observed that Rest.of.World is a patternless data rest all follow a multiplicative form\n#so subsetting the data separately.\n\n\nmyts_ireland <- ts(mydata$Ireland, start=c(1996, 1), end=c(2005, 4), frequency=4) \nmyts_Other.EU <- ts(mydata$Other.EU, start=c(1996, 1), end=c(2005, 4), frequency=4) \nmyts_Rest.of.Europe <- ts(mydata$Rest.of.Europe, start=c(1996, 1), end=c(2005, 4), frequency=4) \nmyts_Total <- ts(mydata$Total, start=c(1996, 1), end=c(2005, 4), frequency=4) \n\nmyts_Rest.of..World <- ts(mydata$Rest.of..World, start=c(1996, 1), end=c(2005, 4), frequency=4) \n\n# plot series\nplot(myts_ireland)\nplot(myts_Other.EU)\nplot(myts_Rest.of.Europe)\nplot(myts_Total)\nplot(myts_Rest.of..World)#this is an non-seasonal patternless data so we can implement an exponential smoothening techniques\n\n\nfit<- decompose(myts_ireland, type = c(\"multiplicative\"))\nls(fit)\nforecast(fit$x, 4,level=c(90,95))\naccuracy(forecast(fit$x, 4))#The MAPE value of 2.428393 for Ireland predicted values\n#FORECASTING AND PLOTTING VALUES FOR NEXT QUATER(2006)\nfinal<-forecast(fit$x, 4,level=c(90,95))\nplot(final)\n\nfit1<- decompose(myts_Other.EU, type = c(\"multiplicative\"))\nforecast(fit1$x, 4,level=c(90,95))\naccuracy(forecast(fit1$x, 4))#The MAPE value of 2.279375 for Other EU predicted values\nfinal1<-forecast(fit1$x, 4,level=c(90,95))\nplot(final1)\n\nfit2<- decompose(myts_Rest.of.Europe, type = c(\"multiplicative\"))\nforecast(fit2$x, 4,level=c(90,95))\naccuracy(forecast(fit2$x, 4))#The MAPE value of 2.871732 for Rest of Europe predicted values\nfinal2<-forecast(fit1$x, 4,level=c(90,95))\nplot(final2)\n\nfit3<- decompose(myts_Total, type = c(\"multiplicative\"))\nforecast(fit3$x, 4,level=c(90,95))\naccuracy(forecast(fit3$x, 4))#The MAPE value of 1.948733 for Total predicted values\nfinal3<-forecast(fit1$x, 4,level=c(90,95))\nplot(final3)\n####NoW for Rest of world data####\nfit4.1 <- HoltWinters(myts_Rest.of..World, beta=FALSE, gamma=FALSE)\nls(fit4.1)\nrequire(forecast)\naccuracy(fit4.1$fitted, myts_Rest.of..World)\n\n# double exponential - models level and trend\nfit4.2 <- HoltWinters(myts_Rest.of..World, gamma=FALSE)\naccuracy(fit4.2$fitted, myts_Rest.of..World)\n# triple exponential - models level, trend, and seasonal components\nfit4.3 <- HoltWinters(myts_Rest.of..World)\naccuracy(fit4.3$fitted, myts_Rest.of..World)\n\n\n#ETS- Exponential method\nfit5<-ets(myts_Rest.of..World)\naccuracy(fit5$fitted, myts_Rest.of..World)\nsummary(fit5)\nfinal5<-forecast(fit5, 4 ,level = c(90,95))\nplot(final5)\n#Thus for rest of world the lowest MAPE is for ETS method thus we use that to predict the next quaters' values.\n\n##All The final graphs \nattach(mtcars)\npar(mfrow=c(3,2)) \nplot(final)\nplot(final1)\nplot(final2)\nplot(final3)\nplot(final5)\n\n#The predicted results are stored in final,final1, final2,final3, final5", "meta": {"hexsha": "7d4b663d58385221bf4d6e56f7ec2eff4a1a4702", "size": 3035, "ext": "r", "lang": "R", "max_stars_repo_path": "Times Series in R.r", "max_stars_repo_name": "ashish95arora/Time-Series-Moving-Averages-Exponential-Smoothening", "max_stars_repo_head_hexsha": "d3a7b2a940ae586d4890fe034a475ebe44d9dc6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Times Series in R.r", "max_issues_repo_name": "ashish95arora/Time-Series-Moving-Averages-Exponential-Smoothening", "max_issues_repo_head_hexsha": "d3a7b2a940ae586d4890fe034a475ebe44d9dc6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Times Series in R.r", "max_forks_repo_name": "ashish95arora/Time-Series-Moving-Averages-Exponential-Smoothening", "max_forks_repo_head_hexsha": "d3a7b2a940ae586d4890fe034a475ebe44d9dc6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7058823529, "max_line_length": 124, "alphanum_fraction": 0.736738056, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7373097520675487}} {"text": "#' @title estimParamsFromCI\n#' @description unknown\n#' @family abysmally documented\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\n estimParamsFromCI = function( CL, probs=c(0.025, 0.975), distribution=\"gamma\", method=\"L-BFGS-B\", plot=FALSE) {\n # CL is estimated/approximate 95% confidence bounds \n # probs = associated quantiles\n # pm0 = stating guess for parameters \n # theoreticalCI is theoretical probabilty function \n # pm are the parameters of the distributional function\n \n distrib = paste('^',distribution, sep=\"\" ) \n\n if ( grepl( distrib, \"normal\", ignore.case=TRUE ) ) {\n CIoptim = function( pm, CL, probs) {\n theoreticalCI = pnorm( CL, mean=pm[1], sd = pm[2], log.p=TRUE )\n llik = ( theoreticalCI[1] - log( probs[1] ) )^2 + ( theoreticalCI[2] - log( probs[2] ) )^2\n return( llik ) \n }\n pm0 = c( mean(CL), (CL[2]-CL[1])/3 )\n lower = c( -Inf, 1e-09 )\n resnames = c(\"mean\", \"sd\")\n resdefault = c( 0, 1e5 )\n plotfn = function(x) dnorm(x, res[[\"mean\"]], res[[\"sd\"]])\n plot.range = CL + c( - pm0[2], + pm0[2] )\n }\n\n \n if ( grepl( distrib, \"lognormal\", ignore.case=TRUE ) ) {\n CIoptim = function( pm, CL, probs) {\n theoreticalCI = plnorm( CL, meanlog=pm[1], sdlog=pm[2], log.p=TRUE ) \n llik = ( theoreticalCI[1] - log( probs[1] ) )^2 + ( theoreticalCI[2] - log( probs[2] ) )^2\n return( llik ) \n }\n pm0 = c( mean(log(CL)), log(CL[2])-log(CL[1])/3 )\n lower = c( -Inf, 1e-9 )\n resnames = c(\"meanlog\", \"sdlog\")\n resdefault = c( 1e-3, 2 )\n plotfn = function(x) dlnorm(x, res[[\"meanlog\"]], res[[\"sdlog\"]])\n plot.range = CL * c( 0.01, 1.5 ) \n }\n\n \n if ( grepl( distrib, \"gamma\", ignore.case=TRUE ) ) {\n CIoptim = function( pm, CL, probs) {\n theoreticalCI = pgamma( CL, shape=pm[1], rate=pm[2], log.p=TRUE )\n llik = ( theoreticalCI[1] - log( probs[1] ) )^2 + ( theoreticalCI[2] - log( probs[2] ) )^2\n return( llik ) \n }\n pm0 = c( 0.5, 1/mean( CL ))\n lower = c( 1e-9, 1e-9 )\n resnames = c(\"shape\", \"rate\")\n resdefault = c( 0.1, 0.01 )\n plotfn = function(x) dgamma(x, res[[\"shape\"]], res[[\"rate\"]])\n plot.range = CL * c( 0.01, 1.5 ) \n }\n\n res = optim( pm0, CIoptim, CL=CL, probs=probs, lower=lower, method=method)\n if (res$convergence==0) {\n res = res$par\n } else {\n res= resdefault \n }\n\n names(res) = resnames\n \n if (plot) {\n curve( plotfn, plot.range[1], plot.range[2] )\n abline( v=CL[1], lty=\"dotted\" )\n abline( v=CL[2], lty=\"dotted\" )\n }\n\n return(res)\n\n # ----------\n debug = FALSE\n if (debug) {\n CL = c(0.5, 10) # initial guess of 95% CI \n estimParamsFromCI( CL, pm0=c(0.1, 0.1) , distribution=\"gamma\", plot=T)\n # E(X) = shape * scale = shape / rate = res[[\"shape\"]] / res[[\"rate\"]] = 3.69\n # Var(X) = shape*scale^2 = shape / (rate^2) = res[[\"shape\"]] / res[[\"rate\"]] ^2 = 6.32\n qgamma( 0.025, res[[\"shape\"]], res[[\"rate\"]] ) # = 0.5\n qgamma( 0.975, res[[\"shape\"]], res[[\"rate\"]] ) # = 9.99\n curve( dgamma(x, res[[\"shape\"]], res[[\"rate\"]]), 0.0005, 100)\n \n }\n }\n \n \n\n", "meta": {"hexsha": "576161f13c3d7706caadcee7851d4124a3c951c4", "size": 3376, "ext": "r", "lang": "R", "max_stars_repo_path": "R/estimParamsFromCI.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/estimParamsFromCI.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/estimParamsFromCI.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6956521739, "max_line_length": 115, "alphanum_fraction": 0.5053317536, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7372539569114055}} {"text": "## Author: Sergio García Prado\n\nrm(list = ls())\n\n\n## a)\n####\n\n##\n## Asymptotic distibution of p.hat as parameter p of Bin(n, p)\n## p.hat ~ N(p, p * (1 - p) / n)\n##\n\n\n## b)\n####\n\nn <- 100\ny <- 15\nalpha <- 0.05\n\nLogLikelihood <- function(p, y, n) {\n y * log(p) + (n - y) * log(1 - p)\n}\n\nNegativeLogLikelihood <- function(...) {\n - LogLikelihood(...)\n}\n\nopt <- optim(runif(1), NegativeLogLikelihood, y = y, n = n, hessian = TRUE,\n method = \"Brent\", lower=10e-3, upper = 1 - 10e-3)\n\n(p.hat <- opt$par)\n# 0.149999999993663\n\n(p.hat.var <- 1 / opt$hessian[1])\n# 0.001274903\n\n## Wald's Confidence Interval at (1 - alpha)% level.\np.hat + c(-1, 1) * qnorm(1 - alpha / 2) * sqrt(p.hat.var)\n# 0.0800179459640629 0.219982054023264\n\n\n## c)\n####\np.zero <- 1 / 3\n\n(W <- (p.hat - p.zero) ^ 2 / p.hat.var)\n# 26.3616557734205\n\n(W.pvalue <- 1 - pchisq(W, df=1))\n# 2.83105275666884e-07\n\n\n## d)\n\n(LRT <- 2 * (LogLikelihood(p.hat, y, n) - LogLikelihood(p.zero, y, n)))\n# 17.345619477233\n\n(LRT.pvalue <- 1 - pchisq(LRT, df=1))\n# 3.11615708954438e-05\n", "meta": {"hexsha": "4cdf09e2bde3e74919d620c21086e4a407355511", "size": 1040, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/likelihood/exercise-01.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/likelihood/exercise-01.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/likelihood/exercise-01.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.7741935484, "max_line_length": 75, "alphanum_fraction": 0.5682692308, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7370891634921832}} {"text": "#COIN\r\np = seq(0,1,0.01)\r\nP10T = function(p) {11 * (1-p)^10} \r\n# 11 to normalize to a density\r\nplot(p, P10T(p),\"l\")\r\n# \r\nintegrate(P10T, lower=0, upper=1)\r\n#\r\n# for the mean\r\npP10T = function(p) 11 * p * (1-p)^10 \r\nintegrate(pP10T, lower=0, upper=1) #0.08333333 (1/12)\r\npoints(c(0, 0),c(0, 11), pch=16, col=\"red\")\r\npoints(c(1/12, 1/12),c(0, P10T(1/12)),pch=16,col=\"green\")\r\n# for the median\r\nintegrate(P10T, lower=0, upper=0.061069081) #0.50000\r\npoints(c(0.061069081, 0.061069081),\r\n c(0, P10T(0.061069081)), pch=16, col=\"blue\")\r\nlegend(0.6,10, #location\r\n c(\"Mode\",\"Mean\",\"Median\"), #labels\r\n cex= 1, #size \r\n pch=c(16,16,16), #filled circle\r\n col=c(\"red\",\"green\",\"blue\")) #color\r\n \r\n \r\n\r\n", "meta": {"hexsha": "77974fd47af67104f5fcaf566217d2f9ac240886", "size": 722, "ext": "r", "lang": "R", "max_stars_repo_path": "original_examples/Codes4Unit2/coin.r", "max_stars_repo_name": "areding/6420-pymc", "max_stars_repo_head_hexsha": "181ee40b8bf4a2c9fb237c4d388c4f62ea41bfeb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-23T00:16:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T23:44:38.000Z", "max_issues_repo_path": "original_examples/Codes4Unit2/coin.r", "max_issues_repo_name": "areding/6420-pymc", "max_issues_repo_head_hexsha": "181ee40b8bf4a2c9fb237c4d388c4f62ea41bfeb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-11T03:31:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T03:31:11.000Z", "max_forks_repo_path": "original_examples/Codes4Unit2/coin.r", "max_forks_repo_name": "areding/6420-pymc", "max_forks_repo_head_hexsha": "181ee40b8bf4a2c9fb237c4d388c4f62ea41bfeb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7692307692, "max_line_length": 59, "alphanum_fraction": 0.5761772853, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.737021069364566}} {"text": "p_1calf=0.83\r\np_2calf=0.02\r\np_0calf=0.15\r\n\r\n# event A= dams gives birth to no healthy progeny ,1 healthy progeny,2 healthy progeny(n1=1,n2=1,n3=1)\r\n\r\nP_eventA=(factorial(3)*(p_0calf^1*p_1calf^1*p_2calf^1))/(factorial(1)*factorial(1)*factorial(1))\r\nprint(P_eventA)\r\n # event B= 3 dams give birth to 1 healthy progeny(n1=0,n2=3,n3=0)\r\nP_eventB=(factorial(3)*(p_0calf^0*p_1calf^3*p_2calf^0))/(factorial(0)*factorial(3)*factorial(0))\r\nprint(P_eventB)\r\n# the probability of obtaining exactly three healthy progeny from three dams\r\np=P_eventA+P_eventB\r\nprint(p)", "meta": {"hexsha": "106249b06bc26412fa04f38bc9a39a05d6aaaed5", "size": 557, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.9/Ex10_9.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.9/Ex10_9.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.9/Ex10_9.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 39.7857142857, "max_line_length": 104, "alphanum_fraction": 0.7360861759, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456936, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.736838408438212}} {"text": "#Relation is the relationship between two set of numbers\n#It can be represented as ordered pairs\n#When we do correlation, we find the relationship between two set of numbers(ie variables)\n#The correlation coefficient explains about the relation.\n#It gives an idea to expand it as functions\n\n#Functions\n# A function is a set of ordered pairs in which the first coordinate, usually x, matches with exactly one second coordinate, y.\n# the y coordinate represents the dependent variable\n# A function can be expressed as an equation -> f(x) = y\n# f(x) - f is the name of the function and x is the name of the independent variable.\n\n#Mathematical modeling\n# Mathematical modeling involves creating a set of mathematical equations that describes a situation, solving those equations, and using them to understand the real life problem\n# Model can also be used to predict what a system will do for different values of the independent variable. Lastly, a model can be used to estimate quantities that are difficult to evaluate exactly\n# The goal is not to produce an exact copy of the \"real object\" but rather to give a representation of some aspect of the real thing.\n# Slope - the coefficient of x\n# Rate of change - f(b) - f(a) / (b-a)\nhotel = linear_tips\ncor(hotel$meal_amt, hotel$tips)\nplot(hotel$meal_amt, hotel$tips)\nmodel = lm(tips$meal_amt, data=hotel)\nmodel\nsummary(model)\nnew = c(20,25)\nnewx = as.data.frame(meal_amt=new)\nnewx\nnewy = predict(model, newx)\nnewy\nsample.read.csv(file.choose(), header=T)\nhead(sample)\nlibrary(SDSFoundations)\nlinFit(sample$x, sample$y)\nlinFitPred(sample$x, sample$y, 1)\nlinFitPred(sample$x, sample$y, 2)\nmean(sample$x)\nmean(sample$y)\n\n# Exponential model\nexpFit(sample$x, sample$y)\n# R-squared = 1 - (Explained variation) / Total variation\nexpFitPred(sample$x, sample$y, 1)\n#determining the target is known as Extrapolation - given y we need to find x, this is known as extrapolation\n# Logistic growth model will be best explainable when the data has reached the upper limit and there after the growth is consistent, logistic growth model can be used\nlogisticFit(sample$x, sample$y)\nlogisticFit(sample$x, sample$y, 1)\nlogisticFit(sample$x, sample$y, 2)\ntripleFit(sample$x, sample$y)\n", "meta": {"hexsha": "a358db147122253c1b86f43a1a49e8f5a073f945", "size": 2214, "ext": "r", "lang": "R", "max_stars_repo_path": "Sem3/IDS/vijay/functionsAndRelations.r", "max_stars_repo_name": "nsudhanva/mca-code", "max_stars_repo_head_hexsha": "812348ce53edbe0f42f85a9c362bfc8aad64e1e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sem3/IDS/vijay/functionsAndRelations.r", "max_issues_repo_name": "nsudhanva/mca-code", "max_issues_repo_head_hexsha": "812348ce53edbe0f42f85a9c362bfc8aad64e1e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sem3/IDS/vijay/functionsAndRelations.r", "max_forks_repo_name": "nsudhanva/mca-code", "max_forks_repo_head_hexsha": "812348ce53edbe0f42f85a9c362bfc8aad64e1e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-12T06:38:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-30T04:38:03.000Z", "avg_line_length": 45.1836734694, "max_line_length": 197, "alphanum_fraction": 0.7732610659, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7367576551192052}} {"text": "library(deSolve)\nlibrary(reshape)\nlibrary(ggplot2)\nlibrary(plotly)\n\n\nmicro_1 <- function(times,init,parms){\n with(as.list(c(parms,init)), {\n # ODEs\n dS <- r*(1-S/K)*S - beta*S*I\n dI <- beta*S*I-(mu + alpha)*I\n list(c(dS,dI))\n })\n}\n\nw <- 1\nm <- 10\nbeta <- 0.0247*m*w**0.44\nr <- 0.6*w**-0.27\nmu <- 0.4*w**-0.26\nK <- 16.2*w**-0.7\nalpha <- (m-1)*mu\n\nparms <- c(beta=beta,r=r,mu=mu,K=K,alpha=alpha)\ninit <- c(S=K,I=1.)\ntimes = seq(0,10,length.out=101)\n\nsir_out <- lsoda(init,times,micro_1,parms)\n\nsir_out_long <- melt(as.data.frame(sir_out),\"time\")\n\n# Plot\np <- plot_ly(data = sir_out_long, x = ~time[variable==\"S\"], y = ~value[variable==\"S\"],type = \"scatter\", mode = \"lines\",name = \"S(t)\") %>%\nadd_trace(y = ~value[variable==\"I\"],type = \"scatter\", mode = \"lines\",name = \"I(t)\") %>%\nlayout(xaxis = list(title=\"Time\"), yaxis = list(title=\"Number\"))\np\n\nm <- c(5,10,20,40)\nws <- 10^seq(-3,3,length.out=601)\nbetas <- data.frame(\"ws\"=ws, \"m5\"=0.0247*m[1]*ws^0.44,\"m10\"=0.0247*m[2]*ws^0.44,\"m20\"=0.0247*m[3]*ws^0.44,\"m40\"=0.0247*m[4]*ws^0.44)\n\n# Plot\np <- plot_ly(betas,x=~ws,y=~m5,type = \"scatter\", mode = \"lines\",name = \"m = 5\") %>%\nadd_trace(y = ~m10,type = \"scatter\", mode = \"lines\",name = \"m = 10\") %>%\nadd_trace(y = ~m20,type = \"scatter\", mode = \"lines\",name = \"m = 20\") %>%\nadd_trace(y = ~m40,type = \"scatter\", mode = \"lines\",name = \"m = 40\") %>%\nlayout(xaxis = list(title=\"Weight\",type = \"log\"), yaxis = list(title=\"beta_min\",type = \"log\"))\np\n", "meta": {"hexsha": "5350e8236688337713dd82a692904f8b3cfabe4c", "size": 1446, "ext": "r", "lang": "R", "max_stars_repo_path": "models/simple_deterministic_models/scaling/scaling_desolve.r", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_deterministic_models/scaling/scaling_desolve.r", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_deterministic_models/scaling/scaling_desolve.r", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 29.5102040816, "max_line_length": 137, "alphanum_fraction": 0.5864453665, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7367534678060867}} {"text": "## Author: Sergio García Prado\n## Title: Exercises with Solutions 5\n\nrm(list = ls())\n\n\nQ <- matrix(c(-20, 20, 0, 0,\n 10, -30, 0, 20,\n 5, 0, -25, 20,\n 0, 5, 10, -15),\n 4, 4, byrow = TRUE)\n\n(A <- cbind(Q[, 1:(nrow(Q) - 1)], rep(1, nrow(Q))))\n# -20\t 20\t 0\t1\n# 10\t-30\t 0\t1\n# 5\t 0\t-25\t1\n# 0\t 5\t 10\t1\n\n\n(stationary <- solve(A)[nrow(A), ])\n# 0.135802469135802 0.172839506172839 0.197530864197531 0.493827160493827\n\n\nstationary[2] + (5 / (10 + 5)) * stationary[4]\n# 0.337448559670782\n\n\n20 * (1 - stationary[4])\n# 10.1234567901235\n", "meta": {"hexsha": "4fc01a39760b1a0f545c9e2634ad4d8b19ba5099", "size": 600, "ext": "r", "lang": "R", "max_stars_repo_path": "stochastic-processes/proposed-exercises/continuous-5.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "stochastic-processes/proposed-exercises/continuous-5.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "stochastic-processes/proposed-exercises/continuous-5.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 73, "alphanum_fraction": 0.5066666667, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7367168356310104}} {"text": "# Function definitions for the inverse-gamma probability distribution.\n# The parameters of the distribution (alpha, beta) are as defined here:\n# https://en.wikipedia.org/wiki/Inverse-gamma_distribution\n\npinvgamma <- function(x, alpha, beta) {\n # The cdf of the inverse-gamma distribution.\n return(1 - pgamma(1/x, shape=alpha, rate=beta));\n}\n\nqinvgamma <- function(p, alpha, beta) {\n # The quantile function of the inverse-gamma distribution.\n return(1 / qgamma(1 - p, shape=alpha, rate=beta));\n}\n\ndinvgamma <- function(x, alpha, beta) {\n # The pdf of the inverse-gamma distribution.\n if (alpha <= 0 | beta <= 0) {\n stop(\"Shape or scale parameter negative in dinvgamma().\\n\");\n }\n log_density <- alpha * log(beta) - lgamma(alpha) - (alpha + 1) * log(x) - (beta / x);\n return(exp(log_density));\n}\n\nrinvgamma <- function(n, alpha, beta) {\n # Draw n samples from the inverse-gamma distribution.\n return(1 / rgamma(n=n, shape=alpha, rate=beta));\n}\n", "meta": {"hexsha": "5792e72b73146e234b0ba2ef6bc24d0893ffa17c", "size": 983, "ext": "r", "lang": "R", "max_stars_repo_path": "invgamma.r", "max_stars_repo_name": "cscheffler/rdistributions", "max_stars_repo_head_hexsha": "a649d455bb4c58974656b5e224e7dc84941525df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "invgamma.r", "max_issues_repo_name": "cscheffler/rdistributions", "max_issues_repo_head_hexsha": "a649d455bb4c58974656b5e224e7dc84941525df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "invgamma.r", "max_forks_repo_name": "cscheffler/rdistributions", "max_forks_repo_head_hexsha": "a649d455bb4c58974656b5e224e7dc84941525df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1071428571, "max_line_length": 89, "alphanum_fraction": 0.6693794507, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530198, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7364512476523192}} {"text": "# This file contains R code for the Cmax estimator used as an example in section 3.\n# Although not designed to be the most efficient R program, it is simply here to \n# assist students in writing their own functions by illustrating several useful concepts.\n\n# Function to calculate the statistic\nCmax=function(song){\n# song is a vector of 0's and 1's that represents the hits (0) and \n# misses (1) of the notes in order \n\n n = length(song) # determine the number of notes in the song\n\n c_temp=0 # this is a temporary counter which tallies the strings of misses\n\n c_max=0 # this holds the current length of the longest streak of misses\n\n for(i in 1:n){ # set up a for loop to scan through entire song\n if(song[i]==1){ # use this section only if a miss on note i\n c_temp=c_temp+1 # increase miss streak by 1\n if(c_temp>c_max) c_max=c_temp # check if new streak is longer than current max \n }\n if(song[i]==0){ # use this section only if a hit on note i\n c_temp=0 # reset current streak of misses\n }\n }\n\n return(c_max) # returns the maximum consecutive number of misses\n}\n\n# Hypothesis test based on the Cmax method\nCmax_test = function(song,B=1000){\n # song is a vector of 0's and 1's that represents the hits (0) \n\t# and misses (1) of the notes in order\n\t# B is the number of new samples to generate\n\t\n\ttest_stat = Cmax(song)\n\tn = length(song)\n\ttstar_b = numeric(B)\n\tfor(b in 1:B){\n\t\tsong_tmp = sample(song) # for permutation test\n#\t\tsong_tmp = sample(song,replace=T) # for non-parametric bootstrap\n#\t\tsong_tmp = rbinom(n,1,mean(song)) # for parametric bootstrap\n\t\ttstar_b[b] = Cmax(song_tmp)\n\t}\n\t\n\t# calculate the two-sided p-value from the sampling distribution\n\tpval = 2*min(sum(tstar_b >= test_stat),sum(tstar_b <= test_stat))/B\n\t\n\t# calculate a one sided p-value\n#\tpval = sum(tstar_b >= test_stat)/B\n\t\n\treturn(pval)\n}\n\n\n# Examples using Songs A and B from Table 1\n\nsongA = c(1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0)\nCmax(songA)\nCmax_test(songA,5000)\n\n\nsongB = c(0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,0,0)\nCmax(songB)\nCmax_test(songB,5000)", "meta": {"hexsha": "233ca6e1e16366777261276543836153457032d9", "size": 2087, "ext": "r", "lang": "R", "max_stars_repo_path": "GHSupplementaryFiles/AppendixC/Cmax.r", "max_stars_repo_name": "iramler/guitar_hero_jse", "max_stars_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GHSupplementaryFiles/AppendixC/Cmax.r", "max_issues_repo_name": "iramler/guitar_hero_jse", "max_issues_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GHSupplementaryFiles/AppendixC/Cmax.r", "max_forks_repo_name": "iramler/guitar_hero_jse", "max_forks_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.609375, "max_line_length": 89, "alphanum_fraction": 0.6952563488, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7364495276242157}} {"text": "library(Sleuth3)\nwith(case0202,hist(Unaffected-Affected))\ndiffs<-case0202$Unaffected-case0202$Affected\ndiffs<-with(case0202,Unaffected-Affected)\ndiffs\nhist(diffs)\nt.test(diffs)\nwith(case0202,t.test(Unaffected,Affected,paired=TRUE))\nwith(case0202,t.test(Unaffected,Affected))\nsample.mean<-mean(diffs) #Calculate the sample mean of the differences\nsample.sd<-sd(diffs) #Calculate the sample standard deviation\nn<-length(diffs) #Find the sample size\n\nse.mean<-sample.sd/sqrt(n) #Calculate the standard error of the sample mean.\nsample.mean/se.mean\n\npt(3.228928,14) # Area under the t_14 curve to the left of 3.228928\n1-pt(3.228928,14) # Area to the right.\n2*(1-pt(3.228928,14)) # Two-sided p-value.\n\nqt(.975,14) # t quantile for 95% confidence interval and 14 df.\nsample.mean-qt(.975,14)*se.mean\nsample.mean+qt(.975,14)*se.mean\n\nlibrary(ggplot2)\nqplot(factor(Year),Depth,data=case0201,geom=\"boxplot\")\n\nt.test(Depth~Year,data=case0201,var.equal=TRUE)\nt.test(Depth~Year,data=case0201,var.equal=TRUE,alternative=\"less\")\n", "meta": {"hexsha": "9d4b02aa0aef9f60dd289adc38206148a5337e7f", "size": 1029, "ext": "r", "lang": "R", "max_stars_repo_path": "ST511-MethDataAnalysis/hw2/Lab2.r", "max_stars_repo_name": "leanth/OSUCoursework", "max_stars_repo_head_hexsha": "ccfbf5f9daa8f6d3818bb5e4cc8df7c5135a5f34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ST511-MethDataAnalysis/hw2/Lab2.r", "max_issues_repo_name": "leanth/OSUCoursework", "max_issues_repo_head_hexsha": "ccfbf5f9daa8f6d3818bb5e4cc8df7c5135a5f34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ST511-MethDataAnalysis/hw2/Lab2.r", "max_forks_repo_name": "leanth/OSUCoursework", "max_forks_repo_head_hexsha": "ccfbf5f9daa8f6d3818bb5e4cc8df7c5135a5f34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3, "max_line_length": 79, "alphanum_fraction": 0.7580174927, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7364495152637389}} {"text": "# Compare means with Kruskal-Wallis test (nonparametric, because non-normal distribution)\n\ndata <- read.csv('../../results/client_algos/data_all.csv', sep = ';')\n\n# Means\naggregate(data$time, list(data$combination), median)\n# None: 1492.0\n# Triple: 1588.5\n# BGPSimple: 745.0\n# BGPCombined: 736.0\n# TripleBGP: 658.5\n\n#boxplot(time ~ combination, data = data, ylab=\"Exec (ms)\", xlab=\"Combination\")\n\n# H0: None == Triple\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_0' | data$combination=='combination_1'),])\n# p: 0.9318\n# => Accept H0, equal means => None == Triple\n\n# H0: None == BGPSimple\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_0' | data$combination=='combination_2'),])\n# p: 0.006231\n# => Accept H0, non-equal means => None > BGPSimple\n\n# H0: None == BGPCombined\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_0' | data$combination=='combination_3'),])\n# p: 0.002631\n# => Reject H0, non-equal means => None > BGPCombined\n\n# H0: Triple == BGPSimple\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_1' | data$combination=='combination_2'),])\n# p: 0.009066\n# => Accept H0, non-equal means => Triple > BGPSimple\n\n# H0: Triple == BGPCombined\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_1' | data$combination=='combination_3'),])\n# p: 0.004172\n# => Reject H0, non-equal means => Triple > BGPCombined\n\n# H0: None == TripleBGP\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_0' | data$combination=='combination_4'),])\n# p: 0.00234\n# => Reject H0, non-equal means => None > TripleBGP\n\n# H0: Triple == TripleBGP\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_1' | data$combination=='combination_4'),])\n# p: 0.003434\n# => Reject H0, non-equal means => Triple > TripleBGP\n\n# H0: BGPSimple == TripleBGP\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_2' | data$combination=='combination_4'),])\n# p: 0.5758\n# => Accept H0, equal means => BGPSimple == TripleBGP\n\n# H0: BGPCombined == TripleBGP\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_3' | data$combination=='combination_4'),])\n# p: 0.9484\n# => Accept H0, equal means => BGPCombined == TripleBGP\n\n# H0: BGPCombined == BGPSimple\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_3' | data$combination=='combination_2'),])\n# p: 0.6689\n# => Accept H0, equal means => BGPCombined == BGPSimple", "meta": {"hexsha": "db95cf22d0741b5f06fa559bbff57a0c8fb87504", "size": 2586, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/client_algos/tests.r", "max_stars_repo_name": "comunica/Experiments-AMF", "max_stars_repo_head_hexsha": "e133e5994d470f84ab923ca6ef8afa114ed21739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/client_algos/tests.r", "max_issues_repo_name": "comunica/Experiments-AMF", "max_issues_repo_head_hexsha": "e133e5994d470f84ab923ca6ef8afa114ed21739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-03-04T17:48:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T11:23:38.000Z", "max_forks_repo_path": "analysis/client_algos/tests.r", "max_forks_repo_name": "comunica/Experiments-AMF", "max_forks_repo_head_hexsha": "e133e5994d470f84ab923ca6ef8afa114ed21739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0476190476, "max_line_length": 124, "alphanum_fraction": 0.7084300077, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948927, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7363991557740753}} {"text": "# 04. 정규분포\n\n# 정규분포 : 평균과 분산으로 표시 \n# 난수함수: rnorm(n, mean=0, sd=1)\n# 확률밀도함수: d~\n# 누적분포함수(점수): p~\n# 누적분포함수(확률): q~\n\n# 난수함수: rnorm(n, mean=0, sd=1)\nx <-rnorm(100,50,20) # 숫자 100개를 무작위로 뽑아라. 그런데 평균이 50이고 표준편차가 20이다. 랜덤으로 추출\n\nx # 무작위 추출\n\nx <- sort(x) # 순서대로 정리 \n\nx <- round(x,2)\n\nplot(x, \n dnorm(x,50,20), \n type='l', # 선을 연결하는 옵션 \n main=\"정규분포, X~N(50,20)\")\nabline(v=50, # 평균이 50이니까 보기좋게 선 그린 것 \n col=\"blue\", \n lty=2) # 라인 스타일 \n\n# 정규분포 누적분포함수(점수)\n# pnorm(q, mean=0, sd=1, lower.tail=FALSE)\n# 이하 : P(X <= a) lower.tail = TRUE\n# 초과: P(X > a) lower.tail = FALSE\n# 만약 60점이라면 \npnorm(60, mean=50, sd=20, lower.tail=TRUE) # 60점 이하 => 60점이면 아래에 전체의 몇 %가 있는가? 아래료 70%\npnorm(60, mean=50, sd=20, lower.tail=FALSE) # 60점 초과 => 60점을 초과하는 학생은 전체의 몇 % 인가? 상위 몇 %에 속하는가? 30%\nabline(v=60, col=\"red\", lty=3)\n\n\n# 누적분포함수(확률) => 몇 % 일때 점수를 알고 싶다. \n# qnorm(p, mean=0, sd=1, lower.tail=FALSE)\n# 이하 : P(X <= a) lower.tail = TRUE\n# 초과: P(X > a) lower.tail = FALSE\n# 상위 35% 안에 들어가려면 \nqnorm(0.35, mean=50, sd=20, lower.tail=FALSE) # 상위 35%의 점수를 알려주어라. 위에서 부터 재는 것\nqnorm(0.35, mean=50, sd=20, lower.tail=TRUE) # 하위 35%의 점수를 알려주어라. \nabline(v=57.7, col=\"green\", lty=3) \n\n# 정규분포 그래프\nplot(x, \n dnorm(x, 50,20), \n type='l', \n main=\"정규분포, X~N(50,20)\")\nabline(v=50, col=\"blue\", lty=3)\nabline(v=50+1.96*20, col=\"red\", lty=3) # 신뢰수준 95% 구간에 표시하라. \nabline(v=50-1.96*20, col=\"red\", lty=3)\n\n# 표준정규분포 그래프 <- 평균을 0로 하여 그린 그래프 \nx <- seq(-3, 3, length=200) \nplot(x, \n dnorm(x, mean=0, sd=1), \n type='l', \n main=\"Normal distribution, X~N(0,1)\") \n\n\n# 퀴즈\n#대학 경영통계 수업 듣는 학생의 시험점수가 평균 70, 표준편차가 20점이라고 한다. \n#상위 35%에 들기 위한 점수는?\n\nqnorm(0.35, 70, 20, lower.tail = FALSE)\nqnorm(0.35, mean=70, sd=20, lower.tail=FALSE)\n\n\n#B이상(80%)에 들기 위한 점수는?7\nqnorm(0.2, mean=70, sd=20, lower.tail=TRUE)\n", "meta": {"hexsha": "49bddf096558f500a9be4fd7a385c241a73a4146", "size": 1777, "ext": "r", "lang": "R", "max_stars_repo_path": "ch06 - 확률분포/04.정규분포.r", "max_stars_repo_name": "Lee-changyul/Rstudy_Lee", "max_stars_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch06 - 확률분포/04.정규분포.r", "max_issues_repo_name": "Lee-changyul/Rstudy_Lee", "max_issues_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch06 - 확률분포/04.정규분포.r", "max_forks_repo_name": "Lee-changyul/Rstudy_Lee", "max_forks_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6805555556, "max_line_length": 99, "alphanum_fraction": 0.5830050647, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7363711726249792}} {"text": "?rbinom\nn <- 1000 #number of observations\np <- 0.2 #probability of success\n\n#create random binomial distribution of [0,1,...,7] scores\nscores <- rbinom(n, 8, p)\n\n#plotting histogram\nhist(scores)\n\n#Unfair coin with P(heads) = 0.65, 10 tosses\n#10 trials, exactly 7 heads\ndbinom(7, 10, 0.65) #using density function\n\n#10 trials, at most 7 heads\npninom(7, 10, 0.65) #cumulative probs, using distribution function\n\n#10 trials, at least 6 heads\n# density 6 heads + density 7 heads + ... + density 10 heads\ndbinom(6, 10, 0.65)+dbinom(7, 10, 0.65)+dbinom(8, 10, 0.65)+dbinom(9, 10, 0.65)+dbinom(10, 10, 0.65)\n#or cumulative of 10 heads - cumulative 5 heads\npbinom(10, 10, 0.65) - pbinom(5, 10, 0.65)\n\n\n#Plotting better the previous hist(scores) using densities\nlibrary(tidyverse)\ndf <- as_tibble(data.frame(scores))\ndf_with_freqs <- df %>% \n group_by(scores) %>%\n summarize(n=n()) %>%\n mutate(freq= n/sum(n))\n\nggplot(df_with_freqs, aes(x=scores, y=freq)) + geom_col() + ylab(\"Estimated Density\")\n\n#Plotting analytical densities in binominal distribution\nbinom <- as_tibble(list(x=0:n, prob= dbinom(0:n, n, p)))\nggplot(binom, aes(x=x, y=prob)) + geom_col() + ylab(\"Analytical Density\")\n\n#Computing the cumulative density function using previous probability density function\ndf_with_cdf <- binom %>%\n mutate(cdf=cumsum(prob))\nggplot(df_with_cdf, aes(x=x, y=cdf)) + geom_step() + ylab(\"CDF\")\n\n#Plotting histogram and density with ggplot\nggplot(binom, aes(x))+\n geom_histogram(data=binom, aes(x, ..density..), fill=\"white\", color=\"darkred\")+\n geom_density(kernel=\"gaussian\", aes(x))\n", "meta": {"hexsha": "a28b3059d5abc453bbc44745432af5e3b1b0bcf0", "size": 1635, "ext": "r", "lang": "R", "max_stars_repo_path": "homework2.r", "max_stars_repo_name": "samuxiii/r-projects", "max_stars_repo_head_hexsha": "13a17bdf5a3db2efcf785c4810bb55c86459bfb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework2.r", "max_issues_repo_name": "samuxiii/r-projects", "max_issues_repo_head_hexsha": "13a17bdf5a3db2efcf785c4810bb55c86459bfb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework2.r", "max_forks_repo_name": "samuxiii/r-projects", "max_forks_repo_head_hexsha": "13a17bdf5a3db2efcf785c4810bb55c86459bfb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-06-24T17:18:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T03:39:37.000Z", "avg_line_length": 34.0625, "max_line_length": 100, "alphanum_fraction": 0.6801223242, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.736326546949384}} {"text": "#' @export\n#'\n#' @title Baysian estimation to binomial proportion using a conjugate\n#' prior.\n#'\n#' @description This routine assumes a beta(a,b) prior for a binomial\n#' proportion and computes posterior point and inteval estimates\n#' for the proportion given\n#' an observed number of 'successes' and number of 'trials'.\n#'\n#' @param x The number of 'successes' (an integer vector)\n#'\n#' @param n The number of 'trials' (an integer vector)\n#'\n#' @param a A vector of shape parameters to specify the beta prior\n#'\n#' @param b A vector of scale parameters to specify the beta prior\n#'\n#' @param conf A scalar specifying the desired confidence level\n#' of the interval estimate. This scalar should be between 0.5 and 1.\n#'\n#' @param ci A character string specifying the type of posterior\n#' confidence interval to compute. A value of 'eq' computes\n#' posterior intervals with equal area in both tails. A value\n#' of 'hdi' computes highest density interval estimates. See Details.\n#'\n#' @details\n#'\n#' Computations are elementary because the beta(a,b) prior is\n#' conjugate for the binomial. Nearly every text on Bayesian\n#' estimation shows that given values for \\code{x}, \\code{n},\n#' \\code{a}, and \\code{b}, the posterior distribution of p\n#' is,\n#' \\deqn{beta(x+a, n-x+b).}\n#' Hence, the Bayes point estimator is,\n#' \\deqn{phat = (x+a) / (n+a+b),}\n#' which is the mean of the posterior. Standard error of the\n#' posterior is,\n#' \\deqn{se.phat=sqrt(a*b/((a+b)^2*(a+b+1))).}\n#' If \\code{a>1} and \\code{b>1}, mode of the posterior for p is,\n#' \\deqn{(a-1)/(a+b-2).}\n#'\n#'\n#' Confidence intervals can be computed two ways. The default,\n#' \\code{ci='eq'}, puts \\code{(1-conf)/2} probability in the\n#' lower tail and \\code{(1-conf)/2} in the upper tail.\n#' That is, the lower limit is\n#' \\code{qbeta((1-conf)/2,x+a,n-x+b)} and the upper limit is\n#' \\code{qbeta(1-(1-conf)/2,x+a,n-x+b)}. If \\code{ci='hdi'},\n#' this routine finds the interval [l,u] such that\n#' \\code{pbeta(u,x+a,n-x+b) - pbeta(l,x+a,n-x+b)} and\n#' \\code{dbeta(u,x+a,n-x+b) = dbeta(l,x+a,n-x+b)}.\n#'\n#' The default values for \\code{a} and \\code{b}\n#' imply use of the Jeffery's prior. The Jeffery's prior is\n#' proportional to the root of Fisher's information and\n#' is equal to beta(0.5,0.5). A flat prior is beta(1,1).\n#'\n#' @return A data frame with number of rows equal to\n#' \\code{max(length(x), length(n), length(a), length(b)}\n#' containing the Baysian point and interval estimates.\n#' The data frame has the\n#' following columns:\n#' \\enumerate{\n#' \\item \\code{phat} : the Bayes point estimates equal to the\n#' mean of the posterior distribution.\n#' \\item \\code{phat.mode} : if \\code{a>1} and \\code{b>1}, this\n#' column contains the mode of the posterior. If either\n#' \\code{a<=1} or \\code{b<=1}, the posterior is either multi-modal\n#' or its mode is infinity. In this case, \\code{phat.mode = NA}.\n#' \\item \\code{se.phat} : the standard\n#' error of the posterior distribution.\n#' \\item \\code{ll.phat} : the lower limit of a \\code{100*(1-(1-conf)/2)}%\n#' posterior confidence interval for \\code{phat}. See Details for\n#' interpretation under the allowed values of \\code{ci}.\n#' \\item \\code{ul.phat} : the upper limit of a \\code{100*(1-(1-conf)/2)}%\n#' posterior confidence interval for \\code{phat}. See Details for\n#' interpretation under the allowed values of \\code{ci}.\n#' }\n#'\n#' @author Trent McDonald\n#'\n#'\n#' @seealso \\code{\\link{agrestiCoullPhat}}\n#'\n#' @examples\n#' bayesPhat(0:5, 100, 0.5, 0.5) # Jeffery's prior\n#' bayesPhat(0:5, 100, 1, 1) # flat prior\n#'\n#' # When prior data is available:\n#' x.prior <- 5\n#' n.prior <- 100\n#' bayesPhat(0:5, 100, x.prior+0.5, n.prior-x.prior+0.5)\n#'\n#' # Simulation: point est bias and ci coverage\n#' trueP <- 0.01\n#' n <- 1000\n#' x <- rbinom( 1000, n, trueP)\n#' baPhat <- bayesPhat( x, n )\n#' muBA <- mean(baPhat$phat)\n#' covBA <- mean(baPhat$ll.phat <= trueP & trueP <= baPhat$ul.phat)\n#' baStats <- c(mean=muBA,\n#' relBias = abs(muBA-trueP)/trueP),\n#' coverage = covBA)\n#'\n#'\n#'\n#'\nbayesPhat <- function(x, n, a=0.5, b=0.5, conf=0.9, ci=\"eq\"){\n aPost <- x + a\n bPost <- n - x + b\n phat <- aPost / (aPost + bPost)\n\n\n se <- sqrt(aPost*bPost / ((aPost+bPost)^2*(aPost+bPost+1)))\n\n if((aPost>1) & (bPost>1)){\n phat.mode <- (aPost-1) / (aPost + bPost - 2)\n } else {\n phat.mode <- NA\n }\n\n ll <- qbeta((1-conf)/2,aPost,bPost)\n ul <- qbeta(1-(1-conf)/2,aPost,bPost)\n if(ci==\"hdi\"){\n if((aPost>1) & (bPost>1)){\n fl <- function(q, a, b, p){\n (dbeta(q,a,b) - p)^2\n }\n hdi.obj <- function(p, a, b, conf, phat.mode){\n q1 <- optim(par=phat.mode/2,fn=fl,a=a, b=b, p=p,\n method=\"Brent\",lower=0, upper = phat.mode)$par\n q2 <- optim(par=(1+phat.mode)/2,fn=fl,a=a, b=b, p=p,\n method=\"Brent\",lower=phat.mode, upper = 1)$par\n hdi.prob <- pbeta(q2,a,b) - pbeta(q1,a,b)\n (hdi.prob - conf)^2\n }\n fp <- optim(par=dbeta(phat.mode,aPost,bPost)/2, fn=hdi.obj,\n a=aPost, b=bPost, conf=conf, phat.mode=phat.mode,\n method=\"Brent\", lower=1e-10,\n upper=dbeta(phat.mode,aPost,bPost))$par\n ll <- optim(par=ll,fn=fl,a=aPost, b=bPost, p=fp,\n method=\"Brent\",lower=0, upper = phat.mode)$par\n ul <- optim(par=ul,fn=fl,a=aPost, b=bPost, p=fp,\n method=\"Brent\",lower=phat.mode, upper = 1)$par\n } else {\n ll <- ul <- NA\n }\n }\n\n data.frame(phat=phat, se.phat=se, phat.mode=phat.mode, ll.phat=ll, ul.phat=ul)\n}\n", "meta": {"hexsha": "048f6027a82e0b8ee35a1099c729d9e2b3dc9589", "size": 5607, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bayesPhat.r", "max_stars_repo_name": "tmcd82070/EoAR", "max_stars_repo_head_hexsha": "30bdd48e88046332fdb1c97d55fb9a6a1a983e06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/bayesPhat.r", "max_issues_repo_name": "tmcd82070/EoAR", "max_issues_repo_head_hexsha": "30bdd48e88046332fdb1c97d55fb9a6a1a983e06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/bayesPhat.r", "max_forks_repo_name": "tmcd82070/EoAR", "max_forks_repo_head_hexsha": "30bdd48e88046332fdb1c97d55fb9a6a1a983e06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6470588235, "max_line_length": 80, "alphanum_fraction": 0.6140538612, "num_tokens": 1853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7363208399269655}} {"text": "#' @export\n#' @title decibar2depth\n#' @description This function calculates depth in meters from pressure in decibars using Saunders and Fofonoff's method\n#' @param \\code{P} = pressure, in decibars\n#' @param \\code{lat} = degrees latitude\n#' @param \\code{Del} = geopotential anomaly (defaults to 0)\n#' @param \\code{method} = valid values include\"default\", \"seabird\", and \"unesco\", although they all appear to be treated the same\n#' @return \\code{DEPTH} = depth in M\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @examples\n#' decibar2depth(10000,30,0)\n#' [1] 9712.653\n#' @note \n#' \n# DEEP-SEA RES., 1976, 23, 109-111.\n#' / UNITS:\n#' // PRESSURE P DECIBARS\n#' // LATITUDE LAT DEGREES\n#' // DEPTH DEPTH METERS\n#' // DTN. HEIGHT DEL DYN. METERS (geopotenial anomaly in J/kg:: assume 0) \n#' // CHECKVALUE:\n#' // 1.) DEPTH = 9712.653 M for P=10000 DECIBARS, LAT=30 DEG, DEL=0\n#' // ABOVE FOR STANDARD OCEAN: T=0 DEG CELSIUS; S=35 (PSS-78)\n#' // ----------------------------------------------------------\n#' // Original fortran code is found in:\n#' // UNESCO technical papers in marine science 44 (1983) -\n#' // 'Algorithms for computation of fundamental properties of seawater'\n#' @references \\url{http://www.code10.info/index.php?option=com_content&view=article&id=67:calculating-the-depth-from-pressure&catid=54:cat_coding_algorithms_seawater&Itemid=79}, \\url{http://www.code10.info/index.php?option=com_content&view=article&id=67:calculating-the-depth-from-pressure&catid=54:cat_coding_algorithms_seawater&Itemid=79}\n#' @family physical and chemical properties\n#' @export\n\n decibar2depth = function( P, lat, Del=0, method=\"default\" ) {\n \n if (method %in% c(\"default\", \"seabird\", \"unesco\" ) ) {\n \n X = (sin( lat * pi / 180 ))^2 # convert degree decimal to RADs\n\n # GR=GRAVITY VARIATION WITH LATITUDE: ANON (1970) BULLETIN GEODESIQUE\n GR = 9.780318 * (1.0 + (5.2788E-3 + 2.36E-5 * X) * X) + 1.092E-6 * P\n DepthTerm = (((-1.82E-15 * P + 2.279E-10) * P - 2.2512E-5) * P + 9.72659) * P ## assuming (35 psu, 0 C, and P=pressure in decibars )\n DEPTH = DepthTerm / GR + Del / 9.8\n return (DEPTH)\n }\n\n \n\n }\n\n\n", "meta": {"hexsha": "07c82cf0f6542c704934f8e1024447e1a8113df4", "size": 2252, "ext": "r", "lang": "R", "max_stars_repo_path": "R/decibar2depth.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/decibar2depth.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/decibar2depth.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.04, "max_line_length": 341, "alphanum_fraction": 0.6194493783, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7363208360290238}} {"text": "# V17: moyenne; V18: max; V25: Nom de l'Etat;\nhead(df)\n#S?lection des colonnes pertinentes\ndata_80_14 <- data_80_14[,c(\"V25\", \"V18\", \"V17\")]\n#S?lection des donn?es des Etats qui nous int?ressent\ndata_80_14=subset(df, V25==\"California\" | V25==\"Louisiana\" | V25==\"Ohio\" | V25==\"Minnesota\" | V25==\"Montana\")\n#Renommage des colonnes\ncolnames(data_80_14)[1] <- \"?tat\"\ncolnames(data_80_14)[2] <- \"Temp?rature maximale\"\ncolnames(data_80_14)[3] <- \"Temp?rature moyenne\"\n\n#Comme la moyenne est une moyenne arithm?tique, on peut d?terminer\n#la temp?rature minimale ? partir de la moyenne et de la temp?rature\n#maximale\n#Moy = (Min+Max)/2\n#2*Moy = Min+Max\n#2*Moy-Max = Min\ntemp_minimale=2*data_80_14$`Temp?rature moyenne`-data_80_14$`Temp?rature maximale`\ndata_80_14$temp_minimale=temp_minimale\n\n#Calcul de la moyenne et de l'?cart type, pour cet ?chantillon\n\n#Moyenne de la temp?rature max\nmoy_max_1 <- mean(data_80_14$`Temp?rature maximale`)\n#Ecart type sur la temp?rature max\nsigma_tmp <- 0\nfor(j in 1:nrow(data_80_14))\n{\n sigma_tmp <- sigma_tmp + (moy_max_1-data_80_14$`Temp?rature maximale`[j])^2\n \n}\n#?cart-type = racine carr? de la variance\nsigma_max_1 <- sqrt(sigma_tmp/(nrow(data_80_14)-1))\n\n\n#Moyenne de la temp?rature moyenne\nmoy_moyenne_1 <- mean(data_80_14$`Temp?rature moyenne`)\n\n#Ecart type sur la temp?rature moyenne\nsigma_tmp <- 0\nfor(j in 1:nrow(data_80_14))\n{\n sigma_tmp <- sigma_tmp+(moy_moyenne_1-data_80_14$`Temp?rature moyenne`[j])^2\n \n}\nsigma_moy_1 <- sqrt(sigma_tmp/(nrow(data_80_14)-1))\n\n#Moyenne de la temp?rature minimale\nmoy_min_1 <- mean(data_80_14$`temp_minimale`)\n\n#Ecart type sur la temp?rature minimale\nsigma_tmp <- 0\nfor(j in 1:nrow(data_80_14))\n{\n sigma_tmp <- sigma_tmp+(moy_min_1-data_80_14$`temp_minimale`[j])^2\n \n}\nsigma_min_1 <- sqrt(sigma_tmp/(nrow(data_80_14)-1))\n\n#-------DEUXIEME ECHANTILLON: 2015 - 2019 -------#\n#On fait pareil avec le deuxi?me ?chantillon\n\n\n# V17 moyenne V18 max V25 Nom de l'Etat\nhead(df)\ndata_15_19=subset(df, V25==\"California\" | V25==\"Louisiana\" | V25==\"Ohio\" | V25==\"Minnesota\" | V25==\"Montana\")\ndata_15_19 <- data_15_19[,c(\"V25\", \"V18\", \"V17\")]\ncolnames(data_15_19)[1] <- \"?tat\"\ncolnames(data_15_19)[2] <- \"Temp?rature maximale\"\ncolnames(data_15_19)[3] <- \"Temp?rature moyenne\"\n\n#Comme la moyenne est une moyenne arithm?tique, on peut d?terminer\n#la temp?rature minimale ? partir de la moyenne et de la temp?rature\n#maximale\ntemp_minimale=2*data_15_19$`Temp?rature moyenne`-data_15_19$`Temp?rature maximale`\ndata_15_19$temp_minimale=temp_minimale\n\n#Moyenne de la temp?rature max\nmoy_max_2 <- mean(data_15_19$`Temp?rature maximale`)\n#Ecart type sur la temp?rature max\nsigma_tmp <- 0\nfor(j in 1:nrow(data_15_19))\n{\n sigma_tmp <- sigma_tmp + (data_15_19$`Temp?rature maximale`[j]-moy_max_2)^2\n \n}\nsigma_max_2 <- sqrt(sigma_tmp/(nrow(data_15_19)-1))\nprint(data_15_19$`Temp?rature maximale`)\n\n#Moyenne de la temp?rature moyenne\nmoy_moyenne_2 <- mean(data_15_19$`Temp?rature moyenne`)\n\n#Ecart type sur la temp?rature moyenne\nsigma_tmp <- 0\nfor(j in 1:nrow(data_15_19))\n{\n sigma_tmp <- eval.parent(substitute(sigma_tmp+(moy_moyenne_1-data_15_19$`Temp?rature moyenne`[j])^2))\n \n}\nsigma_moy_2 <- sqrt(sigma_tmp/(nrow(data_15_19)-1))\n\n#Moyenne de la temp?rature minimale\nmoy_min_2 <- mean(data_15_19$`temp_minimale`)\n\n#Ecart type sur la temp?rature minimale\nsigma_tmp <- 0\nfor(j in 1:nrow(data_15_19))\n{\n sigma_tmp <- sigma_tmp+(moy_min_1-data_15_19$`temp_minimale`[j])^2\n \n}\nsigma_min_2 <- sqrt(sigma_tmp/(nrow(data_15_19)-1))\n\n#----------- COMPARAISON DES MOYENNES ----------------#\nprint(\"Moyennes pour l'?chantillon 1: \")\nprint(paste0(\"Temp?rature minimale: \", moy_min_1))\nprint(paste0(\"Temp?rature moyenne: \", moy_moyenne_1))\nprint(paste0(\"Temp?rature maximale: \", moy_max_1))\n\nprint(\"Moyennes pour l'?chantillon 2: \")\nprint(paste0(\"Temp?rature minimale: \", moy_min_2))\nprint(paste0(\"Temp?rature moyenne: \", moy_moyenne_2))\nprint(paste0(\"Temp?rature maximale: \", moy_max_2))\n\n#---------------- COMPARAISON DES ECARTS TYPE ----------#\nprint(\"Ecarts type pour l'?chantillon 1: \")\nprint(paste0(\"Temp?rature minimale: \", sigma_min_1))\nprint(paste0(\"Temp?rature moyenne: \", sigma_moy_1))\nprint(paste0(\"Temp?rature maximale: \", sigma_max_1))\n\nprint(\"Ecarts type pour l'?chantillon 2: \")\nprint(paste0(\"Temp?rature minimale: \", sigma_min_2))\nprint(paste0(\"Temp?rature moyenne: \", sigma_moy_2))\nprint(paste0(\"Temp?rature maximale: \", sigma_max_2))\n\nsigma_essai=sd(data_15_19$`Temp?rature maximale`)\nprint(paste0(\"ESSAI FONCTION SD \", sigma_essai))\nprint(sigma_essai)\n\n ", "meta": {"hexsha": "db0ff62bc0a1df0e0ccc81d644a3d51f1bac87c0", "size": 4527, "ext": "r", "lang": "R", "max_stars_repo_path": "R/r.r", "max_stars_repo_name": "ThomasGauci/TemperatureUS", "max_stars_repo_head_hexsha": "865ccf9c869adb92c4fbcc656a71436b5ab9b851", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-18T17:44:01.000Z", "max_issues_repo_path": "R/r.r", "max_issues_repo_name": "ThomasGauci/TemperatureUS", "max_issues_repo_head_hexsha": "865ccf9c869adb92c4fbcc656a71436b5ab9b851", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/r.r", "max_forks_repo_name": "ThomasGauci/TemperatureUS", "max_forks_repo_head_hexsha": "865ccf9c869adb92c4fbcc656a71436b5ab9b851", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3357142857, "max_line_length": 109, "alphanum_fraction": 0.7267506075, "num_tokens": 1699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8080672112416736, "lm_q1q2_score": 0.7362944394132134}} {"text": "> #1.\tDla zmiennych losowych przedstawionych w tabelach obliczyć podstawowe statystyki \n> # Wartość = 1, Prawdopodobieństwo = 1/6 (podobnie dla wartośći 2,3,4,5,6)\n> \n> #2.\tWygeneruj próby dla n=100 dla następujących rozkładów: Bernoulliego, Dwumianowego, Poissona \n> library(Rlab)\nBłąd w poleceniu 'library(Rlab)':nie ma pakietu o nazwie ‘Rlab’\n> Probs <- rep(1/6, 6)\n> items <- seq(1, 6, 1)\n> it_mean = mean(items)\n> it_median = median(items)\n> it_std = sd(items)\n> it_var = var(items)\n> n = 100\n> p = 0.2\n> k = 5\n> ber <- rbern(n,p)\nBłąd w poleceniu 'rbern(n, p)':nie udało się znaleźć funkcji 'rbern'\n> ber <- rber(n,p)\nBłąd w poleceniu 'rber(n, p)':nie udało się znaleźć funkcji 'rber'\n> library(Rlab)\nBłąd w poleceniu 'library(Rlab)':nie ma pakietu o nazwie ‘Rlab’\n> install.packages(\"Rlab\")\nWARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:\n\nhttps://cran.rstudio.com/bin/windows/Rtools/\nInstalling package into ‘C:/Users/Adam/Documents/R/win-library/3.6’\n(as ‘lib’ is unspecified)\npróbowanie adresu URL 'https://cran.rstudio.com/bin/windows/contrib/3.6/Rlab_2.15.1.zip'\nContent type 'application/zip' length 347255 bytes (339 KB)\ndownloaded 339 KB\n\npackage ‘Rlab’ successfully unpacked and MD5 sums checked\n\nThe downloaded binary packages are in\n\tC:\\Users\\Adam\\AppData\\Local\\Temp\\RtmpKIlQ6d\\downloaded_packages\n> library(Rlab)\nRlab 2.15.1 attached.\n\n\nDołączanie pakietu: ‘Rlab’\n\nNastępujące obiekty zostały zakryte z ‘package:stats’:\n\n dexp, dgamma, dweibull, pexp, pgamma, pweibull, qexp, qgamma, qweibull, rexp, rgamma, rweibull\n\nNastępujący obiekt został zakryty z ‘package:datasets’:\n\n precip\n\n> ber <- rbern(n,p)\n> bin <- rbinom(n,k,p)\n> poi <- rpois(n,p)\n> \n> # 3.\tPolicz dla nich statystyki podstawowe (średnią, wariancję, kurtozę i skośność). \n> \n> mean(ber)\n[1] 0.23\n> median(ber)\n[1] 0\n> var(ber)\n[1] 0.1788889\n> skew(ber)\n[1] 1.283171\n> kurt(ber)\n[1] 2.646527\n> \n> \n> mean(bin)\n[1] 0.92\n> median(bin)\n[1] 1\n> var(bin)\n[1] 0.599596\n> skew(bin)\n[1] 0.6624718\n> kurt(bin)\n[1] 3.275383\n> \n> \n> mean(poi)\n[1] 0.26\n> median(poi)\n[1] 0\n> var(poi)\n[1] 0.2145455\n> skew(poi)\n[1] 1.397018\n> kurt(poi)\n[1] 3.703055\n> \n> \n> # 4.Dla rozkładów Dwumianowego, Poissona narysuj wykresy rozkładu prawdopodobieństwa (dobierz dowolnie parametry)\n> \n> hist(bin)\n> hist(poi)\n> \n> \n> # 5.\tDla rozkładów Poissona i Dwumianowego wygeneruj rozkład prawdopodobieństwa dla n = 20, k = 0, …, 20 oraz p = 0.4. #Sprawdź, czy suma prawdopodobieństw wygenerowana dla tych rozkładów jest równa 1\n> \n> poi <- rpois(20,0.4)\n> P <- ecdf(poi)\n> plot(P)\n> \n> bin <- rbinom(20,20,0.4)\n> P <- ecdf(bin)\n> plot(P)\n> \n> \n> # 6.\tWygeneruj 30 danych dla rozkładu normalnego o średniej równej 0 i odchyleniu standardowym równym 2. Wyznacz statystyki podstawowe – czy są one równe z wartościami teoretycznymi? Sprawdź, czy zwiększenie liczby danych zwiększy dokładność wyliczeń statystyk opisowych. \n> \n> norm <- rnorm(10, 0, 2)\n> norm\n [1] -1.0128677 -0.8912117 1.2523880 -0.2495768 1.8834332 -0.3241169 0.9447989 0.5889541 -4.0469052 -0.0990004\n> print('mean - 0')\n[1] \"mean - 0\"\n> mean(norm)\n[1] -0.1954105\n> print('median - 0')\n[1] \"median - 0\"\n> median(norm)\n[1] -0.1742886\n> print('variance - 4') var(norm)\nBŁĄD: nieoczekiwany symbol in \"print('variance - 4') var\"\n> print('variance - 4')\n[1] \"variance - 4\"\n> var(norm)\n[1] 2.705355\n> print('skewness - 0')\n[1] \"skewness - 0\"\n> skew(norm)\n[1] -1.159013\n> print('kurtosis - 0')\n[1] \"kurtosis - 0\"\n> kurt(norm)\n[1] 4.147324\n> \n> \n> norm <- rnorm(100, 0, 2)\n> \n> print('mean - 0')\n[1] \"mean - 0\"\n> mean(norm)\n[1] 0.07480349\n> print('median - 0')\n[1] \"median - 0\"\n> median(norm)\n[1] 0.09660881\n> print('variance - 4')\n[1] \"variance - 4\"\n> var(norm)\n[1] 4.825696\n> print('kurtosis - 0')\n[1] \"kurtosis - 0\"\n> kurt(norm)\n[1] 3.351857\n> print('skewness - 0')\n[1] \"skewness - 0\"\n> skew(norm)\n[1] -0.3885361\n> \n> \n> norm <- rnorm(1000, 0, 2)\n> \n> print('mean - 0')\n[1] \"mean - 0\"\n> mean(norm)\n[1] 0.06857219\n> print('median - 0')\n[1] \"median - 0\"\n> median(norm)\n[1] 0.1334143\n> print('variance - 4')\n[1] \"variance - 4\"\n> var(norm)\n[1] 3.977514\n> print('skewness - 0')\n[1] \"skewness - 0\"\n> skew(norm)\n[1] -0.2148435\n> print('kurtosis - 0')\n[1] \"kurtosis - 0\"\n> kurt(norm)\n[1] 3.049271\n> \n> \n> # 7.\tNarysować histogram dla rozkładu normalnego o parametrach: średnia = 1, odchylenie =2, wykres dla rozkładu standardowego, oraz wykres gęstości dla średniej równej -1 oraz odchylenia równego 0.5. \n> \n> norm1 <- rnorm(1000, 1, 2)\n> norm2 <- rnorm(1000, 0, 1)\n> norm3 <- rnorm(1000, -1, 0.5)\n> \n> hist(norm1)\n> hist(norm2)\n> hist(norm3)\n> ", "meta": {"hexsha": "aec195b55e3443c2ba485bbed9f2d1b58c8f7d9b", "size": 4675, "ext": "r", "lang": "R", "max_stars_repo_path": "R/R_cw_3/R_cw_3.r", "max_stars_repo_name": "gradampl/Sts_Alg", "max_stars_repo_head_hexsha": "0008d84b525395488e95718391879ba5eddf4ea7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/R_cw_3/R_cw_3.r", "max_issues_repo_name": "gradampl/Sts_Alg", "max_issues_repo_head_hexsha": "0008d84b525395488e95718391879ba5eddf4ea7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/R_cw_3/R_cw_3.r", "max_forks_repo_name": "gradampl/Sts_Alg", "max_forks_repo_head_hexsha": "0008d84b525395488e95718391879ba5eddf4ea7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9743589744, "max_line_length": 274, "alphanum_fraction": 0.6684491979, "num_tokens": 2014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7362944390995957}} {"text": "library(tidyr)\nlibrary(dplyr)\nlibrary(stringr)\n\nas_decimal <- function(binary) {\n binary <- rev(binary)\n total <- 0\n for(j in 1:length(binary)) {\n c <- as.numeric(binary[j])\n total <-total + (c*(2^(j-1)))\n }\n return(total)\n}\n\ndata <- read.csv(\"input.csv\", header=FALSE) %>%\n mutate(row = str_sub(V1,1,7)) %>%\n mutate(column = str_sub(V1,8,11)) %>%\n mutate(row = str_replace_all(row,\"F\",\"0\")) %>%\n mutate(row = str_replace_all(row,\"B\", \"1\")) %>%\n mutate(column = str_replace_all(column, \"L\", \"0\")) %>%\n mutate(column = str_replace_all(column, \"R\", \"1\")) %>%\n mutate(row = str_split(row, boundary(\"character\"))) %>%\n mutate(column = str_split(column, boundary(\"character\"))) %>%\n rowwise() %>%\n mutate(row_dec = as_decimal(row)) %>%\n mutate(column_dec = as_decimal(column)) %>%\n mutate(seat_id = (row_dec*8)+column_dec)\n# Part 1\nprint(max(data$seat_id))\n# Part 2\ncompare <- tibble(seat_id=1:max(data$seat_id))\ncompare <- compare[-data$seat_id,]\nprint(compare)", "meta": {"hexsha": "b081c462d125a918b791d12f495a4f7950e92dad", "size": 980, "ext": "r", "lang": "R", "max_stars_repo_path": "day 5/solution.r", "max_stars_repo_name": "markwryan/r_advent_of_code_2020", "max_stars_repo_head_hexsha": "f4b756eef233ac23834771b271a9fd18839e612f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day 5/solution.r", "max_issues_repo_name": "markwryan/r_advent_of_code_2020", "max_issues_repo_head_hexsha": "f4b756eef233ac23834771b271a9fd18839e612f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day 5/solution.r", "max_forks_repo_name": "markwryan/r_advent_of_code_2020", "max_forks_repo_head_hexsha": "f4b756eef233ac23834771b271a9fd18839e612f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.696969697, "max_line_length": 63, "alphanum_fraction": 0.637755102, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7361667130621964}} {"text": "#' This function calculates depth in meters from pressure in decibars using Saunders and Fofonoff's method\n#' \\code{P} = pressure, in decibars\n#' \\code{lat} = degrees latitude\n#' \\code{Del} = geopotential anomaly (defaults to 0)\n#' \\code{method} = valid values include\"default\", \"seabird\", and \"unesco\", although they all appear to be treated the same\n#' \\code{DEPTH} = depth in M\n#' \n# DEEP-SEA RES., 1976, 23, 109-111.\n#' / UNITS:\n#' // PRESSURE P DECIBARS\n#' // LATITUDE LAT DEGREES\n#' // DEPTH DEPTH METERS\n#' // DTN. HEIGHT DEL DYN. METERS (geopotenial anomaly in J/kg:: assume 0) \n#' // CHECKVALUE:\n#' // 1.) DEPTH = 9712.653 M for P=10000 DECIBARS, LAT=30 DEG, DEL=0\n#' // ABOVE FOR STANDARD OCEAN: T=0 DEG CELSIUS; S=35 (PSS-78)\n#' // ----------------------------------------------------------\n#' // Original fortran code is found in:\n#' // UNESCO technical papers in marine science 44 (1983) -\n#' // 'Algorithms for computation of fundamental properties of seawater'\n#' \\url{http://www.code10.info/index.php?option=com_content&view=article&id=67:calculating-the-depth-from-pressure&catid=54:cat_coding_algorithms_seawater&Itemid=79}, \\url{http://www.code10.info/index.php?option=com_content&view=article&id=67:calculating-the-depth-from-pressure&catid=54:cat_coding_algorithms_seawater&Itemid=79}\n\n decibar2depth = function( P, lat, Del=0, method=\"default\" ) {\n \n if (method %in% c(\"default\", \"seabird\", \"unesco\" ) ) {\n \n X = (sin( lat * pi / 180 ))^2 # convert degree decimal to RADs\n\n # GR=GRAVITY VARIATION WITH LATITUDE: ANON (1970) BULLETIN GEODESIQUE\n GR = 9.780318 * (1.0 + (5.2788E-3 + 2.36E-5 * X) * X) + 1.092E-6 * P\n DepthTerm = (((-1.82E-15 * P + 2.279E-10) * P - 2.2512E-5) * P + 9.72659) * P ## assuming (35 psu, 0 C, and P=pressure in decibars )\n DEPTH = DepthTerm / GR + Del / 9.8\n return (DEPTH)\n }\n\n if (method %in% c(\"seabird\", \"unesco\") ){\n\n ## NOTE this method is the same as the above ...\n \n # http://www.seabird.com/application_notes/AN69.htm\n # \n # Sea-Bird uses the formula in UNESCO Technical Papers in Marine Science No. 44. \n # This is an empirical formula that takes compressibility (that is, density) into account. \n # An ocean water column at 0 °C (t = 0) and 35 PSU (s = 35) is assumed.\n # \n # The gravity variation with latitude and pressure is computed as:\n # \n # g (m/sec2) = 9.780318 * [ 1.0 + ( 5.2788x10 -3 + 2.36x10 -5 * x) * x ] + 1.092x10 -6 * p\n # \n # where \n # x = [sin (latitude / 57.29578) ] ^2 \n # p = pressure (decibars)\n # \n # Then, depth is calculated from pressure:\n # \n # depth (meters) = [(((-1.82x10 -15 * p + 2.279x10 -10 ) * p - 2.2512x10 -5 ) * p + 9.72659) * p] / g\n # \n # where \n # p = pressure (decibars) \n # g = gravity (m/sec2)\n \n # x = (sin (latitude / 57.29578) )^2\n # g = 9.780318 * [ 1.0 + ( 5.2788E-3 + 2.36E-5 * x) * x ] + 1.092E-6 * p\n # depth = ((((-1.82E-15 * p + 2.279E-10 ) * p - 2.2512E-5 ) * p + 9.72659) * p) / g\n\n\n }\n\n\n }\n\n\n", "meta": {"hexsha": "fce2cf4e40d21d763d4aca346bdd6ab7ec176c85", "size": 3321, "ext": "r", "lang": "R", "max_stars_repo_path": "R/decibar2depth.r", "max_stars_repo_name": "PEDsnowcrab/aegis", "max_stars_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/decibar2depth.r", "max_issues_repo_name": "PEDsnowcrab/aegis", "max_issues_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/decibar2depth.r", "max_forks_repo_name": "PEDsnowcrab/aegis", "max_forks_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:58:58.000Z", "avg_line_length": 45.4931506849, "max_line_length": 330, "alphanum_fraction": 0.5495332731, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7361667065005337}} {"text": "library(MASS) # ginv()\nlenth <- function(xy, theta, x.hat=NULL, i.max=1000, threshold=10.0^(-6)) {\n norm2 <- function(v) sum(v*v)\n #\n # Pseudo-MLE.\n #\n improve <- function(x, cs, xy){\n #\n # Improves an initial estimate `x` based on bearings as represented\n # by a 2 x * matrix of cosines and sines `cs` relative to locations `xy` \n # (as a 2 by * matrix).\n #\n if (is.null(x)) {\n cs.star <- cs # Starting estimate\n }\n else {\n xy.relative <- apply(xy, 2, function(v) x-v) # vectors towards x\n d <- apply(xy.relative, 2, function(v) norm2(v)^(3/2)) # cubed distances\n cs.star <- xy.relative / d # direction cosines\n }\n z <- cs[2,]*xy[1,] - cs[1,]*xy[2,] \n a <- cs.star %*% t(cs) * matrix(c(-1,-1,1,1), nrow=2) # Eq 2.6, lhs\n b <- cs.star %*% z # Eq 2.6, rhs\n u <- solve(a,b) # Solution\n c(u[2], u[1])\n }\n #\n # Convert bearings into direction cosines and sines.\n #\n cs <- sapply(theta, function(x) c(cos(x), sin(x)))\n #\n # Iterate until convergence.\n #\n if (is.null(x.hat)) x.hat <- improve(x.hat, cs, xy)\n repeat {\n x.new <- improve(x.hat, cs, xy)\n eps <- norm2(x.hat-x.new) / sqrt(max(apply(xy, 2, norm2)))\n lines(t(cbind(x.hat, x.new)), pch=2, col=\"Red\")\n x.hat <- x.new\n i.max <- i.max - 1\n if (eps <= threshold) break\n if (i.max < 0) stop(\"Convergence failed.\")\n }\n #\n # Estimate kappa.\n #\n mu.hat <- apply(x.hat - xy, 2, function(u) atan2(u[2], u[1]))\n c.bar <- mean(cos(theta - mu.hat))\n kappa.inv <- 2*(1-c.bar) + (1-c.bar)^2 * (0.48794/c.bar - 0.82905 - 1.3915*c.bar)\n kappa <- 1/kappa.inv\n #\n # Estimate the covariance matrix for x.hat.\n #\n xy.relative <- apply(xy, 2, function(v) x.hat - v)\n d <- apply(xy.relative, 2, function(v) norm2(v)^(3/2)) \n cs.star <- xy.relative / d \n q.hat <- cs.star %*% t(cs)\n q.hat <- (q.hat + t(q.hat))/2\n q.hat <- q.hat * matrix(c(1,-1,-1,1), nrow=2)\n q.hat <- q.hat[2:1, 2:1]\n q.hat <- ginv(q.hat, tol=10^(-16)) * kappa.inv\n x.se <- sqrt(q.hat[1,1])\n y.se <- sqrt(q.hat[2,2])\n\n list(x.hat=x.hat, cov=q.hat, se=c(x.se, y.se), kappa=kappa)\n}\n#--------------------------------------------------------------------------------------#\nset.seed(17)\n#\n# Target point.\n#\nx.0 <- c(1, 1)\n#\n# Observation points.\n#\nn <- 16\nxy <- matrix(rnorm(2*n), nrow=2)\ncs <- sapply(theta, function(x) c(cos(x), sin(x)))\n#\n# Simulate the observed bearings (in radians)\n#\nxy.fuzzy <- matrix(rnorm(2*n, sd=0.2), nrow=2) + x.0\ntheta <- apply(xy.fuzzy - xy, 2, function(u) atan2(u[2], u[1]))\n#\n# Obtain the MLE.\n#\nfit <- lenth(xy, theta)\n#\n# Plot all points.\n#\ncs <- sapply(theta, function(x) c(cos(x), sin(x)))\npar(mfrow=c(1,1))\nplot(t(cbind(xy, fit$x.hat, x.0)), asp=1, type=\"n\", xlab=\"x\", ylab=\"y\")\n temp <- sapply(1:length(theta), \n function(i) lines(t(cbind(xy[,i], xy[,i]+9*cs[,i])), col=\"Gray\"))\n points(t(xy))\n points(x.0[1], x.0[2], pch=19, col=\"Blue\") \n points(t(fit$x.hat), pch=19, col=\"Red\")\n#\n# Plot the 95% confidence ellipse.\n#\nlines(ellipse(fit$cov, centre=fit$x.hat, level=0.95), col=\"#AA4444\")", "meta": {"hexsha": "1e090cfdc31f6b3ff7059814cd9f750b8fc63ae9", "size": 3249, "ext": "r", "lang": "R", "max_stars_repo_path": "lenth-mle.r", "max_stars_repo_name": "theoperatore/triangulate", "max_stars_repo_head_hexsha": "eb8357de87a4d0fefa612470ee69ece49d25bc5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lenth-mle.r", "max_issues_repo_name": "theoperatore/triangulate", "max_issues_repo_head_hexsha": "eb8357de87a4d0fefa612470ee69ece49d25bc5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lenth-mle.r", "max_forks_repo_name": "theoperatore/triangulate", "max_forks_repo_head_hexsha": "eb8357de87a4d0fefa612470ee69ece49d25bc5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-06T17:44:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-06T17:44:07.000Z", "avg_line_length": 31.8529411765, "max_line_length": 88, "alphanum_fraction": 0.513388735, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7360872232596485}} {"text": "scaledf <- function(df, meanvec = NULL, scaledata = NULL, scalefactor = 2, zeromin = FALSE) {\r\n ## centers and scales a dataframe\r\n ## df = dataframe of parameters to be scaled\r\n ## meanvec = vector of mean values for centering\r\n ## default uses means of df for centering\r\n ## scaledata = dataframe used to provide range of each parameter for scaling\r\n ## default uses range of df for scaling\r\n ## scalefactor = number used to set range of scaled data (multiplies data by scalefactor / range of scaledata)\r\n ## (2 results in -1 to +1 if centered and ranges of scaledata are equal distant from mean)\r\n ## (1 results in 0 to +1 if zeroed and ranges of scaledata are equal distant from mean)\r\n ## zeromin = FALSE (default) results in center of scaled df at 0 if ranges of scaledata are equal distant from mean)\r\n ## = TRUE results in min of scaled df at 0 if ranges of scaledata are equal distant from mean)\r\n ## suffix \"_s\" to be added to each variable to identify it is scaled\r\n \r\n ## center data\r\n if (missing(meanvec)) meanvec <- apply(df, 2, mean) # use mean of df to center\r\n # subtract meanvec from each row in df; output is a dataframe\r\n dfcenter <- sweep(df, 2, meanvec, \"-\") \r\n \r\n ## scale centered data\r\n if (missing(scaledata)) scaledata <- df # use range of df to scale\r\n ## calculate vector (1 value for each parameter in scaledata) = range of parameter / scalefactor\r\n scalerange <- (sapply(scaledata,max) - sapply(scaledata,min)) / scalefactor\r\n ## divide every row in dfcenter by scalerange\r\n dfs <- sweep(dfcenter, 2, scalerange, \"/\")\r\n\r\n ## adjust location center if needed\r\n if (zeromin == TRUE) dfs <- sweep(dfs, 2, (scalefactor/2), \"+\")\r\n \r\n ## ## convert to dataframe and ad suffix to column names\r\n ## dfs <- data.frame(dfs)\r\n ## names(dfs) <- paste(names(dfs), \"_s\", sep = \"\")\r\n \r\n ## return parameters\r\n return( list(dfs=dfs, meanvec=meanvec, scaledata=scaledata, scalefactor=scalefactor, zeromin=zeromin) )\r\n}\r\n# dfs.out <- scaledf(df)$dfs\r\n# dfs <- dfs.out$dfs\r\n# summary(dfs)\r\n\r\n", "meta": {"hexsha": "1187aca8476b86728d42453fc94474afaac7b8d1", "size": 2234, "ext": "r", "lang": "R", "max_stars_repo_path": "modules/scaledf.r", "max_stars_repo_name": "TECComputing/R-setup", "max_stars_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/scaledf.r", "max_issues_repo_name": "TECComputing/R-setup", "max_issues_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/scaledf.r", "max_forks_repo_name": "TECComputing/R-setup", "max_forks_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-16T12:06:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T12:06:21.000Z", "avg_line_length": 54.487804878, "max_line_length": 125, "alphanum_fraction": 0.6248880931, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7358914642181208}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Goodness of Fit - Exercise 05\n\nrm(list = ls())\n\n\nobserved <- c(34, 10, 20)\n\n(k <- length(observed))\n# 3\n\n(n <- sum(observed))\n# 64\n\nproportion <- c(9, 3, 2)\n\n(expected <- n * proportion / sum(proportion))\n# 41.1428571428571 13.7142857142857 9.14285714285714\n\n(Q <- sum((observed - expected) ^ 2 / expected))\n# 15.1388888888889\n\n(pvalue <- 1 - pchisq(Q, df = k - 1))\n# 0.000515979024014124\n", "meta": {"hexsha": "22f7e3f53df455500018d43349d69eff33083e89", "size": 454, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/goodness-of-fit/exercise-05.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/goodness-of-fit/exercise-05.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/goodness-of-fit/exercise-05.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.16, "max_line_length": 63, "alphanum_fraction": 0.6519823789, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.96741025335478, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.7358612511190554}} {"text": "buckets <- read.delim(\"~/gas-simulator/buckets.txt\", sep=\" \", header=F)\n\nfn <- buckets\n\nfor(vv in buckets[1]) {\n r <- 1\n for (v in vv) {\n fn[r,2] <- fn[r,2]/(4*pi*fn[r,1]^2)*2900000 # 10 is for scale\n r <- r+1\n }\n}\n\n#\n# Maxwell distribution\n#\n\n# f(v)dv = √(m/2pikT)^3*4*pi*v^2*exp(-mv^2/(2kT))*dv\n\n# assume homogeneous buckets distribution in velocity\ndv <- buckets[3,1] - buckets[2,1]\nmaxwell <- buckets\n\n# physical constants\nNa = 6.022e+23\nR = 8.3144598\nk = R/Na\n\n# params\nN = 1000000\nm = 6.646476410e-27\nT = 293.321\n\n# compute maxwell distribution\nfor(vv in buckets[1]) {\n r <- 1\n for (v in vv) {\n maxwell[r,2] <- N*((m/(2*pi*k*T))^(3/2))*(4*pi*v^2)*exp(-m*(v^2)/(2*k*T))*dv\n r <- r+1\n }\n}\n\nsum(buckets[2])\nsum(maxwell[2])\n\nplot(buckets, type=\"o\",\n xlab=\"Velocity\",\n ylab=\"Number of particles\"\n)\nlines(fn, type=\"o\", col=\"red\")\nlines(maxwell, type=\"o\", col=\"green\")\n", "meta": {"hexsha": "46db7559dbf69babfbea742de6f8f74268c30e7d", "size": 888, "ext": "r", "lang": "R", "max_stars_repo_path": "show-sim-data.r", "max_stars_repo_name": "yurivict/gas-simulator", "max_stars_repo_head_hexsha": "74c38f48fb8cc0b87432e14f420abac376e985ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "show-sim-data.r", "max_issues_repo_name": "yurivict/gas-simulator", "max_issues_repo_head_hexsha": "74c38f48fb8cc0b87432e14f420abac376e985ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "show-sim-data.r", "max_forks_repo_name": "yurivict/gas-simulator", "max_forks_repo_head_hexsha": "74c38f48fb8cc0b87432e14f420abac376e985ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4117647059, "max_line_length": 80, "alphanum_fraction": 0.5878378378, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7357894701018632}} {"text": "## defaults for matrix size and cp for synthetic wavefront construction\n\nnrow.default <- 640\nncol.default <- nrow.default\ncp.default <- list(xc=320.5, yc=320.5, rx=319.5, ry=319.5, obstruct=0)\n\n## create a unit aperture inside a matrix of arbitrary size\n## note the parameter cp is a list with components (xc, yc, rx, ry, obstruct) as returned by pupil.pars()\n\npupil <- function(zcoef=NULL, maxorder=14L, isoseq=FALSE, \n phi=0, piston=NULL,\n nrow=nrow.default, ncol=ncol.default, \n cp=cp.default) {\n \n prt <- pupil.rhotheta(nrow, ncol, cp)\n rho <- prt$rho\n theta <- prt$theta\n rho.v <- rho[!is.na(rho)]\n theta.v <- theta[!is.na(rho)] - pi*phi/180\n wf.v <- numeric(length(rho.v))\n if (cp$obstruct > 0) {\n use.circ <- FALSE\n } else {\n use.circ <- TRUE\n }\n if (!is.null(zcoef)) {\n if (!is.null(piston)) {\n zcoef <- c(piston, zcoef)\n }\n if (isoseq) {\n if (use.circ) {\n wf.v <- zpm_cart(x=rho.v*cos(theta.v), y=rho.v*sin(theta.v), maxorder=maxorder) %*% zcoef\n } else {\n wf.v <- zapm_cart(x=rho.v*cos(theta.v), y=rho.v*sin(theta.v), maxorder=maxorder) %*% zcoef\n }\n } else {\n if (use.circ) {\n wf.v <- zpm(rho.v, theta.v, maxorder = maxorder) %*% zcoef\n } else {\n wf.v <- zapmC(rho.v, theta.v, maxorder = maxorder) %*% zcoef\n }\n }\n }\n wf <- matrix(NA, nrow=nrow, ncol=ncol)\n wf[!is.na(rho)] <- wf.v\n class(wf) <- c(\"pupil\", class(wf))\n wf\n}\n \npupil.arb <- function(zcoef=NULL, zlist=makezlist(), \n phi=0, piston=0,\n nrow=nrow.default, ncol=ncol.default, \n cp=cp.default) {\n\n prt <- pupil.rhotheta(nrow, ncol, cp)\n rho <- prt$rho\n theta <- prt$theta\n rho.v <- rho[!is.na(rho)]\n theta.v <- theta[!is.na(rho)]\n wf.v <- numeric(length(rho.v))\n if (!is.null(zcoef)) {\n wf.v <- zpm.arb(rho.v, theta.v, phi, zlist=zlist) %*% zcoef\n }\n wf <- matrix(NA, nrow=nrow, ncol=ncol)\n wf[!is.na(rho)] <- wf.v\n wf <- wf+piston\n class(wf) <- c(\"pupil\", class(wf))\n wf\n}\n\n## estimate of rms over pupil\n\npupilrms <- function(pupil) {\n sd(as.vector(pupil), na.rm=TRUE)\n}\n\n## estimate of p-v over pupil\n\npupilpv <- function(pupil) {\n max(pupil, na.rm=TRUE) - min(pupil, na.rm=TRUE)\n}\n\n#' Zygo's \"robust\" PV\n#'\n#' A peak to valley error estimate that reduces the effect of noise and artifacts\n#'\n#' @param wf.zfit matrix containing the smoothed Zernike fit wavefront\n#' @param wf.residual matrix of the difference between the raw wavefront\n#' and the Zernike fit. These values are returned by [wf_net()]\n#' @return the estimated PVr\n#' @references\n#' Evans, C. (2009) Optical Engineering 48(4), 43605.\n#' \n#'\n#' @details\n#' no check is performed on the wavefronts, so it's the user's\n#' responsibility to make sure these come from the same source\nPVr <- function(wf.zfit, wf.residual) {\n pvr <- pupilpv(wf.zfit) + 3*sd(wf.residual, na.rm=TRUE)\n pvr\n}\n\n## Mahajan's approximation to Strehl ratio\n\nstrehlratio <- function(rms) {\n exp(-(2*pi*rms)^2)\n}\n\n## a summary method for pupils\n\nsummary.pupil <- function(wf, digits=3) {\n\tcat(\"Size: \",nrow(wf), \"x\",ncol(wf),\"\\n\")\n\tcat(\"RMS =\", format(pupilrms(wf), digits=digits), \"\\n\")\n\tcat(\"P-V =\", format(pupilpv(wf), digits=digits), \"\\n\")\n\tcat(\"Strehl =\", format(strehlratio(pupilrms(wf)), digits=digits), \"\\n\")\n}\n\n## a plot method for pupils\n\nplot.pupil <- function(wf, cp=NULL, col=topo.colors(256), addContours=TRUE, \n cscale=FALSE, eqa=FALSE, zlim=NULL, ...) {\n nr <- nrow(wf)\n nc <- ncol(wf)\n if(is.null(zlim)) zlim <- range(wf, finite=TRUE)\n if(eqa) wfcdf <- ecdf(wf[!is.na(wf)])\n if (cscale) {\n mar.orig <- (par.orig <- par(c(\"mar\", \"las\", \"mfrow\")))$mar\n on.exit(par(par.orig))\n w <- (3 + mar.orig[2]) * par(\"csi\") * 2.54\n layout(matrix(c(2, 1), ncol = 2), widths = c(1, lcm(w)))\n par(las = 1)\n mar <- mar.orig\n mar[4] <- mar[2]\n mar[2] <- 1\n par(mar = mar)\n levels <- seq(zlim[1], zlim[2], length=length(col)+1)\n plot.new()\n plot.window(xlim=c(0,1),ylim=range(levels), xaxs=\"i\", yaxs=\"i\")\n if (eqa) {\n vcol <- col[round((length(col)-1)*wfcdf(seq(zlim[1],zlim[2],length=length(col)))+1)]\n } else vcol <- col\n\trect(0, levels[-length(levels)], 1, levels[-1], col=vcol, density=NA)\n axis(4)\n box()\n mar <- mar.orig\n mar[4] <- 0\n par(mar = mar)\n }\n if (is.null(cp)) {\n axis1 <- 1:nr\n axis2 <- 1:nc\n } else {\n axis1 <- ((1:nr)-cp$xc)/cp$rx\n axis2 <- ((1:nc)-cp$yc)/cp$ry\n }\n if (eqa) {\n iwf <- wfcdf(wf[!is.na(wf)])\n iwfm <- wf\n iwfm[!is.na(iwfm)] <- iwf\n zlim <- wfcdf(zlim)\n col1 <- round((length(col)-1)*zlim[1]+1)\n col2 <- round((length(col)-1)*zlim[2]+1)\n image(axis1, axis2, iwfm, zlim=zlim, asp=1, col=col[col1:col2], \n xlab=\"X\", ylab=\"Y\", useRaster=TRUE, ...)\n } else {\n image(axis1, axis2, wf, zlim=zlim, asp=1, col=col, \n xlab=\"X\", ylab=\"Y\", useRaster=TRUE, ...)\n }\n if (addContours) contour(axis1, axis2, wf, add=TRUE)\n}\n\n## RGL animated 3D plot\n\n## administrative stuff needed to make this a method for class \"pupil\"\n\nwf3d <- function(wf, ...) UseMethod(\"wf3d\", wf)\n\ncol3d <- function(wf, surf.col=topo.colors(256), zlim = NULL, eqa=FALSE) {\n\tif (is.null(zlim)) zlim <- range(wf, na.rm=TRUE)\n if (eqa) {\n wfcdf <- ecdf(wf[!is.na(wf)])\n iwf <- wfcdf(wf[!is.na(wf)])\n wf[!is.na(wf)] <- iwf\n zlim <- wfcdf(zlim)\n }\n surf.col[(length(surf.col)-1)*(wf-zlim[1])/(zlim[2]-zlim[1])+1]\n}\n\nwf3d.pupil <- function(wf, cp=NULL, zoom.wf=1, surf.col=topo.colors(256), bg.col=\"black\",\n eqa=FALSE) {\n require(rgl)\n zlim <- range(wf, na.rm=TRUE)\n col <- col3d(wf, surf.col, zlim, eqa)\n if (is.null(cp)) {\n axis1 <- seq(-1, 1, length=nrow(wf))\n axis2 <- seq(-1, 1, length=ncol(wf))*(ncol(wf)/nrow(wf))\n } else {\n axis1 <- ((1:nrow(wf))-cp$xc)/cp$rx\n axis2 <- ((1:ncol(wf))-cp$yc)/cp$ry\n }\n\n rgl.bg(sphere=FALSE, fogtype=\"exp2\", color=bg.col)\n rgl.surface(-axis1, axis2, wf*zoom.wf, color=col, shininess=100)\n rgl.lines(c(-1,-1.25)*max(axis1),c(0,0),c(0,0),color=\"red\", lit=FALSE)\n rgl.lines(c(0,0),c(0,0),c(1,1.25)*max(axis2),color=\"red\", lit=FALSE)\n rgl.texts(-1.3*max(axis1),0,0, \"X\", color=\"red\")\n rgl.texts(0,0,1.3*max(axis2), \"Y\", color=\"red\")\n}\n\n## polar coordinates inside the unit radius pupil\n\npupil.rhotheta <- function(nrow, ncol, cp) {\n\txs <- ((1:nrow)-cp$xc)/cp$rx\n\tys <- ((1:ncol)-cp$yc)/cp$ry\n\trho <- function(x,y) sqrt(x^2+y^2)\n\ttheta <- function(x,y) atan2(y,x)\n\trho.mat <- outer(xs, ys, rho)\n\ttheta.mat <- outer(xs,ys,theta)\n\trho.mat[rho.mat>1] <- NA\n\trho.mat[rho.mat= corrdat)/length(corr)\nsum(vr >= vrdat)/length(vr)\n\nfill.lm <- lm(Sodium ~ Beer, data=beers)\ncorrobs <- cor(sort(residuals(fill.lm)),qnorm((1:48)/49))\n\npostscript(\"../beerdata.eps\",horiz=F,width=6,height=4)\npar(mfrow=c(1,1), pty=\"m\", mar=c(4,4,2,1)+0.1)\n\nplot(beers$Beer,beers$Sodium,pch=16, xlab=\"Beer\", ylab=\"Sodium\")\npoints(1:6,sodium,pch=16,col=2)\ndev.off()\n\npostscript(\"../beerhyper.eps\",horiz=F,width=8,height=5)\npar(mfrow=c(1,2), pty=\"m\", mar=c(4,4,2,1)+0.1)\n\nhist(tausim,prob=T,xlim=c(0,30), xlab=expression(tau),main=\"\")\nlines(tau,post/mean(post)/40,col=2)\n\nhist(musim,prob=T, xlab=expression(mu),xlim=c(10,30),main=\"\")\n\ndev.off()\n\npostscript(\"../beertheta.eps\",horiz=F,width=8,height=5)\npar(mfrow=c(2,3), pty=\"m\", mar=c(4,4,2,1)+0.1)\n\nhist(thetasim[,1],prob=T, xlab=expression(theta[1]),\n main=\"Beer 1\")\npoints(sodium[1],0,pch=16,col=2)\npoints(mean(thetasim[,1]),0,pch=16,col=4)\nhist(thetasim[,2],prob=T, xlab=expression(theta[2]),\n main=\"Beer 2\")\npoints(sodium[2],0,pch=16,col=2)\npoints(mean(thetasim[,2]),0,pch=16,col=4)\nhist(thetasim[,3],prob=T, xlab=expression(theta[3]),\n main=\"Beer 3\")\npoints(sodium[3],0,pch=16,col=2)\npoints(mean(thetasim[,3]),0,pch=16,col=4)\nhist(thetasim[,4],prob=T, xlab=expression(theta[4]),\n main=\"Beer 4\")\npoints(sodium[4],0,pch=16,col=2)\npoints(mean(thetasim[,4]),0,pch=16,col=4)\nhist(thetasim[,5],prob=T, xlab=expression(theta[5]),\n main=\"Beer 5\")\npoints(sodium[5],0,pch=16,col=2)\npoints(mean(thetasim[,5]),0,pch=16,col=4)\nhist(thetasim[,6],prob=T, xlab=expression(theta[6]),\n main=\"Beer 6\")\npoints(sodium[6],0,pch=16,col=2)\npoints(mean(thetasim[,6]),0,pch=16,col=4)\ndev.off()\n\n\npostscript(\"../beercheck.eps\",horiz=F,width=8,height=3.5)\npar(mfrow=c(1,2), pty=\"m\", mar=c(4,4,2,1)+0.1)\n\nhist(corr,prob=T, xlab=\"Correlation\",\n main=\"\")\nabline(v=corrobs,col=2)\nhist(vr,prob=T, xlab=\"Variance Ratio\",\n main=\"\")\nabline(v=vrdat,col=2)\ndev.off()\n", "meta": {"hexsha": "cf86e64dad7c19125a4bd107925d6f4b0551bfa3", "size": 3317, "ext": "r", "lang": "R", "max_stars_repo_path": "HW5/beersampler_502009041.r", "max_stars_repo_name": "goldsail/BayesianHomework", "max_stars_repo_head_hexsha": "d5506faccbf4d0b7b696c7c2bcb42d020bb0d357", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-07T18:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-07T18:55:43.000Z", "max_issues_repo_path": "HW5/beersampler_502009041.r", "max_issues_repo_name": "kingium/BayesianHomework", "max_issues_repo_head_hexsha": "d5506faccbf4d0b7b696c7c2bcb42d020bb0d357", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW5/beersampler_502009041.r", "max_forks_repo_name": "kingium/BayesianHomework", "max_forks_repo_head_hexsha": "d5506faccbf4d0b7b696c7c2bcb42d020bb0d357", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8434782609, "max_line_length": 101, "alphanum_fraction": 0.6493819717, "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7352642677381945}} {"text": "analyze_bivariate_data <- function(matrix, explanatory_variable, response_variable) {\n relationship <- \"linear\"\n r <- cor(matrix[,1], matrix[,2])\n\n exponential_r <- cor(matrix[,1], log(matrix[,2]))\n if (exponential_r > r) {\n relationship <- \"exponential\"\n r <- exponential_r\n }\n\n logarithmic_r <- cor(log(matrix[,1]), matrix[,2])\n if (logarithmic_r > r) {\n relationship <- \"logarithmic\"\n r <- logarithmic_r\n }\n\n power_r <- cor(log(matrix[,1]), log(matrix[,2]))\n if (power_r > r) {\n relationship <- \"power\"\n r <- power_r\n }\n\n r <- round(r, 4)\n\n inc_or_dec <- if (r > 0) \"increase\" else \"decrease\"\n\n linear_description <- \"\"\n if (abs(r) < 0.5) {\n linear_description <- \"weakly\"\n } else if (abs(r) < 0.8) {\n linear_description <- \"moderately\"\n } else if (abs(r) <= 1) {\n linear_description <- \"strongly\"\n }\n\n title <- paste(c(explanatory_variable, \"vs.\", response_variable), collapse = \" \")\n\n plot(matrix[,1], matrix[,2], main = title, xlab = explanatory_variable, ylab = response_variable)\n\n if (relationship == \"linear\") {\n abline(lm(matrix[,2] ~ matrix[,1]))\n }\n\n return(paste(c(\"As \", explanatory_variable, \" increases, \", response_variable, \" tends to \", inc_or_dec, \". The association is \", linear_description, \" \", relationship, \", as evidenced by r = \", r, \".\"), collapse = \"\"))\n}\n", "meta": {"hexsha": "9afd1ffe9d91363b04c78e6757200b3e5e20b240", "size": 1425, "ext": "r", "lang": "R", "max_stars_repo_path": "src/bivariate.r", "max_stars_repo_name": "jackcook/statistician", "max_stars_repo_head_hexsha": "2c0a83830d1815230626b76f6e8c1dacc8887b01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bivariate.r", "max_issues_repo_name": "jackcook/statistician", "max_issues_repo_head_hexsha": "2c0a83830d1815230626b76f6e8c1dacc8887b01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bivariate.r", "max_forks_repo_name": "jackcook/statistician", "max_forks_repo_head_hexsha": "2c0a83830d1815230626b76f6e8c1dacc8887b01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9782608696, "max_line_length": 223, "alphanum_fraction": 0.5845614035, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7351711973241503}} {"text": "## Dale W.R. Rosenthal, 2018\n## You are free to distribute and use this code so long as you attribute\n## it to me or cite the text.\n## The legal disclaimer in _A Quantitative Primer on Investments with R_\n## applies to this code. Use or distribution without these comment lines\n## is forbidden.\nlibrary(xts)\nlibrary(Quandl)\n\n## Get 6 contracts of the crude curve\ncrude.tickers <- c(\"CHRIS/CME_CL1\", \"CHRIS/CME_CL2\", \"CHRIS/CME_CL3\",\n \"CHRIS/CME_CL4\", \"CHRIS/CME_CL5\", \"CHRIS/CME_CL6\")\nsettle.field <- \"Settle\"\ncrude.prices <- Quandl(crude.tickers[1], type=\"xts\")[,settle.field]\nfor (i in 2:length(crude.tickers)) {\n crude.tmp <- Quandl(crude.tickers[i], type=\"xts\")[,settle.field]\n crude.prices <- cbind(crude.prices, crude.tmp)\n}\ncolnames(crude.prices) <- paste(\"CL\", 1:6, sep=\"\")\n\ncrude.returns <- na.omit(diff(log(crude.prices)))\npc.crude <- princomp(crude.returns)\nsummary(pc.crude)\nloadings(pc.crude)\n\n## Get 6 contracts of the natgas curve\nnatgas.tickers <- c(\"CHRIS/CME_NG1\", \"CHRIS/CME_NG2\", \"CHRIS/CME_NG3\",\n \"CHRIS/CME_NG4\", \"CHRIS/CME_NG5\", \"CHRIS/CME_NG6\")\nsettle.field <- \"Settle\"\nnatgas.prices <- Quandl(natgas.tickers[1], type=\"xts\")[,settle.field]\nfor (i in 2:length(natgas.tickers)) {\n natgas.tmp <- Quandl(natgas.tickers[i], type=\"xts\")[,settle.field]\n natgas.prices <- cbind(natgas.prices, natgas.tmp)\n}\ncolnames(natgas.prices) <- paste(\"NG\", 1:6, sep=\"\")\n\nnatgas.returns <- na.omit(diff(log(natgas.prices)))\npc.natgas <- princomp(natgas.returns)\nsummary(pc.natgas)\nloadings(pc.natgas)\n", "meta": {"hexsha": "76bd991fb82f9218d0f68922daeab2a85fc55fa0", "size": 1550, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch19-exercises.r", "max_stars_repo_name": "bmoretz/Quantitative-Investments", "max_stars_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-26T05:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T21:50:54.000Z", "max_issues_repo_path": "Quantitative Primer/samples/ch19-exercises.r", "max_issues_repo_name": "bmoretz/Quantitative-Investments", "max_issues_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quantitative Primer/samples/ch19-exercises.r", "max_forks_repo_name": "bmoretz/Quantitative-Investments", "max_forks_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-03T09:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:50:55.000Z", "avg_line_length": 37.8048780488, "max_line_length": 73, "alphanum_fraction": 0.6929032258, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7349774383178654}} {"text": "rm(list=ls(all=TRUE))\n\nprior_heads = 10\nprior_tails = 10\nheads = 3\ntails = 7\n\npost_heads = prior_heads + heads\npost_tails = prior_tails + tails\nepost_heads = prior_heads + (2 * heads)\nepost_tails = prior_tails + (2 * tails)\n\nq = seq(0, 1, 0.005)\nprior = dbeta(q, prior_heads, prior_tails)\npost = dbeta(q, post_heads, post_tails)\nepost = dbeta(q, epost_heads, epost_tails)\nymax = max(epost) + (0.02 * max(epost))\n\npost_prob_unfair_heads = pbeta(0.5, post_heads, post_tails,\n lower.tail = F)\nepost_prob_unfair_heads = pbeta(0.5, epost_heads, epost_tails,\n lower.tail = F)\npost_mode = (post_heads - 1) / (post_heads + post_tails - 2)\nepost_mode = (epost_heads - 1) / (epost_heads + epost_tails - 2)\ncat(paste('post prob unfair heads: ', post_prob_unfair_heads, '\\n'))\ncat(paste('emp post prob unfair heads: ', epost_prob_unfair_heads, '\\n'))\ncat(paste('post mode: ', post_mode, '\\n'))\ncat(paste('emp post mode: ', epost_mode, '\\n'))\n\npdf('coin_flip.pdf', width=7.087, height=4.5)\npar(yaxs=\"i\", xaxs=\"i\", cex.lab=1.2, cex.axis=1.0, mgp=c(2.2, 0.7, 0),\n oma=c(0, 0, 0.2, 0.5), mar=c(3.2, 3.2, 0.5, 0.1))\nplot(x=c(), y = c(), xlab=bquote(theta), ylab='Density', xlim=c(0,1),\n ylim=c(0, ymax))\nlines(q, prior)\nlines(q, post, col='blue')\nlines(q, epost, col='red')\ndev.off()\n\n", "meta": {"hexsha": "155bada6074ed18e2c4ecfdbd036bc4d4f9c7dbc", "size": 1336, "ext": "r", "lang": "R", "max_stars_repo_path": "manuscripts/images/coin_flip.r", "max_stars_repo_name": "joaks1/msbayes-experiments", "max_stars_repo_head_hexsha": "72fcf3c26f6d92bdcc39343372552f45d72d8f7f", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manuscripts/images/coin_flip.r", "max_issues_repo_name": "joaks1/msbayes-experiments", "max_issues_repo_head_hexsha": "72fcf3c26f6d92bdcc39343372552f45d72d8f7f", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuscripts/images/coin_flip.r", "max_forks_repo_name": "joaks1/msbayes-experiments", "max_forks_repo_head_hexsha": "72fcf3c26f6d92bdcc39343372552f45d72d8f7f", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4, "max_line_length": 73, "alphanum_fraction": 0.6377245509, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7349394927425604}} {"text": "#1\n\n#perform the ANOVA and save the results to plantanova\nplantanova<-aov(weight~group, PlantGrowth)\n\n#view the ANOVA data\nanova(plantanova)\n\n#p-value = 0.0159. p-value is less than the significance level of 0.05, So we can reject the null hypothesis that the mean growth is the same for all treatments.\n\n#p-value = 0.0159.This means that, if the effect of all three treatments were the same, we would have less than 2% chance of seeing differences between groups as large or larger than this\n\ncoef(plantanova)\n\n#Control treatment gives an average weight of 5.032. The effect of treatment 1 (trt1) is to reduce weight by an average of -0.371 units compared to the control method, and the effect of treatment 2 (trt2) is to increase weight by an average of 0.494 units compared to the control method.\n\n#2\n\nbottles<-read.csv(\"bottles.csv\")\nks.test(bottles$Volume, \"pnorm\", 500, 25)\n\n#The p-value for the one-sample Kolmogorov-Smirnov test is 0.2108. As this is not less than the significance level of 0.05, we can not reject the null hypothesis. This means that there is no evidence that the bottle volumes are not drawn from the normal distribution.\n\n#3\n\ndbinom(2,10,1/6)\n#The probability of throwing exactly two sixes, when a fair die is rolled 10 times is 0.29071 or 29.071%\n\n#4\n\ndpois(18,20)\n# the probability that exactly eighteen lobsters will be ordered tomorrow is 8.4%\n\n#5\n\nairquality_dataset<-as.data.frame(airquality)\nsummary(airquality_dataset)\nairquality_dataset=na.omit(airquality_dataset)\n\nmax_data<-apply(airquality_dataset,2,max)\nmin_data<-apply(airquality_dataset,2, min)\ndata_scaled<-scale(airquality_dataset,center=min_data,scale=max_data-min_data)\nsummary(data_scaled)\n\n#6\n\nairquality_dataset<-as.data.frame(airquality)\nsummary(airquality_dataset)\nairquality_dataset=na.omit(airquality_dataset)\n\nmean_data<-apply(airquality_dataset, 2, mean)\nstd_data<-apply(airquality_dataset, 2, sd)\n\ndata_scaled<-scale(airquality_dataset, center=mean_data, scale=std_data)\nsummary(data_scaled)", "meta": {"hexsha": "178e51f8bf5b599bb7ae061a2f0d758cc54f3042", "size": 1998, "ext": "r", "lang": "R", "max_stars_repo_path": "R Community/R Stats_Basics Part 2/programs.r", "max_stars_repo_name": "vaibhavkrishna-bhosle/Trendnxt-Projects", "max_stars_repo_head_hexsha": "6c8a31be2f05ec79cfc5086ee09adff161b836ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R Community/R Stats_Basics Part 2/programs.r", "max_issues_repo_name": "vaibhavkrishna-bhosle/Trendnxt-Projects", "max_issues_repo_head_hexsha": "6c8a31be2f05ec79cfc5086ee09adff161b836ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R Community/R Stats_Basics Part 2/programs.r", "max_forks_repo_name": "vaibhavkrishna-bhosle/Trendnxt-Projects", "max_forks_repo_head_hexsha": "6c8a31be2f05ec79cfc5086ee09adff161b836ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3272727273, "max_line_length": 287, "alphanum_fraction": 0.7902902903, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7348244856602963}} {"text": "=begin\n # sample-polynomial02.rb\n\n require \"algebra\"\n P = Polynomial(Integer, \"x\", \"y\", \"z\")\n x, y, z = P.vars\n p((-x + y + z)*(x + y - z)*(x - y + z))\n #=> -z^3 + (y + x)z^2 + (y^2 - 2xy + x^2)z - y^3 + xy^2 + x^2y - x^3\n \n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "809ff2f11883442a8aeb207491e8cae9f554c881", "size": 253, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-polynomial02.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-polynomial02.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-polynomial02.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0833333333, "max_line_length": 70, "alphanum_fraction": 0.4505928854, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7347170647256009}} {"text": "findfactors <- function(n) {\n d <- c()\n div <- 2; nxt <- 3; rest <- n\n while( rest != 1 ) {\n while( rest%%div == 0 ) {\n d <- c(d, div)\n rest <- floor(rest / div)\n }\n div <- nxt\n nxt <- nxt + 2\n }\n d\n}\n\nprint(findfactors(1005025))\n", "meta": {"hexsha": "60bafc131b6b63e8477d74d52e9deb9d74ac86a5", "size": 257, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Prime-decomposition/R/prime-decomposition.r", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Task/Prime-decomposition/R/prime-decomposition.r", "max_issues_repo_name": "djgoku/RosettaCodeData", "max_issues_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Prime-decomposition/R/prime-decomposition.r", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0625, "max_line_length": 31, "alphanum_fraction": 0.4552529183, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7347090642554717}} {"text": "## Output : A matrix such that the\n## column sums are item log-likelihood values, and\n## row sums are person log-likelihood values.\nlog.prob <- function(U.data, th, a, b) {\n ## Step 1: Build the matrix of probabilities \n ## (see Post 2 for details) \n term.1 <- outer(th, a)\n term.2 <- matrix(rep(a*b, P.persons), nrow=P.persons, \n byrow=TRUE)\n P.prob <- plogis(term.1 - term.2) #### 1/(1 + exp(term.2 - term.1))\n \n ## Step 2: Build the likelihood from Equation 1 on the log scale\n log.bernoulli <- log(P.prob^U.data) + log((1-P.prob)^(1-U.data))\n return(log.bernoulli)\n}", "meta": {"hexsha": "4de3d95d421e152233a8b1039773fe8e682ffe67", "size": 695, "ext": "r", "lang": "R", "max_stars_repo_path": "2PL/functions/logprob.r", "max_stars_repo_name": "jevanluo/BayesianIRT", "max_stars_repo_head_hexsha": "788b34e951968222493b7ad2c65f3086ddff84e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-23T03:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:45:25.000Z", "max_issues_repo_path": "2PL/functions/logprob.r", "max_issues_repo_name": "jevanluo/BayesianIRT", "max_issues_repo_head_hexsha": "788b34e951968222493b7ad2c65f3086ddff84e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2PL/functions/logprob.r", "max_forks_repo_name": "jevanluo/BayesianIRT", "max_forks_repo_head_hexsha": "788b34e951968222493b7ad2c65f3086ddff84e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3333333333, "max_line_length": 75, "alphanum_fraction": 0.5395683453, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7346894458793928}} {"text": "\n explicit.to.implicit.2d.line = function ( p1, p2 ) {\n\n# LINE_EXP2IMP_2D converts an explicit line to implicit form in 2D.\n#% A * X + B * Y + C = 0\n dx = p1[1] - p2[1]\n dy = p1[2] - p2[2]\n slope = dy/dx\n # slope = (p1[2] - Y) / (p1[1] - X)\n # slope * (p1[1]-X) = (p1[2]-Y)\n # slope * p1[1] - slope * X - p1[2] + Y = 0\n # - slope * X + Y + slope*p1[1] - p1[2] = 0\n A = -slope\n B = 1\n C = slope * p1[1] - p1[2]\n out = as.matrix( cbind( A,B,C) )\n return( out )\n\n}\n\n\n", "meta": {"hexsha": "1d460ffd9f87ff556bfc6a388a201ff411746b4c", "size": 482, "ext": "r", "lang": "R", "max_stars_repo_path": "R/explicit.to.implicit.2d.line.r", "max_stars_repo_name": "PEDsnowcrab/aegis", "max_stars_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/explicit.to.implicit.2d.line.r", "max_issues_repo_name": "PEDsnowcrab/aegis", "max_issues_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/explicit.to.implicit.2d.line.r", "max_forks_repo_name": "PEDsnowcrab/aegis", "max_forks_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:58:58.000Z", "avg_line_length": 21.9090909091, "max_line_length": 67, "alphanum_fraction": 0.4854771784, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632302488964, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7346894450997087}} {"text": "library(polynom)\nlibrary(orthopolynom)\n\nlegendre.coeff <- function(x,y,l, xlim=range(x)) {\n\ta <- (xlim[2] - xlim[1])/2\n\tb <- xlim[1] + a\n\tx_ <- (x-b)/a\n\n\tn <- length(y) \n\tcoeffs <- NULL\t\n\n\tfor (i in 1:length(l)) { \n\t\tcoeffs <- cbind(coeffs, 2 * sum(y * predict(l[[i]], x_))/n)\n\t}\t\n\t# Return a vector of coefficients\n\t#print(coeffs)\n\tcoeffs\n}\n\nlegendre.var <- function(x,y,xlim) {\n\n\tn <- length(y)\n\tk <- ceiling(n/4)\n\tl <- legendre.polynomials(length(y), normalized=T)\n\tcoeffs <- legendre.coeff(x,y,l,xlim)\n\t#print(coeffs)\n\tv <- 4 * sum(coeffs[(n-k+1):n] * coeffs[(n-k+1):n]) \n\tprint(v)\n\tv\t\n} \n\nlegendre.R <- function(J,x,y,xlim) {\n\tn <- length(y)\n\tl <- legendre.polynomials(J, normalize=T)\n\tcoeffs <- legendre.coeff(x,y,l,xlim) \n\tv <- legendre.var(x,y,xlim)\n\n\tj <- c(1:n) \t\t\n\tR <- J*(v/n) + sum(coeffs[J+1:n] - (v * j[J+1:n])) \n\n\tR\n}\n\nlegendre.choose.R <- function(x,y,xlim) {\n\tJs <- c(1:length(y))\t\n\tprint(Js)\n\tRs <- sapply(Js, function(j){legendre.R(j,x,y,xlim)}) \t\n\tprint(Rs)\t\n\tJ.min <- which.min(Rs) \t\n}\n\nlegendre.eval <- function(x, coeffs, l, xlim=range(x)) { \n\ta <- (xlim[2] - xlim[1])/2\n\tb <- xlim[1] + a\n\tx_ <- (x-b)/a\n\n\ty <- 0 \t\n\tfor (i in 1:length(l)) {\n\t\ty <- y + coeffs[i] * predict(l[[i]], x_)\n\t}\t\n\ty\t\n}\n\nlegendre.trial <- function() {\n\tx <- seq(2,10,by=0.001)\n\ty <- sin(2*x)\n\n\tplot(x,y)\n\tl <- legendre.polynomials(3, normalized = TRUE) \n\tg <- legendre.coeff(x,y,l)\n\tlines(x, legendre.eval(x,g,l), col=\"orange\") \n\n\tg <- legendre.coeff(x,y,l)\n\tlines(x, legendre.eval(x,g,l), col=\"orange\") \n\n}\n\n\n\n\n\n", "meta": {"hexsha": "2b70feb6df0ff320a5af305a27e3c46e6c5cc194", "size": 1516, "ext": "r", "lang": "R", "max_stars_repo_path": "prosody/legendre.r", "max_stars_repo_name": "laic/rst-prosody", "max_stars_repo_head_hexsha": "72925b0828b7700e366efa667af3e052dff12114", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-21T02:49:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T09:12:26.000Z", "max_issues_repo_path": "legendre.r", "max_issues_repo_name": "laic/prosody", "max_issues_repo_head_hexsha": "f148fd4e085e3f598c8de9b213179f09f3b2a402", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "legendre.r", "max_forks_repo_name": "laic/prosody", "max_forks_repo_head_hexsha": "f148fd4e085e3f598c8de9b213179f09f3b2a402", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.487804878, "max_line_length": 61, "alphanum_fraction": 0.5679419525, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7346570033650949}} {"text": "# O(N)\nsquare_sum <- 0\nsum_of_squares <- 0\nrng = 1:100\n\nfor (i in rng) {\n square_sum <- square_sum + i\n sum_of_squares <- sum_of_squares + i*i\n}\n \nsquare_sum <- square_sum * square_sum\n\nprint(square_sum - sum_of_squares)\n\n\n# O(1)\nsm <- 100 * (100+1)/ 2\nsquared <- (100 * (100 + 1) * (2 * 100 + 1)) / 6\n\nresult <- sm * sm - squared\n \nprint(result)\n", "meta": {"hexsha": "daf26f6e3af2f38f0a56801a1cef06e281c5e51e", "size": 356, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Problem6.r", "max_stars_repo_name": "ditekunov/projectEuler-research", "max_stars_repo_head_hexsha": "e8f84388045cdc1391d1e363c7b55ff4f85be708", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-20T08:01:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-20T08:05:07.000Z", "max_issues_repo_path": "R/Problem6.r", "max_issues_repo_name": "ditekunov/ProjectEuler-asymptotics", "max_issues_repo_head_hexsha": "e8f84388045cdc1391d1e363c7b55ff4f85be708", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/Problem6.r", "max_forks_repo_name": "ditekunov/ProjectEuler-asymptotics", "max_forks_repo_head_hexsha": "e8f84388045cdc1391d1e363c7b55ff4f85be708", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.4782608696, "max_line_length": 48, "alphanum_fraction": 0.6011235955, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7346570014109622}} {"text": "\n\n### SPOTTING A VOLATILE TIME SERIES\n\n# Compute the length n of djx \nn <- length(djx)\n\n# Generate a normal sample of size n with parameters given by npars\nndata <- rnorm(n)*npars[2] + npars[1]\n\n# Generate a t-distributed sample of size n with paramaters given by tpars\ntdata <- rt(n, df = tpars[1])*tpars[3] + tpars[2]\n\n# Make ndata and tdata into xts objects\nndatax <- xts(ndata, time(djx))\ntdatax <- xts(tdata, time(djx))\n\n# Merge djx, ndatax, and tdatax and plot\nalldata <- merge(djx,ndatax, tdatax)\nplot.zoo(alldata, type = \"h\", ylim = range(alldata))\n\n\n### COMPUTING VaR and ES for NORMAL DISTRIBUTION\n\n# Make a sequence of 100 x-values going from -4*sigma to 4*sigma\nxvals <- seq(from = -4*sigma, to = 4*sigma, length.out = 100)\n\n# Compute the density of a N(mu, sigma^2) distribution at xvals\nndens <- dnorm(xvals, mean = mu, sd = sigma)\n\n# Plot ndens against xvals\nplot(xvals, ndens, type = \"l\")\n\n# Compute the 99% VaR and 99% ES of a N(mu, sigma^2) distribution\nVaR99 <- qnorm(0.99, mean = mu, sd = sigma)\nES99 <- ESnorm(0.99, mu = mu, sd = sigma)\n\n# Draw vertical lines at VaR99 and ES99 in red and green\nabline(v = VaR99, col = \"red\")\nabline(v = ES99, col = \"green\")\n\n\n### Examining risk factors for international equity portfolio\n\n# Plot the risk-factor data\nplot.zoo(riskfactors)\n\n# Calculate the log-returns, assign to returns, and plot\nreturns <- diff(log(riskfactors))[-1, ]\nplot.zoo(returns)\n\n# Use apply() to carry out the Jarque-Bera test for all 5 series\napply(returns, 2, jarque.test)\n\n# Make a Q-Q plot against normal for the 5th return series and add a reference line\nqqnorm(returns[, 5])\nqqline(returns[, 5])\n\n# Make a picture of the sample acfs for returns and their absolute values\nacf(returns)\nacf(abs(returns))\n\n# Partition plotting area into 3 pieces\npar(mfrow = c(1, 3))\n\n# Plot djx_extremes\nplot(djx_extremes, type = \"h\")\n\n# Compute the spaces between the times of the extremes\ndjx_spaces <- diff(time(djx_extremes))\n\n# Make a histogram of these spaces\nhist(as.numeric(djx_spaces))\n\n# Make a Q-Q plot of djx_spaces against exp_quantiles\nqqplot(exp_quantiles, djx_spaces)\n\n# Carry out the previous 4 steps for iid_extremes\nplot(iid_extremes, type=\"h\")\niid_spaces <- diff(time(iid_extremes))\nhist(as.numeric(iid_spaces))\nqqplot(exp_quantiles, iid_spaces)\n\n# Make a time series plot of indexes with plot.zoo and a pairwise scatterplot with pairs\nplot.zoo(indexes)\npairs(as.zoo(indexes))\n\n# Calculate the sample correlation matrix of indexes\ncor(indexes)\n\n# Plot the sample acfs and cross-correlation functions for the returns in indexes\nacf(indexes)\n\n# Plot the sample acfs and cross-correlations functions for the absolute values of indexes\nacf(abs(indexes))\n\n\n# Plot fx and fx_w\nplot.zoo(fx, type = \"h\")\nplot.zoo(fx_w, type = \"h\")\n\n# Make acf plots of fx and the absolute values of fx\nacf(fx)\nacf(abs(fx))\n\n# Apply the Ljung-Box test to the components of fx and their absolute values\napply(fx, 2, Box.test, lag = 10, type = \"Ljung\")\napply(abs(fx), 2, Box.test, lag = 10, type = \"Ljung\")\n\n# Make acf plots of fx_w and the absolute values of fx_w\nacf(fx_w)\nacf(abs(fx_w))\n\n# Apply the Ljung-Box test to the components of fx_w and their absolute values\napply(fx_w, 2, Box.test, lag = 10, type = \"Ljung\")\napply(abs(fx_w), 2, Box.test, lag = 10, type = \"Ljung\")\n", "meta": {"hexsha": "cf1e28b731dc8bf8c86df9ccca13987717e3a681", "size": 3289, "ext": "r", "lang": "R", "max_stars_repo_path": "DataCamp/Quant_Risk_Management.r", "max_stars_repo_name": "eddyzhang2018/quantwithR", "max_stars_repo_head_hexsha": "1c4ce1619ea53c2a392c5d21b660780ef7318038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DataCamp/Quant_Risk_Management.r", "max_issues_repo_name": "eddyzhang2018/quantwithR", "max_issues_repo_head_hexsha": "1c4ce1619ea53c2a392c5d21b660780ef7318038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DataCamp/Quant_Risk_Management.r", "max_forks_repo_name": "eddyzhang2018/quantwithR", "max_forks_repo_head_hexsha": "1c4ce1619ea53c2a392c5d21b660780ef7318038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1111111111, "max_line_length": 90, "alphanum_fraction": 0.7214958954, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7344835687420446}} {"text": "#' Computes Moran's I correlation index\n#'\n#' Natively built for computing Moran's I on \\code{dgCMatrix} objects, this\n#' routine allows computing the I on large sparse matrices (graphs). Part of\n#' its implementation was based on \\code{\\link[ape:Moran.I]{ape::Moran.I}},\n#' which computes the I for dense matrices.\n#'\n#' @param x Numeric vector of size \\eqn{n}.\n#' @param w Numeric matrix of size \\eqn{n\\times n}{n * n}. Weights. It can be\n#' either a object of class \\code{\\link{matrix}} or \\code{\\link[Matrix:dgCMatrix-class]{dgCMatrix}}\n#' from the \\code{\\link[Matrix]{Matrix}} package.\n#' @param normalize.w Logical scalar. When TRUE normalizes rowsums to one (or zero).\n#' @param alternative\tCharacter String. Specifies the alternative hypothesis that\n#' is tested against the null of no autocorrelation; must be of one \\code{\"two.sided\"},\n#' \\code{\"less\"}, or \\code{\"greater\"}.\n#' @export\n#' @details\n#' In the case that the vector \\code{x} is close to constant (degenerate random\n#' variable), the statistic becomes irrelevant, and furthermore, the standard error\n#' tends to be undefined (\\code{NaN}).\n#'\n#' @family statistics\n#' @family Functions for inference\n#' @return A list of class \\code{diffnet_moran} with the following elements:\n#' \\item{observed}{Numeric scalar. Observed correlation index.}\n#' \\item{expected}{Numeric scalar. Expected correlation index equal to \\eqn{-1/(N-1)}.}\n#' \\item{sd}{Numeric scalar. Standard error under the null.}\n#' \\item{p.value}{Numeric scalar. p-value of the specified \\code{alternative}.}\n#' @references\n#'\n#' Moran's I. (2015, September 3). In Wikipedia, The Free Encyclopedia.\n#' Retrieved 06:23, December 22, 2015, from \\url{https://en.wikipedia.org/w/index.php?title=Moran\\%27s_I&oldid=679297766}\n#'\n#' @examples\n#'\n#' if (require(\"ape\")) {\n#'\n#' # Generating a small random graph\n#' set.seed(123)\n#' graph <- rgraph_ba(t = 4)\n#' w <- approx_geodesic(graph)\n#' x <- rnorm(5)\n#'\n#' # Computing Moran's I\n#' moran(x, w)\n#'\n#' # Comparing with the ape's package version\n#' ape::Moran.I(x, as.matrix(w))\n#'\n#' }\n#'\n#' @author George G. Vega Yon\nmoran <- function(x, w, normalize.w=TRUE, alternative = \"two.sided\") {\n if (!inherits(w, \"matrix\") & !inherits(w, \"dgCMatrix\"))\n stop(\"-w- must be either a matrix or a dgCMatrix.\")\n\n if (any(!is.finite(x)))\n stop(\"-x- must have only numbers.\")\n\n if (inherits(w, \"matrix\"))\n w <- methods::as(w, \"dgCMatrix\")\n\n if (normalize.w)\n w <- w/(rowSums(w) + 1e-20)\n\n res <- moran_cpp(x, w)\n\n # Computing pval\n pv <- with(res, pnorm(observed, mean = expected, sd = sd))\n\n # Checking alternatives\n alternative <- match.arg(\n alternative, c(\"two.sided\", \"less\", \"greater\")\n )\n\n if (alternative == \"two.sided\")\n pv <- if (res$observed <= res$expected)\n 2 * pv\n else 2 * (1 - pv)\n if (alternative == \"greater\")\n pv <- 1 - pv\n\n # Returning\n structure(\n c(res, p.value = pv),\n class = \"diffnet_moran\"\n )\n\n}\n\n", "meta": {"hexsha": "20add65cbf2a7e5d493e8865f74c2725f5471271", "size": 2959, "ext": "r", "lang": "R", "max_stars_repo_path": "R/moran.r", "max_stars_repo_name": "USCCANA/netdiffuseR", "max_stars_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2015-12-15T02:49:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T02:48:37.000Z", "max_issues_repo_path": "R/moran.r", "max_issues_repo_name": "USCCANA/netdiffuseR", "max_issues_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2015-12-17T03:43:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T18:50:22.000Z", "max_forks_repo_path": "R/moran.r", "max_forks_repo_name": "USCCANA/netdiffuseR", "max_forks_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-12-28T21:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T19:48:08.000Z", "avg_line_length": 32.5164835165, "max_line_length": 121, "alphanum_fraction": 0.6600202771, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7342583432539495}} {"text": "#\n# Exemplo 2\n#\n\n# Série de taylor que desenvolve\n# a série até encontrar erro menor\n# que 0.01\ntaylor <- function(a, x) {\n n <- 0\n tay <- 0\n valor <- exp(x)\n while (abs(valor - tay) > 0.01) {\n termo <- exp(a) / factorial(n) * (x - a)^n\n tay <- tay + termo\n n <- n + 1\n }\n cat(\"Taylor=\", tay, \"Numero de interacoes=\", n, \"\\n\")\n}\n# executa a série em torno de a=2 para x=1\ntaylor(2, 1)", "meta": {"hexsha": "136512db6512b32e0aba8a6a834a53992b7f0d73", "size": 423, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/aula5/exemplo2.r", "max_stars_repo_name": "EduardoJM/anotacoes-matematica-aplicada", "max_stars_repo_head_hexsha": "75eaa8548ec01cc596e40dc4699fbef06001f20d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/aula5/exemplo2.r", "max_issues_repo_name": "EduardoJM/anotacoes-matematica-aplicada", "max_issues_repo_head_hexsha": "75eaa8548ec01cc596e40dc4699fbef06001f20d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/aula5/exemplo2.r", "max_forks_repo_name": "EduardoJM/anotacoes-matematica-aplicada", "max_forks_repo_head_hexsha": "75eaa8548ec01cc596e40dc4699fbef06001f20d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.15, "max_line_length": 57, "alphanum_fraction": 0.5271867612, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.734224346456717}} {"text": "#!/usr/bin/Rscript\n# Task 1\n#-------------------------------------------------------------------------------\n# Initial data\n#-------------------------------------------------------------------------------\nS0=1; r=0.05; sigma=0.2; T=2; K=0.8;\n#-------------------------------------------------------------------------------\nCall <- function(S0,r, sigma, T, K){\n d1=(log(S0/K)+T*(r+(sigma^2)/2))/(sigma*sqrt(T))\n d2=d1-sigma*sqrt(T)\n C=S0*pnorm(d1)-K*exp(-r*T)*pnorm(d2)\n return (C)\n}\n\nImpliedVola <- function(S0, r, T, K, C){\n vola=uniroot(function(sigma) Call(S0, r, sigma, T, K) - C, c(0,5))\n return (vola$root)\n}\n\nC=Call(S0,r,sigma,T,K)\nC\nImpliedVola(S0,r,T,K,C)\n#-------------------------------------------------------------------------------\nData=read.csv(\"data/option_values.csv\",header=F,sep=\";\")\nMaturities=as.numeric(Data[1,]/12); Interests=as.numeric(Data[2,])\n\nS0=2890.62; K=c(2700, 2800, 2900, 3000, 3100, 3200, 3300)\nvola=matrix(rep(0,42), 7, 6)\nfor(i in 1:7)\n for(j in 1:6)\n vola[i, j] = ImpliedVola(S0, Interests[j], Maturities[j], K[i], Data[i+2,j])\n\npersp(K,Maturities,vola,theta=60,col=\"green\")", "meta": {"hexsha": "1c362e6b2a8daafe5ef82b1c09d4b81573b45cf8", "size": 1121, "ext": "r", "lang": "R", "max_stars_repo_path": "tum/continuous-time-finance/ws8.r", "max_stars_repo_name": "nyxcalamity/classwork", "max_stars_repo_head_hexsha": "dfe47a40fe57ec5e0ccfd672a8dcaf246386de99", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-02-10T19:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T00:08:40.000Z", "max_issues_repo_path": "tum/continuous-time-finance/ws8.r", "max_issues_repo_name": "nyxcalamity/classwork", "max_issues_repo_head_hexsha": "dfe47a40fe57ec5e0ccfd672a8dcaf246386de99", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tum/continuous-time-finance/ws8.r", "max_forks_repo_name": "nyxcalamity/classwork", "max_forks_repo_head_hexsha": "dfe47a40fe57ec5e0ccfd672a8dcaf246386de99", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-05-02T11:00:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T03:55:35.000Z", "avg_line_length": 33.9696969697, "max_line_length": 80, "alphanum_fraction": 0.4469223907, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650674, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.7342004515760895}} {"text": "=begin\n= 代数パッケージ\n\n2006.09.16\n\n*Version: 0.72\n*著者: 原 信一郎\n*e-mail: sinara@blade.nagaokaut.ac.jp\n*Home Page: (())\n\n== これは、、、\n\n1変数あるいは多変数の多項式を計算するためのライブラリです。\n数学的対象を自然に Ruby で表現可能にする事を目的にしています。\nスピードはありませんが、スクリプト言語なのでアルゴリズムを見る事\nができます。\n\n* 一変数多項式\n * 加法、乗法、商/剰余等の演算\n * 因数分解\n * Galois 群\n* 多変数多項式\n * 加法、乗法等の演算\n * 因数分解\n * グレブナ基底の生成、グレブナ基底による商/剰余の演算\n* 代数系\n * 商体の生成\n * 剰余環の生成\n * 行列環の生成\n * 置換群の計算\n* 集合と写像\n\n== インストール\n\nこのパッケージを利用するにはまず、オブジェクト指向スクリプト言語 Ruby \n((())参照) が必要です。\n\n更に、アーカイブの展開後\n\n ruby install.rb\n\nとすれば、lib ディレクトリ以下を、ロード可能なディレクトリにコピーし、\nインストールが完了します。\n\n速度の点から、有理数は標準添付の rational.rb ではなく、拡張ライブラリ\n((())\nを使うことを勧めます。\n\n== 使い方・サンプル\n\ndoc ディレクトリの (()) を見てください。\nマニュアルやサンプルがあります。\n\n== 参考\n* D.コックス, J.リトル and D.オシー, \"グレブナ基底と代数多様体入門(上・下)\",\n 2000,シュプリンガー・フェアラーク東京\n* 児玉宏児, \"Polynomial\", (())\n* H.Anai, M.Noro and K.Yokoyama, \"Computation of the splitting fields and the Galois groups of polynomials\", Progres in Mathematics, 28-50, Vo.143, 1996\n\n=end\n", "meta": {"hexsha": "a9ad1e7ba46060775f1408321a96b31d541066d2", "size": 1177, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/README-ja.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "doc-ja/README-ja.rd", "max_issues_repo_name": "kunishi/algebra-ruby2", "max_issues_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc-ja/README-ja.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2950819672, "max_line_length": 152, "alphanum_fraction": 0.7128292268, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.8740772368049823, "lm_q1q2_score": 0.7339923461142354}} {"text": "#----------------------------------------------------------------\n# test function\n#----------------------------------------------------------------\n\nlibrary(inline)\n\nbody <- \"std::cout << \\\"It works\\\" << std::endl;\"\ntest <- cxxfunction(signature(), body=body, plugin=\"Rcpp\")\n\ntest()\n\n\n\n#----------------------------------------------------------------\n# Estimating pi\n#----------------------------------------------------------------\n\nmcsim_pi_r <- function(n){\n r <- 0L\n \n for (i in 1:n){\n u <- runif(1)\n v <- runif(1)\n \n if (u^2 + v^2 <= 1)\n r <- r + 1\n }\n \n return( 4*r/n )\n}\n\nmcsim_pi_r_vectorized <- function(n){\n x <- matrix(runif(n * 2), ncol=2)\n r <- sum(rowSums(x^2) <= 1)\n \n return( 4*r/n )\n}\n\nlibrary(inline)\ncxx_pi <- cxxfunction(signature(n_=\"int\"), body='\n int i, r = 0;\n int n = Rcpp::as(n_);\n double u, v;\n \n for (i=0; i(vs);\n arma::mat op = v * v.t();\n arma::mat ip = v.t()*v;\n \n return Rcpp::List::create(\n Rcpp::Named(\"outer\")=op, Rcpp::Named(\"inner\") = ip);\n'\n\nlibrary(inline)\ng <- cxxfunction(signature(vs=\"matrix\"), plugin=\"RcppArmadillo\", body=body)\n\n\n\nx <- matrix(1:30, 10)\nall.equal(f(x), g(x))\n\n\n\n#----------------------------------------------------------------\n# RcppGSL\n#----------------------------------------------------------------\n\nincludes <- '\n #include \n #include \n'\n\nbody <- '\n RcppGSL::matrix M = sM;\n int k = M.ncol();\n Rcpp::NumericVector n(k);\n \n for (int j = 0; j < k; j++) {\n RcppGSL::vector_view colview = gsl_matrix_column(M, j);\n n[j] = gsl_blas_dnrm2(colview);\n }\n \n M.free() ;\n return n;\n'\n\nlibrary(inline)\ng <- cxxfunction(signature(sM=\"matrix\"), plugin=\"RcppGSL\", body=body, inc=includes)\n\n\n", "meta": {"hexsha": "0ab484832fa472ad8d704622eb659abf41988bea", "size": 5073, "ext": "r", "lang": "R", "max_stars_repo_path": "tutorials/NIMBioS2014/presentations/rcpp_script.r", "max_stars_repo_name": "RBigData/website", "max_stars_repo_head_hexsha": "1783bbc523405ce66463c7eac98e162a3953bc59", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/NIMBioS2014/presentations/rcpp_script.r", "max_issues_repo_name": "RBigData/website", "max_issues_repo_head_hexsha": "1783bbc523405ce66463c7eac98e162a3953bc59", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/NIMBioS2014/presentations/rcpp_script.r", "max_forks_repo_name": "RBigData/website", "max_forks_repo_head_hexsha": "1783bbc523405ce66463c7eac98e162a3953bc59", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1433962264, "max_line_length": 83, "alphanum_fraction": 0.44726986, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7339898993092008}} {"text": "\n## data https://github.com/n0acar/eigenfaces\nlibrary(pixmap)\n\nlist files in a gihub directory\n\nurl <- \"https://github.com/n0acar/eigenfaces/tree/master/lfw_cropped_gray_eigenfaces\"\n\npg <- xml2::read_html(url)\nlibrary(magrittr)\nlibrary(rvest)\ntst <- pg %>% html_nodes(\"div\") %>% html_nodes(\"span\") %>% html_nodes(\"a\") %>% html_text()\ncelebs <- tst[grep(\".pgm\",tst)]\nbase <- \"https://raw.githubusercontent.com/n0acar/eigenfaces/master/lfw_cropped_gray_eigenfaces/\"\n\nfor(i in 1:length(celebs)){\n download.file(paste(base, celebs[i], sep = \"\"), destfile = celebs[i])\n}\n\nimgs <- list.files(\"./\", pattern = \".pgm\", full = TRUE)\npix <- lapply(imgs,read.pnm)\npar(mfrow = c(4,4), mar = c(0,0,0,0), oma = c(0,0,0,0))\nfor(i in 1:length(pix)){\n plot(pix[[i]])\n nm <- strsplit(strsplit(imgs[i],\"//\")[[1]][2],\"_\")[[1]]\n legend(\"bottom\", bty = \"n\", paste(nm[-length(nm)], collapse = \" \"))\n}\n\n## names\ntst <- sapply(imgs, function(x) strsplit(strsplit(x,\"//\")[[1]][2],\"_\")[[1]])\nnames <- sapply(tst, function(y) paste(y[-length(y)], collapse = \" \")); names(names) <- NULL\n## collapse the grey matrix\nfaces <- lapply(pix, function(x) c(x@grey))\n## each column is a face\nfaces <- do.call('cbind',faces)\ncolnames(faces) <- names\n\n## center around mean\nmean <- apply(faces, 1, mean)\nmean_face <- pixmapGrey(mean, 64, 64, bbox = c(0, 0, 64, 64))\nplot(mean_face)\ncentered <- apply(faces, 2, function(x) x - mean)\n## centered imags\npar(mfrow = c(4,4), mar = c(0,0,0,0), oma = c(0,0,0,0))\nfor(i in 1:length(pix)){\n plot(pixmapGrey(centered[,i], 64, 64, bbox = c(0, 0, 64, 64)))\n legend(\"bottom\", bty = \"n\", paste(names[i], \"centered\", sep = \" \"))\n}\n\n \npca <- prcomp(centered)\nlibrary(ggbiplot)\nggbiplot(pca, alpha = 0.1) +\n theme(legend.direction = 'horizontal', legend.position = 'top')\n\n## eigen faces\npcs <- pca$x\neigenfaces <- apply(pcs,2, function(x) pixmapGrey(x, 64, 64, bbox = c(0, 0, 64, 64)))\npar(mfrow = c(4,4), mar = c(0,0,0,0), oma = c(0,0,0,0))\nfor(i in 1:length(eigenfaces)){\n plot(eigenfaces[[i]])\n legend(\"bottom\", bty = \"n\", paste(\"PC\", i, sep = \" \"))\n}\n\n## reconstruction\n## each face is a weighted (loadings) combintation of the eigen faces (PCs) above\n## but how many PCs (eigenfaces) do we keep\nplot(pca)\npca$rotation\n## 2 PCs\nn_pc <- 2\n\nrecon <- pixm <- list()\nfor (i in 1:length(names)){\n recon[[i]] <- rowSums(pca$x[,1:n_pc]%*%pca$rotation[i,1:n_pc])\n pixm[[i]] <- pixmapGrey(recon[[i]], 64, 64, bbox = c(0, 0, 64, 64))\n}\n\n## 2PC to reconstruct centered imags\npar(mfrow = c(4,4), mar = c(0,0,0,0), oma = c(0,0,0,0))\nfor(i in 1:length(pixm)){\n plot(pixm[[i]])\n legend(\"bottom\", bty = \"n\", paste(names[i], \"2 PC\", sep = \" \"))\n}\n\n### Hmm OK, what about 5\n## 5 PCs\nn_pc <- 5\n\nrecon <- pixm <- list()\nfor (i in 1:length(names)){\n recon[[i]] <- rowSums(pca$x[,1:n_pc]%*%pca$rotation[i,1:n_pc])\n pixm[[i]] <- pixmapGrey(recon[[i]], 64, 64, bbox = c(0, 0, 64, 64))\n}\n\n## 2PC to reconstruct centered imags\npar(mfrow = c(4,4), mar = c(0,0,0,0), oma = c(0,0,0,0))\nfor(i in 1:length(pixm)){\n plot(pixm[[i]])\n legend(\"bottom\", bty = \"n\", paste(names[i], \"5 PC\", sep = \" \"))\n}\n\n### Hmm OK, what about 10\n## 10 PCs\nn_pc <- 10\n\nrecon <- pixm <- list()\nfor (i in 1:length(names)){\n recon[[i]] <- rowSums(pca$x[,1:n_pc]%*%pca$rotation[i,1:n_pc])\n pixm[[i]] <- pixmapGrey(recon[[i]], 64, 64, bbox = c(0, 0, 64, 64))\n}\n\n## 10PC to reconstruct centered images\npar(mfrow = c(4,4), mar = c(0,0,0,0), oma = c(0,0,0,0))\nfor(i in 1:length(pixm)){\n plot(pixm[[i]])\n legend(\"bottom\", bty = \"n\", paste(names[i], \"10 PC\", sep = \" \"))\n}\n## remember this is the centered image, let's add the \"mean face\" to reconstruct the original\npar(mfrow = c(4,4), mar = c(0,0,0,0), oma = c(0,0,0,0))\nfor(i in 1:length(recon)){\n plot(pixmapGrey(recon[[i]] + mean, 64, 64, bbox = c(0, 0, 64, 64)))\n legend(\"bottom\", bty = \"n\", paste(names[i], \"10 PC + mean\", sep = \" \"))\n}\n\n\n## So arguabke we reduced 16 dim to 10... Not a huge achievement, but what about if we have 1000 images\nzip <- \"http://conradsanderson.id.au/lfwcrop/lfwcrop_grey.zip\"\ntemp <- tempfile(fileext = \".zip\")\ndownload.file(zip,destfile = temp)\ntst <- unzip(temp)\nunlink(temp)\nall_faces <- list.files(\"lfwcrop_grey/faces\",pattern = \".pgm\", full = TRUE)\nset.seed(6666)\nchoose <- sample(1:length(all_faces), 1000, replace = FALSE)\n\nface_set <- lapply(choose, function(x) read.pnm(all_faces[x]))\n\n## names\ncol <- sapply(all_faces[choose], function(x) strsplit(strsplit(x,\"faces/\")[[1]][2],\"_\")[[1]])\nnames <- sapply(col, function(y) paste(y[-length(y)], collapse = \" \")); names(names) <- NULL\nnames(face_set) <- names\nface_data <- lapply(face_set, function(x) c(x@grey))\n## each column is a face\nface_data <- do.call('cbind',face_data)\ncolnames(face_data) <- names(face_set)\n## center around mean\nmean <- apply(face_data, 1, mean)\nmean_face <- pixmapGrey(mean, 64, 64, bbox = c(0, 0, 64, 64))\nplot(mean_face)\n\ncentered <- apply(face_data, 2, function(x) x - mean)\npca <- prcomp(centered)\npcs <- pca$x\neigenfaces <- apply(pcs,2, function(x) pixmapGrey(x, 64, 64, bbox = c(0, 0, 64, 64)))\nplot(eigenfaces[[1]])\nlegend(\"bottom\", bty = \"n\", \"PC 1\")\n\nn_pc <- 250\nrecon <- rowSums(pca$x[,1:n_pc]%*%pca$rotation[1,1:n_pc])\n## add the \"mean face\" to reconstruct the original\npar(mfrow = c(1,2), mar = c(0,0,0,0), oma = c(0,0,0,0))\n## original\nplot(face_set[[1]])\n", "meta": {"hexsha": "a8367877155d836d26d9a87e5c17e4249467ac42", "size": 5370, "ext": "r", "lang": "R", "max_stars_repo_path": "swots/eigenfaces.r", "max_stars_repo_name": "statbiscuit/swots", "max_stars_repo_head_hexsha": "005da6fdb980e6cbb40f407e059623256f9c0626", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-22T02:58:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-22T03:01:46.000Z", "max_issues_repo_path": "swots/eigenfaces.r", "max_issues_repo_name": "cmjt/statbiscuits", "max_issues_repo_head_hexsha": "005da6fdb980e6cbb40f407e059623256f9c0626", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swots/eigenfaces.r", "max_forks_repo_name": "cmjt/statbiscuits", "max_forks_repo_head_hexsha": "005da6fdb980e6cbb40f407e059623256f9c0626", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5454545455, "max_line_length": 103, "alphanum_fraction": 0.6173184358, "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936435, "lm_q2_score": 0.8976952975813453, "lm_q1q2_score": 0.7339327627015653}} {"text": "y1bar=1.175\r\ny2bar=1.293\r\ny3bar=1.328\r\ny4bar=1.415\r\ny5bar=1.500\r\n\r\nalpha=0.05\r\nq.alpha=4.158\r\nMSError=0.0153\r\nLSD=q.alpha*sqrt((MSError)/6)\r\nprint(LSD)\r\n\r\n# the 95% confidence interval for y3bar-y1bar\r\nleft_i=(y3bar-y1bar)-LSD\r\nright_i=(y3bar-y1bar)+LSD\r\nprint(\"Confidence interval is\")\r\nprint(left_i)\r\nprint(right_i)", "meta": {"hexsha": "90890086596d92a4c173e44a986511be5ef9d8cb", "size": 318, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH9/EX9.11/Ex9_11.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH9/EX9.11/Ex9_11.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH9/EX9.11/Ex9_11.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 17.6666666667, "max_line_length": 47, "alphanum_fraction": 0.713836478, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7339283744485737}} {"text": "#' Compute the time-shift parameter tau.\n#'\n#' @param t Sampling times.\n#' @param omega Angular frequency.\n#'\n#' @return Time-shift parameter tau.\n#'\n#' @examples\n#' tau(1:10, 2*pi)\n#'\n#' @export\ntau <- function(t, omega) {\n # two.omega[j] = 2 * omega[j]\n two.omega <- 2 * omega\n # two.omega.t[j,i] = 2 * omega[j] * t[i]\n two.omega.t <- two.omega %o% t\n\n # sin.sum[j] = Sum from i=1..N of sin(two.omega.t[j,i])\n sin.sum = rowSums(sin(two.omega.t))\n # cos.sum[j] = Sum from i=1..N of cos(two.omega.t[j,i])\n cos.sum = rowSums(cos(two.omega.t))\n\n # Consistent with the Fortran code\n # two.omega.tau[j] = atan(sin.sum[j] / cos.sum[j])\n two.omega.tau <- atan(sin.sum / cos.sum)\n# # Consistent with the paper.\n# # two.omega.tau[j] = atan2(sin.sum[j], cos.sum[j])\n# two.omega.tau <- atan2(sin.sum, cos.sum)\n\n\n # Consistent with the Fortran code\n # two.omega.tau[j] / (2*pi)\n two.omega.tau / (2*pi)\n# # Consistent with the paper.\n# # two.omega.tau[j] / (2*omega[j])\n# two.omega.tau / two.omega\n\n}\n", "meta": {"hexsha": "6a4fd7e1edf1cd64bd4d3a2ee78dff65e56779f8", "size": 1049, "ext": "r", "lang": "R", "max_stars_repo_path": "R/tau.r", "max_stars_repo_name": "dwysocki/cross-spectral-analysis", "max_stars_repo_head_hexsha": "854d0fabee3e5c32dba7152bae18e6ae0a20e646", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-06T12:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-06T12:41:16.000Z", "max_issues_repo_path": "R/tau.r", "max_issues_repo_name": "dwysocki/cross-spectral-analysis", "max_issues_repo_head_hexsha": "854d0fabee3e5c32dba7152bae18e6ae0a20e646", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-12T03:17:50.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-12T03:17:50.000Z", "max_forks_repo_path": "R/tau.r", "max_forks_repo_name": "dwysocki/cross-spectral-analysis", "max_forks_repo_head_hexsha": "854d0fabee3e5c32dba7152bae18e6ae0a20e646", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8974358974, "max_line_length": 59, "alphanum_fraction": 0.5824594852, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7338410390068628}} {"text": "# ......................................................................................\n# ..........Exercise 6 - Selected distributions of a continuous random variable.........\n# ......................................................................................\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# Overview of distributions and their functions ####\n# \n# * Introduction: Probability Density, Distribution Function and Quantile Function ####\n# \n# ** Probability density ####\n# \n# - starts with the letter **d**: p=d...(x,...)\n# \n# ** Distribution function ####\n# \n# - starts with the letter **p**: $p = P(X < x)$:p=p...(x,...)\n# \n# ** Quantile function ####\n# \n# - starts with the letter **q**: find x for the given p: $p = F(x) \\rightarrow x =\n# F^{-1}(p)$: x=q...(p,...)\n# \n\n\n# * Uniform distribution: $X \\sim U(a, b)$ ####\n# \n# - the random variable takes on only values greater than a and less than b\n# \n# - all values have the same occurrence density ->the probability density is constant\n# between a and b, elsewhere zero\n# \n\n\n# Probability density f(x)\na = 2 # from where\nb = 4 # up to\nx = 3 \ndunif(x, a, b)\n\n# we plot the probability density\nx = seq(from = 0, to = 6, by = 0.01)\nf_x = dunif(x, a, b)\nplot(x, f_x, cex = 0.1) # cex is the size of the markers\ngrid()\n\n# Distribution function F(x)=P(Xexponential distribution\nx = 5\ndweibull(x,shape=beta, scale=theta)\n\n# we plot the probability density\nx = seq(from = 0, to = 6, by = 0.01)\nf_x = dweibull(x,shape=beta, scale=theta)\nplot(x, f_x, type='l')\ngrid()\n\n# Distribution function F(x)=P(Xexponential distribution\nx = 5\npweibull(x,shape=beta, scale=theta)\n\n# we draw the Distribution function\nx = seq(from = 0, to = 6, by = 0.01)\nF_x = pweibull(x,shape=beta, scale=theta)\nplot(x, F_x, type = 'l')\ngrid()\n\n# quantile function F ^(- 1)(p)=x: P(Xexponential distribution\np = 0.5\nqweibull(p,shape=beta, scale=theta)\n\n# plot - quantile function F ^(- 1)(p)=x\np = seq(from=0, to=1, by=0.01) \nx = qweibull(p,shape=beta, scale=theta)\nplot(p, x, type = 'l')\ngrid()\n\n# * Normal distribution: $X \\sim N(\\mu,\\sigma^2)$ ####\n# \n# - distribution modeling eg. measurement errors, sum/average behavior of many other\n# random variables\n# \n# - viz. Central limit theorem\n# \n# - $\\mu$ is the average distribution value: $E(X)=\\mu$\n# \n# - $\\sigma$ is the directly standard deviation of the distribution: $D(X)=\\sigma^2$\n# \n# - with parameters $\\mu=0,\\sigma=1$ is called normalized Normal distribution\n# \n\n\n# Probability density f(x)\nmu = 2\nsigma = 3\nx = 4\ndnorm(x, mean=mu, sd=sigma)\n\n# we plot the probability density\nx = seq(from = -5, to = 10, by = 0.01)\nf_x = dnorm(x, mean=mu, sd=sigma)\nplot(x, f_x, type='l')\ngrid()\n\n# Distribution function F(x)=P(X35000)=1-F(35000)\n1 - pexp(35000, lambda)\n\n# ** c) ####\n# \n# time until 95% of the components fail.\n# \n\n\n# c) P(XF(t)=0.95 ->t… 95% quantile\nqexp(0.95, lambda)\n\n# * Example 3. ####\n# \n# The production facility fails on average once every 2000 hours. The quantity Y\n# representing the time before the fault has an exponential distribution. Determine the\n# time T0 so that the probability that the device will run longer than T0 is 0.99.\n# \n\n\n# X... fault waiting time(h)\n# X~Exp(lambda), where E(X)=1/lambda\nlambda = 1/2000\n\n# P(X>t)=0.99 ->1-F(t)=0.99 ->F(t)=0.01 ->t… 1% quant.\nqexp(0.01, lambda)\n\n# * Example 4. ####\n# \n# The measurement results are corrupted only with a normally distributed error with zero\n# mean and a standard deviation of 3 mm. What is the probability that there will be an\n# error in the interval(0 mm; 2.4 mm) at least once in 3 measurements?\n# \n\n\n# Y measurement error size(mm)\n# Y~N(mu=0, sigma=3)\n\nmu = 0\nsigma = 3\n\n# pp… true that the measurement error will be in int. 0.0-2.4mm\npp = pnorm(2.4,mean=mu,sd=sigma) - pnorm(0,mean=mu,sd=sigma)\npp\n\n# X… number of measurement errors in int. 0 mm -2.4 mm in 3 measures.\n# X~Bi(n=3, p=pp)\nn = 3\np = pp\n\n# P(X>=1)=1-P(X=0)\n1 - dbinom(0, n, p)\n\n# * Example 5. ####\n# \n# An average of 25 users per hour log on to a large computer network. Determine the\n# probability that:\n# \n# ** a) ####\n# \n# no one logs in during 14:30 - 14:36,\n# \n\n\n# X… number of users logged in in 6 minutes\n# X~Po(lt=2.5)\n\nlambda = 25/60\nt = 6\nlt = lambda*t\n\n# P(X=0)\ndpois(0, lt)\n\n# ** b) ####\n# \n# 2-3 minutes will elapse before the next login.\n# \n\n\n# Y… time until next login\n# Y~Exp(lambda=25/60), where E(X)=1/lambda\nlambda = 25/60 \n\n# P(2t)=0.90 ->1-F(t)=0.90 ->F(t)=0.10 ->t… 10% kv.\n\nqexp(0.10, lambda)*60\n\n# * Example 6. ####\n# \n# The random variable X has a normal distribution N(µ; σ). Specify:\n# \n# ** a) ####\n# \n# P(µ - 2σ0.99.\n# \n\n\n# normal distribution is symmetric\n# P(µ - kσµ + kσ))=\n# 1 - 2 * P(X>µ + kσ)=0.99 ->P(X>µ + kσ)=0.005\n# ->P(X<µ + kσ)=0.995\n\n# x=µ + kσ\nx = qnorm(0.995, mean=mu, sd=sigma)\n(x - mu)/sigma\n\nfor(k in 1:5){\n p = pnorm(mu + k*sigma, mean=mu, sd=sigma) - \n pnorm(mu - k*sigma, mean=mu, sd=sigma)\n print(paste0(k,\":\",p))\n}\n\n# * Example 7. ####\n# \n# An accompanying film about the life of the author of the exhibited works is screened\n# on a tour of the exhibition. His screening begins every 20 minutes. Determine the\n# probability that if you come to the screening room at random time (and you have no\n# clue about screening shedule),\n# \n\n\n# Y… time until the start of the next projection\n# Y~Ro(a=0, b=20)\n\na = 0\nb = 20\n\n# ** a) ####\n# \n# you won't have to wait more than 5 minutes for the movie to start,\n# \n\n\n# P(X<5)\npunif(5, a, b)\n\n# ** b) ####\n# \n# you will wait between 5 and 10 minutes,\n# \n\n\n# P(5700)=1-F(700)\nP.J = 1-pnorm(700,mean=mu_J,sd=sigma_J)\nP.J\n\n# P(A)=P(SA>700)=1-F(700)\nP.A = 1-pnorm(700,mean=mu_A, sd=sigma_A)\nP.A\n\n# KJ… Jakub qualifies for races,\n# P(KJ)=1-(1-P(J))(1-P(J))\nP.KJ=1-(1-P.J)*(1-P.J)\nP.KJ\n\n# KA… Aleš qualifies for races,\n# P(KA)=1-(1-P(A))(1-P(A))\nP.KA=1-(1-P.A)*(1-P.A)\nP.KA\n\n# ** a) ####\n# \n# How likely are they both to qualify for the race?\n# \n\n\n# ada)\nP.KJ*P.KA\n\n# ** b) ####\n# \n# With what probability does Aleš qualify, but Jakub does not?\n# \n\n\n# adb)\n(1-P.KJ)*P.KA\n\n\n\n", "meta": {"hexsha": "3ceae5df83390df244143e90cc09a7858edff166", "size": 11397, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 6/T8_selected_CRV.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise 6/T8_selected_CRV.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise 6/T8_selected_CRV.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 21.6261859583, "max_line_length": 88, "alphanum_fraction": 0.6047205405, "num_tokens": 4030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7338256198379081}} {"text": "plot(function(x){\n return(plnorm(x,meanlog=(log(0.1)-0.5^2/2),sdlog=0.5))\n},xlim=c(0,0.6))\n0.1 = exp(mulog+sdlog^2/2)\nlog(0.1) = mulog + sdlog^2/2\nmulog = log(0.1) - sdlog^2/2\nlog(0.1)-0.5^2/2\n\nplot(function(x){\n return(plnorm(x,meanlog=(log(0.1)-0.6^2/2),sdlog=0.6))\n},xlim=c(0,0.6),add=TRUE)\n\nplot(function(x){\n return(pnorm(x,mean=0.1,sd=0.025))\n},xlim=c(0,0.6),add=TRUE)\n\nplot(function(x){\n return(plnorm(x,meanlog=(log(0.1)-0.25^2/2),sdlog=0.25))\n},xlim=c(0,0.6),add=TRUE)\n\nplot(function(x){\n return(plnorm(x,meanlog=(log(0.12)-0.5^2/2),sdlog=0.5))\n},xlim=c(0,0.6),add=TRUE)\n\nplot(function(x){\n return(plnorm(x,meanlog=(log(0.12)-0.6^2/2),sdlog=0.6))\n},xlim=c(0,0.6),add=TRUE)\n\nmu.1 = 0.12\nmu.2 = exp(2*(log(0.12)-0.5^2/2)+0.5^2)*(exp(0.5^2)-1) + mu.1^2\nmu.1^2/(mu.2)\nnlminb(1, function(x) {return((mu.1^2*gamma(1+2/x)-mu.2*gamma(1+1/x)^2)^2)})\nplot(function(x) {return(((mu.1^2*gamma(1+2/x)-mu.2*gamma(1+1/x)^2)^2))},\n xlim=c(1,4))\nm = 1.957465\neta = 0.12/gamma(1+1/m)\nplot(function(x){\n return(pweibull(x,shape=m,scale=eta))\n},xlim=c(0,0.6),add=TRUE)\n\nmu.1 = 0.12\nmu.2 = exp(2*(log(0.12)-0.6^2/2)+0.6^2)*(exp(0.6^2)-1) + mu.1^2\nmu.1^2/(mu.2)\nnlminb(1, function(x) {return((mu.1^2*gamma(1+2/x)-mu.2*gamma(1+1/x)^2)^2)})\nplot(function(x) {return(((mu.1^2*gamma(1+2/x)-mu.2*gamma(1+1/x)^2)^2))},\n xlim=c(1,4))\nm = 1.551332\neta = 0.12/gamma(1+1/m)\nplot(function(x){\n return(pweibull(x,shape=m,scale=eta))\n},xlim=c(0,0.6),add=TRUE)\n", "meta": {"hexsha": "fd6186337bcfd99d9b18766549ba2e2c64293cab", "size": 1450, "ext": "r", "lang": "R", "max_stars_repo_path": "distribution.r", "max_stars_repo_name": "waterloodark/DeCost-Holm-2016-", "max_stars_repo_head_hexsha": "b3e9c4bc60b47ac81c4d2a1ca19ba4f68e7e612a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution.r", "max_issues_repo_name": "waterloodark/DeCost-Holm-2016-", "max_issues_repo_head_hexsha": "b3e9c4bc60b47ac81c4d2a1ca19ba4f68e7e612a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution.r", "max_forks_repo_name": "waterloodark/DeCost-Holm-2016-", "max_forks_repo_head_hexsha": "b3e9c4bc60b47ac81c4d2a1ca19ba4f68e7e612a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8846153846, "max_line_length": 76, "alphanum_fraction": 0.6006896552, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.7338256099783173}} {"text": "library(MASS)\ngetPriorProbabilities <- function (dset, column) {\n dsetLength <- dim(dset)[1]\n return (table(dset[, column]) / dsetLength)\n}\n\ngetCovMatrix <- function(dset, expectation) {\n featureTypesCount <- dim(dset)[2]\n dsetLength <- dim(dset)[1]\n cov <- matrix(0, nrow = featureTypesCount - 1, ncol = featureTypesCount - 1)\n \n for (i in 1:dsetLength) {\n currentFeature <- as.matrix(dset[i, 1:featureTypesCount - 1], nrow = 1)\n tmp <- t(currentFeature - expectation) %*% (currentFeature - expectation)\n cov <- cov + tmp\n }\n cov <- cov / (dsetLength - 1)\n \n return(cov)\n}\n\ngetLikelihood <- function(point, expectation, covMatrix) {\n pointMinusMean <- t(as.matrix(point - expectation))\n \n covMatrixInverse <- solve(covMatrix)\n nom <- exp(-(pointMinusMean %*% covMatrixInverse %*% t(pointMinusMean)) / 2)\n denom <- sqrt((2 * pi) ^ nrow(covMatrix) * det(covMatrix))\n \n return(nom / denom)\n}\n\ngetPlugInProbability <- function(dset, classesColumn, className, point, lambda) {\n featuresCount <- length(point)\n croppedDset <- dset[which(dset[, classesColumn] == className), ]\n dsetLength <- dim(dset)[1]\n\n prior <- getPriorProbabilities(dset, classesColumn)[className]\n \n expectations <- array(dim = featuresCount)\n for (i in 1:featuresCount) {\n expectations[i] <- mean(croppedDset[, i])\n }\n \n \n # lambda = rep(1, featuresCount)\n covMatrix <- getCovMatrix(croppedDset, matrix(expectations, nrow=1))\n likelihood <- getLikelihood(point, expectations, covMatrix)\n \n probability <- lambda * prior * likelihood;\n \n return (probability)\n}\n\nplugInClassifier <- function(point, dset) {\n classes <- unique(dset[, 3])\n classesCount <- length(classes)\n scores <- array(dim = classesCount)\n for (i in 1:classesCount) {\n scores[i] <- getPlugInProbability(dset, 'class', classes[i], point, lambdas[i])\n }\n return(classes[which.max(scores)])\n}\n\n# mu1 <- c(0, 0)\n# mu2 <- c(4, 4)\n# sig1 <- matrix(c(2, 0.9, 0.9, 2), 2, 2)\n# sig2 <- matrix(c(0.5, 0, 0, 2), 2, 2)\n# dset1 <- mvrnorm(250, mu1, sig1)\n# dset2 <- mvrnorm(250, mu2, sig2)\n# dset <- rbind(cbind(dset1, 1),cbind(dset2, 2))\n\ndset = data.frame(x = double(), y = double(), class = character())\n\ndset <- rbind(dset, data.frame(x = 0, y = 2, class = 1))\ndset <- rbind(dset, data.frame(x = 2, y = 0, class = 1))\ndset <- rbind(dset, data.frame(x = 2.5, y = 2.5, class = 1))\ndset <- rbind(dset, data.frame(x = 2.8, y = 2.8, class = 1))\n\ndset <- rbind(dset, data.frame(x = 2, y = 4.5, class = 2))\ndset <- rbind(dset, data.frame(x = 4.5, y = 2, class = 2))\ndset <- rbind(dset, data.frame(x = 6, y = 6, class = 2))\ndset <- rbind(dset, data.frame(x = 6, y = 5, class = 2))\ndset <- rbind(dset, data.frame(x = 5, y = 6, class = 2))\ndset <- rbind(dset, data.frame(x = 3, y = 5.5, class = 2))\ndset <- rbind(dset, data.frame(x = 5.5, y = 3, class = 2))\n\nplot(dset[ ,1], dset[ ,2], pch=21, bg=c(\"green\",\"blue\")[dset[ ,3]])\n\n# print(plugInClassifier(c(0, 0), dset))\n# # print(getPlugInProbability(dset, 3, 1, c(0, 0), 1))\n\n## generating map\ncolors <- c(\"1\" = \"green\", \"2\" = \"blue\")\nxs <- seq(from = -5, to = 7, by = 0.2)\nys <- seq(from = -5, to = 7, by = 0.2)\n## lambdas <- runif(2, min=1, max=100)\nlambdas = c(1, 1)\nprint(lambdas)\n\nall <- length(xs) * length(ys)\nprogress = 1\nfor (i in xs) {\n for (j in ys) {\n cat(\"\\rProcessing point\", progress, \"of\", all)\n progress <- progress + 1\n result <- plugInClassifier(c(i, j), dset)\n points(i, j, col = colors[result], pch = 21)\n }\n}\ncat(\"\\rDone. \\n\")\n", "meta": {"hexsha": "f5b8b462152639c48d274f4f948daf05f4fd8db0", "size": 3505, "ext": "r", "lang": "R", "max_stars_repo_path": "7 - Plug-in algorithm/plug-in.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "7 - Plug-in algorithm/plug-in.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "7 - Plug-in algorithm/plug-in.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5765765766, "max_line_length": 83, "alphanum_fraction": 0.6182596291, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7332639376950052}} {"text": "#Example : 1 Chapter : 2.1 Pageno : 37\n#Multiplication by rows and cols dotproduct.\nmultiply<-function(A,x){\n b<-c()\n for(i in 1:3){\n b<-c(b,sum(A[i,]*x[,1]))\n }\n b<-matrix(b,ncol=1)\n print(paste(\"Multiplying matrices by dotproduct of rows and cols\"))\n print(A)\n print(\"*\")\n print(x)\n print(\"=\")\n print(b)\n}\n\n\nI<-matrix(c(1,0,0,0,1,0,0,0,1),ncol=3,byrow=T)\nx<-matrix(c(4,5,6),ncol=1)\nA=matrix(c(1,1,1,0,0,0,0,0,0),ncol=3)\nmultiply(A,x)\nA<-matrix(c(1,0,0,0,1,0,0,0,1),nrow=3,ncol=3,byrow=T)\nmultiply(A,x)\n\n\n\n\n", "meta": {"hexsha": "9afb84ce791a94db7569d979e2a7cbbfcf971669", "size": 524, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.1.1/Ex2.1_1.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.1.1/Ex2.1_1.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.1.1/Ex2.1_1.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 18.7142857143, "max_line_length": 69, "alphanum_fraction": 0.5992366412, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7332001804614748}} {"text": "euclidean <- function(a, b) {\n return (sqrt(sum((a - b) ^ 2)))\n}\n\nfast_cvloo_knn <- function() {\n maxK <- length(iris[,1]) - 1\n classes = unique(iris$Species)\n \n ans <- rep(x = 0, times = maxK)\n for (i in 1:length(iris[,1])) {\n # for (i in 1:10) {\n cat(\"\\r\", \"Processing sample \", i, \" of \", length(iris[,1]))\n dataset <- iris[-i,]\n # print(dataset)\n distance <- array(dim=c(length(dataset[,1])))\n for (j in 1:(length(dataset[,1]))) {\n distance[j] <- euclidean(dataset[j, 1:4], iris[i, 1:4])\n }\n sortedDataset <- irisSubset[order(distance),]\n \n classesCount <- rep(x = 0, times = length(classes))\n names(classesCount) = classes\n for (j in 1:maxK) {\n classesCount[sortedDataset$Species[j]] <- classesCount[sortedDataset$Species[j]] + 1\n \n classForCurrentK = names(which.max(classesCount))[1]\n if (classForCurrentK == iris$Species[i]) {\n ans[j] = ans[j] + 1\n }\n }\n \n }\n cat(\"\\n\")\n for (i in 1:length(ans)) {\n \n ans[i] = ans[i] / length(iris[,1] - 1)\n }\n \n return (ans)\n}\n\n\nstats <- fast_cvloo_knn()\n\nprint(stats)\nprint(paste(\"The best K: \", which.max(stats)))\n\npar(mfrow=c(1,1))\nplot(1:(length(iris[,1]) - 1), stats, type=\"l\", xlab=\"k\", ylab=\"Accuracy\")", "meta": {"hexsha": "f4be57b54f7ed2b9dfe9b2d2f939f6fdaca097a3", "size": 1248, "ext": "r", "lang": "R", "max_stars_repo_path": "-1 - Fast CV LOO implementation, the best K search for 1-4 iris features/-1.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "-1 - Fast CV LOO implementation, the best K search for 1-4 iris features/-1.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "-1 - Fast CV LOO implementation, the best K search for 1-4 iris features/-1.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4693877551, "max_line_length": 90, "alphanum_fraction": 0.5641025641, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7331187886007124}} {"text": "## Author: Sergio García Prado\n\nrm(list = ls())\n\n\n## a)\n####\n\n## Asymptotic distibution of (lambda1.hat, lambda2.hat) as parameters lambda1 of Pois(lambda1) and\n## lambda2 of Pois(lambda2) independent of each other.\n##\n## (lambda1.hat, lambda2.hat) ~ N_2( (lambda1, lambda2) , [lambda1 / n, 0;\n## 0, lambda2 / n] )\n##\n\n\n## b)\n####\nn1 <- 50\ny1 <- 75\n\nn2 <- 50\ny2 <- 100\n\nn <- c(n1, n2)\ny <- c(y1, y2)\n\nalpha <- 0.05\n\nLogLikelihood <- function(lambda, y, n) {\n sum(y * log(lambda) - n * lambda)\n}\n\nNegativeLogLikelihood <- function(...) {\n - LogLikelihood(...)\n}\n\nopt <- optim(runif(2), NegativeLogLikelihood, y = y, n = n, hessian = TRUE)\n\n(lambda.hat <- opt$par)\n#\n\n(lambda.hat.var <- solve(opt$hessian))\n#\n#\n\ng.transform <- c(-2, 1)\n\n(g.hat <- (g.transform %*% lambda.hat)[1])\n#\n\n(g.hat.var <- (g.transform %*% lambda.hat.var %*% g.transform)[1])\n#\n\n## Wald's Confidence Interval at (1 - alpha)% level.\ng.hat + c(-1, 1) * qnorm(1 - alpha / 2) * sqrt(g.hat.var)\n#\n\n\n## b)\n####\ng.zero <- 0\n\n(W <- (g.hat - g.zero) ^ 2 / g.hat.var)\n#\n\n(W.pvalue <- 1 - pchisq(W, df = 1))\n#\n\n## b)\n####\n\nLogLikelihoodHZero <- function(ll, ...) {\n LogLikelihood(c(2 * ll, ll), ...)\n}\n\nNegativeLogLikelihoodHZero <- function(...) {\n - LogLikelihoodHZero(...)\n}\n\nopt.hzero <- optim(runif(1), NegativeLogLikelihoodHZero, y = y, n = n,\n lower = 10e-3, upper = 10e3, method = \"Brent\")\n\n(LRT <- 2 * (LogLikelihood(lambda.hat, y, n) - LogLikelihoodHZero(opt.hzero$par, y, n)))\n#\n\n(LRT.pvalue <- 1 - pchisq(LRT, df = 1))\n#\n", "meta": {"hexsha": "b1f789043485a313197d103a39c1588a822b947f", "size": 1572, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/likelihood/exercise-04.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/likelihood/exercise-04.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/likelihood/exercise-04.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6629213483, "max_line_length": 98, "alphanum_fraction": 0.5553435115, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.733118788177136}} {"text": "# Chapter 1 Conditional Flow\r\n# Comparison of logicals\r\nTRUE == FALSE\r\n# FALSE\r\n\r\n# Comparison of numerics\r\n-6*14 != 17-101\r\n# FALSE\r\n\r\n# Comparison of character strings\r\n\"useR\" == \"user\"\r\n# FALSE\r\n\r\n# Compare a logical with a numeric\r\nTRUE == 1\r\n# TRUE\r\n\r\n# Comparison of numerics\r\n-6*5+2 >= -10+1\r\n# FALSE\r\n\r\n# Comparison of character strings\r\n\"raining\" <= \"raining dogs\"\r\n# TRUE\r\n\r\n# Comparison of logicals\r\nTRUE > FALSE\r\n# TRUE\r\n\r\n# The linkedin and facebook vectors have already been created for you\r\nlinkedin <- c(16, 9, 13, 5, 2, 17, 14)\r\nfacebook <- c(17, 7, 5, 16, 8, 13, 14)\r\n\r\n# Popular days\r\nlinkedin > 15\r\n# TRUE FALSE FALSE FALSE FALSE TRUE FALSE\r\n\r\n# Quiet days\r\nlinkedin <= 5\r\n# FALSE FALSE FALSE TRUE TRUE FALSE FALSE\r\n\r\n# LinkedIn more popular than Facebook\r\nlinkedin > facebook\r\n# FALSE TRUE TRUE FALSE FALSE TRUE FALSE\r\n\r\n# The social data has been created for you\r\nlinkedin <- c(16, 9, 13, 5, 2, 17, 14)\r\nfacebook <- c(17, 7, 5, 16, 8, 13, 14)\r\nviews <- matrix(c(linkedin, facebook), nrow = 2, byrow = TRUE)\r\n\r\n# When does views equal 13?\r\nviews == 13\r\n# [,1] [,2] [,3] [,4] [,5] [,6] [,7]\r\n# [1,] FALSE FALSE TRUE FALSE FALSE FALSE FALSE\r\n# [2,] FALSE FALSE FALSE FALSE FALSE TRUE FALSE\r\n\r\n# When is views less than or equal to 14?\r\nviews <= 14\r\n# [,1] [,2] [,3] [,4] [,5] [,6] [,7]\r\n# [1,] FALSE TRUE TRUE TRUE TRUE FALSE TRUE\r\n# [2,] FALSE TRUE TRUE FALSE TRUE TRUE TRUE\r\n\r\n# The linkedin and last variable are already defined for you\r\nlinkedin <- c(16, 9, 13, 5, 2, 17, 14)\r\nlast <- tail(linkedin, 1)\r\n\r\n# Is last under 5 or above 10?\r\nlast < 5 | last > 10\r\n# TRUE\r\n\r\n# Is last between 15 (exclusive) and 20 (inclusive)?\r\nlast > 15 & last <= 20\r\n# FALSE\r\n\r\n# The social data (linkedin, facebook, views) has been created for you\r\nls()\r\n\r\n# linkedin exceeds 10 but facebook below 10\r\nlinkedin > 10 & facebook < 10\r\n# FALSE FALSE TRUE FALSE FALSE FALSE FALSE\r\n\r\n# When were one or both visited at least 12 times?\r\nlinkedin >= 12 | facebook >= 12\r\n# TRUE FALSE TRUE TRUE FALSE TRUE TRUE\r\n\r\n# When is views between 11 (exclusive) and 14 (inclusive)?\r\nviews > 11 & views <= 14\r\n# [,1] [,2] [,3] [,4] [,5] [,6] [,7]\r\n# [1,] FALSE FALSE TRUE FALSE FALSE FALSE TRUE\r\n# [2,] FALSE FALSE FALSE FALSE FALSE TRUE TRUE\r\n\r\n# li_df is pre-loaded in your workspace\r\nls()\r\nstr(li_df)\r\n\r\n# Select the second column, named day2, from li_df: second\r\nsecond <- li_df$day2\r\n# [1] 3 23 18 18 25 20 4 3 22 12 27 13 17 27 6 35 17 6 1 12 15 17 12 8 7\r\n# [26] 25 15 32 29 1 22 11 5 17 12 26 13 10 37 33 19 29 8 22 10 19 27 18 15 28\r\n\r\n# Build a logical vector, TRUE if value in second is extreme: extremes\r\nextremes <- second > 25 | second < 5\r\n\r\n# Count the number of TRUEs in extremes\r\nsum(extremes)\r\n# 16\r\n\r\n# Variables related to your last day of recordings\r\nmedium <- \"LinkedIn\"\r\nnum_views <- 14\r\n\r\n# Control structure for medium\r\nif (medium == \"LinkedIn\") {\r\n print(\"Showing LinkedIn information\")\r\n} else if (medium == \"Facebook\") {\r\n # Add code to print correct string when condition is True\r\n print(\"Showing Facebook information\")\r\n} else {\r\n print(\"Unknown medium\")\r\n}\r\n\r\n# Control structure for num_views\r\nif (num_views > 15) {\r\n print(\"You're popular!\")\r\n} else if (num_views <= 15 & num_views > 10) {\r\n # Add code to print correct string when condition is TRUE\r\n print(\"Your number of views is average\")\r\n} else {\r\n print(\"Try to be more visible!\")\r\n}\r\n\r\n# Variables related to your last day of recordings\r\nli <- 15\r\nfb <- 9\r\n\r\n# Code the control-flow construct\r\nif (li > 15 & fb > 15) {\r\n sms <- c(sum(li) * 2 + sum(fb) * 2)\r\n} else if (li < 10 & fb < 10) {\r\n sms <- c(sum(li) / 2 + sum(fb) / 2)\r\n} else {\r\n sms <- c(sum(li) + sum(fb))\r\n}\r\n\r\n# Print the resulting sms to the console\r\nsms\r\n\r\n#\r\n#\r\n#\r\n#\r\n#\r\n# Chapter 2 Loop\r\n# Initialize the speed variable\r\nspeed <- 64\r\n\r\n# Code the while loop\r\nwhile ( speed > 30) {\r\n print(\"Slow down!\")\r\n speed = speed -7\r\n}\r\n\r\n# Extend/adapt the while loop\r\nwhile (speed > 30) {\r\n print(paste(\"Your speed is\",speed))\r\n if (speed > 48 ) {\r\n print(\"Slow down big time!\")\r\n speed = speed - 11\r\n } else {\r\n print(\"Slow down!\")\r\n speed = speed - 6\r\n }\r\n}\r\n\r\n# Initialize the speed variable\r\nspeed <- 88\r\n\r\nwhile (speed > 30) {\r\n print(paste(\"Your speed is\", speed))\r\n \r\n # Break the while loop when speed exceeds 80\r\n if (speed > 80) {\r\n break\r\n }\r\n \r\n if (speed > 48) {\r\n print(\"Slow down big time!\")\r\n speed <- speed - 11\r\n } else {\r\n print(\"Slow down!\")\r\n speed <- speed - 6\r\n }\r\n}\r\n\r\n# Initialize i as 1 \r\ni <- 1\r\n\r\n# Code the while loop\r\nwhile (i <= 10) {\r\n print(3 * i)\r\n if ((3 * i %% 8) == 0) {\r\n break\r\n }\r\n i <- i + 1\r\n}\r\n\r\n# The linkedin vector has already been defined for you\r\nlinkedin <- c(16, 9, 13, 5, 2, 17, 14)\r\n\r\n# Loop version 1\r\nfor ( i in linkedin){\r\n print(i)\r\n}\r\n\r\n# Loop version 2\r\nfor (i in 1:length(linkedin)) {\r\n print(linkedin[i])\r\n}\r\n\r\n# The nyc list is already specified\r\nnyc <- list(pop = 8405837, \r\n boroughs = c(\"Manhattan\", \"Bronx\", \"Brooklyn\", \"Queens\", \"Staten Island\"), \r\n capital = FALSE)\r\n\r\n# Loop version 1\r\nfor (i in nyc) {\r\n print(i)\r\n}\r\n\r\n# Loop version 2\r\nfor (i in 1:length(nyc)) {\r\n print(nyc[[i]])\r\n}\r\n\r\n# The tic-tac-toe matrix ttt has already been defined for you\r\n# [,1] [,2] [,3]\r\n# [1,] \"O\" NA \"X\" \r\n# [2,] NA \"O\" \"O\" \r\n# [3,] \"X\" NA \"X\"\r\n\r\n# define the double for loop\r\nfor (x in 1:nrow(ttt)){\r\n for (y in 1:ncol(ttt)){\r\n print(paste(\"On row \", x, \" and column \", y, \" the board contains \", ttt[x,y]))\r\n }\r\n}\r\n\r\nfor (li in linkedin) {\r\n if (li > 10) {\r\n print(\"You're popular!\")\r\n } else {\r\n print(\"Be more visible!\")\r\n }\r\n \r\n # Add if statement with break\r\n if (li > 16){\r\n print(\"This is ridiculous, I'm outta here!\")\r\n break\r\n }\r\n \r\n # Add if statement with next\r\n if (li < 5) {\r\n print(\"This is too embarrassing!\")\r\n next\r\n }\r\n \r\n print(li)\r\n}\r\n\r\n# Pre-defined variables\r\nrquote <- \"r's internals are irrefutably intriguing\"\r\nchars <- strsplit(rquote, split = \"\")[[1]]\r\n\r\n# Initialize rcount\r\nrcount <- 0\r\n\r\n# Finish the for loop\r\nfor (char in chars) {\r\n if (char == \"r\"){\r\n rcount <- rcount + 1\r\n } else if (char == \"u\") {\r\n break\r\n }\r\n}\r\n\r\n# Print out rcount\r\nprint(rcount)\r\n\r\n#\r\n#\r\n#\r\n#\r\n#\r\n# Chapter 3 Functions\r\n# The linkedin and facebook vectors have already been created for you\r\nlinkedin <- c(16, 9, 13, 5, 2, 17, 14)\r\nfacebook <- c(17, 7, 5, 16, 8, 13, 14)\r\n\r\n# Calculate the mean of the sum\r\navg_sum <- sum(mean(linkedin + facebook))\r\n# 22.28571\r\n\r\n# Calculate the trimmed mean of the sum\r\navg_sum_trimmed <- sum(mean(linkedin + facebook,trim = 0.2))\r\n# 22.6\r\n\r\n# The linkedin and facebook vectors have already been created for you\r\nlinkedin <- c(16, 9, 13, 5, NA, 17, 14)\r\nfacebook <- c(17, NA, 5, 16, 8, 13, 14)\r\n\r\n# Basic average of linkedin\r\nprint(mean(linkedin))\r\n# NA\r\n\r\n# Advanced average of linkedin\r\nprint(mean(linkedin, na.rm = TRUE ))\r\n# 12.33333\r\n\r\n# Calculate the mean absolute deviation\r\nprint(mean(abs(linkedin - facebook),na.rm = TRUE))\r\n# 4.8\r\n\r\n# Create a function pow_two()\r\npow_two <- function(x) {\r\n x**2\r\n}\r\n\r\n# Use the function \r\npow_two(12)\r\n\r\n# Create a function sum_abs()\r\nsum_abs <- function(x, y) {\r\n abs(x) + abs(y)\r\n}\r\n\r\n# Use the function\r\nsum_abs(-2, 3)\r\n\r\n# Define the function hello()\r\nhello <- function() {\r\n print(\"Hi there!\")\r\n return(TRUE)\r\n}\r\n\r\n# Call the function hello()\r\nhello()\r\n\r\n# Define the function my_filter()\r\nmy_filter <- function(x) {\r\n if (x > 0) {\r\n return(x)\r\n } else {\r\n return(NULL)\r\n }\r\n}\r\n\r\n# Finish the pow_two() function\r\npow_two <- function(x, print_info = TRUE) {\r\n y <- x ^ 2\r\n \r\n # Add if construct\r\n if (print_info == TRUE) {\r\n print(paste(x, \"to the power two equals\", y))\r\n }\r\n \r\n return(y)\r\n}\r\n\r\ntwo_dice <- function() {\r\n possibilities <- 1:6\r\n dice1 <- sample(possibilities, size = 1)\r\n dice2 <- sample(possibilities, size = 1)\r\n dice1 + dice2\r\n}\r\n\r\n# The linkedin and facebook vectors have already been created for you\r\n\r\n# Define the interpret function\r\ninterpret <- function(num_views) {\r\n if (num_views > 15) {\r\n print(\"You're popular!\")\r\n return(num_views)\r\n } else {\r\n print(\"Try to be more visible!\")\r\n return(0)\r\n }\r\n}\r\n\r\n# Call the interpret function twice\r\ninterpret(linkedin)\r\n# [1] \"You're popular!\"\r\n# [1] 16 9 13 5 2 17 14\r\ninterpret(facebook[2])\r\n# [1] \"Try to be more visible!\"\r\n# [1] 0\r\n\r\n# Define the interpret_all() function\r\n# views: vector with data to interpret\r\n# return_sum: return total number of views on popular days?\r\ninterpret_all <- function(views, return_sum = TRUE) {\r\n count <- 0\r\n \r\n for (v in views) {\r\n count <- count + interpret(v)\r\n }\r\n \r\n if (return_sum) {\r\n return(count)\r\n } else {\r\n return(NULL)\r\n }\r\n}\r\n\r\n# Call the interpret_all() function on both linkedin and facebook\r\ninterpret_all(linkedin)\r\n# [1] \"You're popular!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] \"You're popular!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] 33\r\ninterpret_all(facebook)\r\n# [1] \"You're popular!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] \"You're popular!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] \"Try to be more visible!\"\r\n# [1] 33\r\n\r\n# The mtcars vectors have already been prepared for you\r\nwt <- mtcars$wt\r\nhp <- mtcars$hp\r\n\r\n# Request the currently attached packages\r\nsearch()\r\n\r\n# Load the ggplot2 package\r\nlibrary(ggplot2)\r\n\r\n# Retry the qplot() function\r\nqplot(wt)\r\nqplot(hp)\r\n\r\n# Check out the currently attached packages again\r\nsearch()\r\n\r\n#\r\n#\r\n#\r\n#\r\n#\r\n# Chapter 4 The Apply Family\r\n# The vector pioneers has already been created for you\r\npioneers <- c(\"GAUSS:1777\", \"BAYES:1702\", \"PASCAL:1623\", \"PEARSON:1857\")\r\n\r\n# Split names from birth year\r\nsplit_math <- strsplit(pioneers, split = \":\")\r\n# List of 4\r\n# $ : chr [1:2] \"GAUSS\" \"1777\"\r\n# $ : chr [1:2] \"BAYES\" \"1702\"\r\n# $ : chr [1:2] \"PASCAL\" \"1623\"\r\n# $ : chr [1:2] \"PEARSON\" \"1857\"\r\n\r\n# Convert to lowercase strings: split_low\r\nsplit_low <- lapply(split_math, tolower)\r\n# List of 4\r\n# $ : chr [1:2] \"gauss\" \"1777\"\r\n# $ : chr [1:2] \"bayes\" \"1702\"\r\n# $ : chr [1:2] \"pascal\" \"1623\"\r\n# $ : chr [1:2] \"pearson\" \"1857\"\r\n\r\n# Write function select_first()\r\nselect_first <- function(x) {\r\n x[1]\r\n}\r\n\r\n# Apply select_first() over split_low: names\r\nnames <- lapply(split_low,select_first)\r\n# [[1]]\r\n# [1] \"gauss\"\r\n\r\n# [[2]]\r\n# [1] \"bayes\"\r\n\r\n# [[3]]\r\n# [1] \"pascal\"\r\n\r\n# [[4]]\r\n# [1] \"pearson\"\r\n\r\n# Write function select_second()\r\nselect_second <- function(x) {\r\n x[2]\r\n}\r\n\r\n# Apply select_second() over split_low: years\r\nyears <- lapply(split_low,select_second)\r\n# [[1]]\r\n# [1] \"1777\"\r\n\r\n# [[2]]\r\n# [1] \"1702\"\r\n\r\n# [[3]]\r\n# [1] \"1623\"\r\n\r\n# [[4]]\r\n# [1] \"1857\"\r\n\r\n# Transform: use anonymous function inside lapply\r\nnames <- lapply(split_low, function(x) {x[1]})\r\n\r\n# Transform: use anonymous function inside lapply\r\nyears <- lapply(split_low, function(x) {x[2]})\r\n\r\n# Generic select function\r\nselect_el <- function(x, index) {\r\n x[index]\r\n}\r\n\r\n# Use lapply() twice on split_low: names and years\r\nnames <- lapply(split_low, select_el, index = 1)\r\nyears <- lapply(split_low, select_el, index = 2)\r\n\r\n# Use lapply() to find each day's minimum temperature\r\nlapply(temp,min)\r\n\r\n# Use sapply() to find each day's minimum temperature\r\nsapply(temp,min)\r\n\r\n# Use lapply() to find each day's maximum temperature\r\nlapply(temp,max)\r\n\r\n# Use sapply() to find each day's maximum temperature\r\nsapply(temp,max)\r\n\r\n# temp is already defined in the workspace\r\n\r\n# Finish function definition of extremes_avg\r\nextremes_avg <- function(x) {\r\n ( min(x) + max(x) ) / 2\r\n}\r\n\r\n# Apply extremes_avg() over temp using sapply()\r\nsapply(temp, extremes_avg)\r\n# 4.0 9.0 2.5 2.5 5.5 3.0 5.0\r\n\r\n# Apply extremes_avg() over temp using lapply()\r\nlapply(temp, extremes_avg)\r\n# [[1]]\r\n# [1] 4\r\n\r\n# [[2]]\r\n# [1] 9\r\n\r\n# [[3]]\r\n# [1] 2.5\r\n\r\n# [[4]]\r\n# [1] 2.5\r\n\r\n# [[5]]\r\n# [1] 5.5\r\n\r\n# [[6]]\r\n# [1] 3\r\n\r\n# [[7]]\r\n# [1] 5\r\n\r\n# Create a function that returns min and max of a vector: extremes\r\nextremes <- function(x) {\r\n c(min = min(x), max = max(x))\r\n}\r\n\r\n# Apply extremes() over temp with sapply()\r\nsapply(temp, extremes)\r\n# [,1] [,2] [,3] [,4] [,5] [,6] [,7]\r\n# min -1 5 -3 -2 2 -3 1\r\n# max 9 13 8 7 9 9 9\r\n\r\n# Apply extremes() over temp with lapply()\r\nlapply(temp, extremes)\r\n# [[1]]\r\n# min max \r\n# -1 9 \r\n\r\n# [[2]]\r\n# min max \r\n# 5 13 \r\n\r\n# [[3]]\r\n# min max \r\n# -3 8 \r\n\r\n# [[4]]\r\n# min max \r\n# -2 7 \r\n\r\n# [[5]]\r\n# min max \r\n# 2 9 \r\n\r\n# [[6]]\r\n# min max \r\n# -3 9 \r\n\r\n# [[7]]\r\n# min max \r\n# 1 9 \r\n\r\n# Definition of below_zero()\r\nbelow_zero <- function(x) {\r\n return(x[x < 0])\r\n}\r\n\r\n# Apply below_zero over temp using sapply(): freezing_s\r\nfreezing_s <- sapply(temp, below_zero)\r\n# [[1]]\r\n# [1] -1\r\n\r\n# [[2]]\r\n# numeric(0)\r\n\r\n# [[3]]\r\n# [1] -1 -3\r\n\r\n# [[4]]\r\n# [1] -2\r\n\r\n# [[5]]\r\n# numeric(0)\r\n\r\n# [[6]]\r\n# [1] -3\r\n\r\n# [[7]]\r\n# numeric(0)\r\n\r\n# Apply below_zero over temp using lapply(): freezing_l\r\nfreezing_l <- lapply(temp, below_zero)\r\n# [[1]]\r\n# [1] -1\r\n\r\n# [[2]]\r\n# numeric(0)\r\n\r\n# [[3]]\r\n# [1] -1 -3\r\n\r\n# [[4]]\r\n# [1] -2\r\n\r\n# [[5]]\r\n# numeric(0)\r\n\r\n# [[6]]\r\n# [1] -3\r\n\r\n# [[7]]\r\n# numeric(0)\r\n\r\n# Are freezing_s and freezing_l identical?\r\nidentical(freezing_s, freezing_l)\r\n# TRUE\r\n\r\n# Definition of print_info()\r\nprint_info <- function(x) {\r\n cat(\"The average temperature is\", mean(x), \"\\n\")\r\n}\r\n\r\n# Apply print_info() over temp using lapply()\r\nxl <- lapply(temp, print_info)\r\n# The average temperature is 4.8 \r\n# The average temperature is 9 \r\n# The average temperature is 2.2 \r\n# The average temperature is 2.4 \r\n# The average temperature is 5.4 \r\n# The average temperature is 4.6 \r\n# The average temperature is 4.6 \r\n# [[1]]\r\n# NULL\r\n\r\n# [[2]]\r\n# NULL\r\n\r\n# [[3]]\r\n# NULL\r\n\r\n# [[4]]\r\n# NULL\r\n\r\n# [[5]]\r\n# NULL\r\n\r\n# [[6]]\r\n# NULL\r\n\r\n# [[7]]\r\n# NULL\r\n# Apply print_info() over temp using sapply()\r\nxs <- sapply(temp, print_info)\r\n# The average temperature is 4.8 \r\n# The average temperature is 9 \r\n# The average temperature is 2.2 \r\n# The average temperature is 2.4 \r\n# The average temperature is 5.4 \r\n# The average temperature is 4.6 \r\n# The average temperature is 4.6 \r\n# [[1]]\r\n# NULL\r\n\r\n# [[2]]\r\n# NULL\r\n\r\n# [[3]]\r\n# NULL\r\n\r\n# [[4]]\r\n# NULL\r\n\r\n# [[5]]\r\n# NULL\r\n\r\n# [[6]]\r\n# NULL\r\n\r\n# [[7]]\r\n# NULL\r\n\r\n# Great! Notice here that, quite surprisingly, \r\n# sapply() does not simplify the list of NULL's.\r\n# That's because the 'vector-version' of a list of \r\n# NULL's would simply be a NULL, which is no longer \r\n# a vector with the same length as the input. \r\n\r\n# Definition of basics()\r\nbasics <- function(x) {\r\n c(min = min(x), mean = mean(x), max = max(x))\r\n}\r\n\r\n# Apply basics() over temp using vapply()\r\nvapply(temp, basics, numeric(3))\r\n# [,1] [,2] [,3] [,4] [,5] [,6] [,7]\r\n# min -1.0 5 -3.0 -2.0 2.0 -3.0 1.0\r\n# mean 4.8 9 2.2 2.4 5.4 4.6 4.6\r\n# max 9.0 13 8.0 7.0 9.0 9.0 9.0\r\n\r\n# Convert to vapply() expression\r\nsapply(temp, max)\r\nvapply(temp, max, numeric(1))\r\n# [1] 9 13 8 7 9 9 9\r\n\r\n# Convert to vapply() expression\r\nsapply(temp, function(x, y) { mean(x) > y }, y = 5)\r\nvapply(temp, function(x, y) { mean(x) > y }, y = 5, logical(1))\r\n# [1] FALSE TRUE FALSE FALSE TRUE FALSE FALSE\r\n\r\n# work_todos and fun_todos have already been defined\r\nwork_todos <- c(\"Schedule call with team\", \r\n \"Fix error in Recommendation System\", \r\n \"Respond to Marc from IT\")\r\nfun_todos <- c(\"Sleep\", \"Make arrangements for summer trip\")\r\n\r\n# Create a list: todos\r\ntodos <- list(work_todos, fun_todos)\r\n\r\n# Sort the vectors inside todos alphabetically\r\nsapply(todos, sort)\r\n# [[1]]\r\n# [1] \"Fix error in Recommendation System\" \"Respond to Marc from IT\" \r\n# [3] \"Schedule call with team\" \r\n\r\n# [[2]]\r\n# [1] \"Make arrangements for summer trip\" \"Sleep\"\r\n\r\n#\r\n#\r\n#\r\n#\r\n#\r\n# Chapter 5 Utilities\r\n# abs(): calculate the absolute value.\r\n# sum(): calculate the sum of all the values in a data structure.\r\n# mean(): calculate the arithmetic mean.\r\n# round(): Round the values to 0 decimal places by default. \r\n# seq(): Generate sequences, by specifying the from, to and by arguments.\r\n# rep(): Replicate elements of vectors and lists.\r\n# sort(): Sort a vector in ascending order. Works on numerics, but also on character strings and logicals.\r\n# rev(): Reverse the elements in a data structures for which reversal is defined.\r\n# str(): Display the structure of any R object.\r\n# append(): Merge vectors or lists.\r\n# is.*(): Check for the class of an R object.\r\n# as.*(): Convert an R object from one class to another.\r\n# unlist(): Flatten (possibly embedded) lists to produce a vector.\r\n\r\n# The errors vector has already been defined for you\r\nerrors <- c(1.9, -2.6, 4.0, -9.5, -3.4, 7.3)\r\n\r\n# Sum of absolute rounded values of errors\r\nround(sum(abs(errors)), digits = 0)\r\n# 29\r\n\r\n# The linkedin and facebook vectors have already been created for you\r\nlinkedin <- list(16, 9, 13, 5, 2, 17, 14)\r\nfacebook <- list(17, 7, 5, 16, 8, 13, 14)\r\n\r\n# Convert linkedin and facebook to a vector: li_vec and fb_vec\r\nli_vec <- unlist(linkedin)\r\nfb_vec <- unlist(facebook)\r\n\r\n# Append fb_vec to li_vec: social_vec\r\nsocial_vec <- append(li_vec, fb_vec)\r\n\r\n# Sort social_vec\r\nsort(social_vec, decreasing = TRUE)\r\n# [1] 17 17 16 16 14 14 13 13 9 8 7 5 5 2\r\n\r\n# Create first sequence: seq1\r\nseq1 <- seq(1,500,3)\r\n\r\n# Create second sequence: seq2\r\nseq2 <- seq(1200,900,-7)\r\n\r\n# Calculate total sum of the sequences\r\nsum(seq1,seq2)\r\n# [1] 87029\r\n\r\n# The emails vector has already been defined for you\r\nemails <- c(\"john.doe@ivyleague.edu\", \"education@world.gov\", \"dalai.lama@peace.org\", \r\n \"invalid.edu\", \"quant@bigdatacollege.edu\", \"cookie.monster@sesame.tv\")\r\n\r\n# Use grepl() to match for \"edu\"\r\ngrepl(\"edu\",emails)\r\n# [1] TRUE TRUE FALSE TRUE TRUE FALSE\r\n\r\n# Use grep() to match for \"edu\", save result to hits\r\nhits <- grep(\"edu\", emails)\r\n# [1] 1 2 4 5\r\n\r\n# Subset emails using hits\r\nemails[hits]\r\n# [1] \"john.doe@ivyleague.edu\" \"education@world.gov\" \r\n# [3] \"invalid.edu\" \"quant@bigdatacollege.edu\"\r\n\r\n# @, because a valid email must contain an at-sign.\r\n# .*, which matches any character (.) zero or more times (*). \r\n# Both the dot and the asterisk are metacharacters. You can use them to match any character between the at-sign and the \".edu\" portion of an email address.\r\n# \\\\.edu$, to match the \".edu\" part of the email at the end of the string. The \\\\ part escapes the dot: it tells R that you want to use the . as an actual character.\r\n\r\n# Use grepl() to match for .edu addresses more robustly\r\ngrepl(\"@.*\\\\.edu$\",emails)\r\n# [1] TRUE FALSE FALSE FALSE TRUE FALSE\r\n\r\n# Use grep() to match for .edu addresses more robustly, save result to hits\r\nhits <- grep(\"@.*\\\\.edu$\",emails)\r\n\r\n# Subset emails using hits\r\nemails[hits]\r\n# [1] \"john.doe@ivyleague.edu\" \"quant@bigdatacollege.edu\"\r\n\r\n# Use sub() to convert the email domains to datacamp.edu\r\nsub(\"@.*\\\\.edu$\",\"@datacamp.edu\",emails)\r\n# [1] \"john.doe@datacamp.edu\" \"education@world.gov\"\r\n# [3] \"dalai.lama@peace.org\" \"invalid.edu\"\r\n# [5] \"quant@datacamp.edu\" \"cookie.monster@sesame.tv\"\r\n\r\n# .*: A usual suspect! It can be read as \"any character that is matched zero or more times\".\r\n# \\\\s: Match a space. The \"s\" is normally a character, escaping it (\\\\) makes it a metacharacter.\r\n# [0-9]+: Match the numbers 0 to 9, at least once (+).\r\n# ([0-9]+): The parentheses are used to make parts of the matching string available to define the replacement. \r\n# The \\\\1 in the replacement argument of sub() gets set to the string that is captured by the regular expression [0-9]+.\r\n\r\nawards <- c(\"Won 1 Oscar.\",\r\n \"Won 1 Oscar. Another 9 wins & 24 nominations.\",\r\n \"1 win and 2 nominations.\",\r\n \"2 wins & 3 nominations.\",\r\n \"Nominated for 2 Golden Globes. 1 more win & 2 nominations.\",\r\n \"4 wins & 1 nomination.\")\r\n\r\nsub(\".*\\\\s([0-9]+)\\\\snomination.*$\", \"\\\\1\", awards)\r\n\r\n# [1] \"Won 1 Oscar.\" \"24\" \"2\" \"3\" \"2\" \r\n# [6] \"1\" \r\n\r\n# %Y: 4-digit year (1982)\r\n# %y: 2-digit year (82)\r\n# %m: 2-digit month (01)\r\n# %d: 2-digit day of the month (13)\r\n# %A: weekday (Wednesday)\r\n# %a: abbreviated weekday (Wed)\r\n# %B: month (January)\r\n# %b: abbreviated month (Jan)\r\n# Definition of character strings representing dates\r\nstr1 <- \"May 23, '96\"\r\nstr2 <- \"2012-03-15\"\r\nstr3 <- \"30/January/2006\"\r\n\r\n# Convert the strings to dates: date1, date2, date3\r\ndate1 <- as.Date(str1, format = \"%b %d, '%y\")\r\ndate2 <- as.Date(str2, format = \"%Y-%m-%d\")\r\ndate3 <- as.Date(str3, format = \"%d/%B/%Y\")\r\n\r\n# Convert dates to formatted strings\r\nformat(date1, \"%A\")\r\n# [1] \"Thursday\"\r\nformat(date2, \"%d\")\r\n# [1] \"15\"\r\nformat(date3, \"%b %Y\")\r\n# [1] \"Jan 2006\"\r\n\r\n# %H: hours as a decimal number (00-23)\r\n# %M: minutes as a decimal number\r\n# %S: seconds as a decimal number\r\n# %T: shorthand notation for the typical format %H:%M:%S\r\n\r\n# Definition of character strings representing times\r\nstr1 <- \"May 23, '96 hours:23 minutes:01 seconds:45\"\r\nstr2 <- \"2012-3-12 14:23:08\"\r\n\r\n# Convert the strings to POSIXct objects: time1, time2\r\ntime1 <- as.POSIXct(str1, format = \"%B %d, '%y hours:%H minutes:%M seconds:%S\")\r\ntime2 <- as.POSIXct(str2, format = \"%Y-%m-%d %T\")\r\n\r\n# Convert times to formatted strings\r\nformat(time1, format = \"%M\")\r\n# [1] \"01\"\r\nformat(time2, format = \"%I:%M %p\" )\r\n# [1] \"02:23 PM\"\r\n\r\n# day1, day2, day3, day4 and day5 are already available in the workspace\r\n\r\n# Difference between last and first pizza day\r\nday5-day1\r\n# Time difference of 11 days\r\n\r\n# Create vector pizza\r\npizza <- c(day1, day2, day3, day4, day5)\r\n\r\n# Create differences between consecutive pizza days: day_diff\r\nday_diff <- diff(pizza)\r\n# Time differences in days\r\n# [1] -5 11 -13 18\r\n\r\n# Average period between two consecutive pizza days\r\nmean(day_diff)\r\n# Time difference of 2.75 days\r\n\r\n# login and logout are already defined in the workspace\r\n# Calculate the difference between login and logout: time_online\r\ntime_online <- logout - login\r\n\r\n# Inspect the variable time_online\r\ntime_online\r\n# Time differences in secs\r\n# [1] 2305.11818 34.18472 837.18182 2397.90153 1851.30411\r\n\r\n# Calculate the total time online\r\nsum(time_online)\r\n# Time difference of 7425.69 secs\r\n\r\n# Calculate the average time online\r\nmean(time_online)\r\n# Time difference of 1485.138 secs\r\n\r\n# Convert astro to vector of Date objects: astro_dates\r\n# spring summer fall winter \r\n# \"20-Mar-2015\" \"25-Jun-2015\" \"23-Sep-2015\" \"22-Dec-2015\" \r\nastro_dates <- as.Date(astro, format = \"%d-%b-%Y\")\r\n# [1] \"2015-03-20\" \"2015-06-25\" \"2015-09-23\" \"2015-12-22\"\r\n\r\n# Convert meteo to vector of Date objects: meteo_dates\r\n # spring summer fall winter \r\n # \"March 1, 15\" \"June 1, 15\" \"September 1, 15\" \"December 1, 15\" \r\nmeteo_dates <- as.Date(meteo, format = \"%B %d, %y\")\r\n# [1] \"2015-03-01\" \"2015-06-01\" \"2015-09-01\" \"2015-12-01\"\r\n\r\n# Calculate the maximum absolute difference between astro_dates and meteo_dates\r\nmax(abs(astro_dates-meteo_dates))\r\n# Time difference of 24 days", "meta": {"hexsha": "291e4859b54e4ef26baaba0d8e8d1741cf9f9b14", "size": 23256, "ext": "r", "lang": "R", "max_stars_repo_path": "Intermediate_in_R/Intermediate_in_R.r", "max_stars_repo_name": "mghozyah/couRses", "max_stars_repo_head_hexsha": "ed5561a63ffde98c67d64c233a9b00b7478a0b93", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Intermediate_in_R/Intermediate_in_R.r", "max_issues_repo_name": "mghozyah/couRses", "max_issues_repo_head_hexsha": "ed5561a63ffde98c67d64c233a9b00b7478a0b93", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Intermediate_in_R/Intermediate_in_R.r", "max_forks_repo_name": "mghozyah/couRses", "max_forks_repo_head_hexsha": "ed5561a63ffde98c67d64c233a9b00b7478a0b93", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-17T18:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-17T18:58:48.000Z", "avg_line_length": 23.6341463415, "max_line_length": 166, "alphanum_fraction": 0.6078861369, "num_tokens": 7332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.7331173994236453}} {"text": "################################################################################\n# Monte Carlo Simulation and Resampling Methods for Social Science #\n# Thomas M. Carsey and Jeffrey J. Harden #\n# Chapter 6 File #\n# Last update: 2/28/13 #\n################################################################################\n# Set the working directory\nsetwd(\"C:/Users/jjharden/Dropbox/Research/Sim Book\")\n\n# OLS as a Probability Model\nset.seed(123456) # Set the seed for reproducible results\n\nreps <- 1000 # Set the number of repetitions at the top of the script\npar.est <- matrix(NA, nrow = reps, ncol = 4) # Empty matrix to store the\n # estimates \nb0 <- .2 # True value for the intercept\nb1 <- .5 # True value for the slope\nn <- 1000 # Sample size\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\n\nfor(i in 1:reps){ # Start the loop\nY <- rnorm(n, b0 + b1*X, 1) # The true DGP, Y ~ N(mu, sigma)\nmodel <- lm(Y ~ X) # Estimate OLS model\nvcv <- vcov(model) # Variance-covariance matrix\npar.est[i, 1] <- model$coef[1] # Put the estimate for the intercept\n # in the first column\npar.est[i, 2] <- model$coef[2] # Put the estimate for the coefficient on\n # X in the second column\npar.est[i, 3] <- sqrt(diag(vcv)[1]) # SE of the intercept\npar.est[i, 4] <- sqrt(diag(vcv)[2]) # SE of the coefficient on X\n} # End the loop\n\n# Logit\n# Inverse Logit Function\ninv.logit <- function(p){\nreturn(exp(p)/(1 + exp(p)))\n}\n\n# CP Function\ncoverage <- function(b, se, true, level = .95, df = Inf){ # Estimate, \n # standard error,\n # true parameter, \n # confidence level, \n # and df \nqtile <- level + (1 - level)/2 # Compute the proper quantile\nlower.bound <- b - qt(qtile, df = df)*se # Lower bound\nupper.bound <- b + qt(qtile, df = df)*se # Upper bound \n# Is the true parameter in the confidence interval? (yes = 1)\ntrue.in.ci <- ifelse(true >= lower.bound & true <= upper.bound, 1, 0)\ncp <- mean(true.in.ci) # The coverage probability\nmc.lower.bound <- cp - 1.96*sqrt((cp*(1 - cp))/length(b)) # Monte Carlo error \nmc.upper.bound <- cp + 1.96*sqrt((cp*(1 - cp))/length(b)) \nreturn(list(coverage.probability = cp, # Return results\n true.in.ci = true.in.ci,\n ci = cbind(lower.bound, upper.bound),\n mc.eb = c(mc.lower.bound, mc.upper.bound)))\n}\n\nset.seed(32945) # Set the seed for reproducible results\n\nreps <- 1000 # Set the number of repetitions at the top of the script\npar.est.logit <- matrix(NA, nrow = reps, ncol = 4) # Empty matrix to store\n # the estimates \nb0 <- .2 # True value for the intercept\nb1 <- .5 # True value for the slope\nn <- 1000 # Sample size\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\n\nfor(i in 1:reps){ # Start the loop\nY <- rbinom(n, 1, inv.logit(b0 + b1*X)) # The true DGP, Bernoulli trials\nmodel <- glm(Y ~ X, family = binomial (link = logit)) # Estimate logit model\nvcv <- vcov(model) # Variance-covariance matrix\npar.est.logit[i, 1] <- model$coef[1] # Put the estimate for the \n # intercept in the first column\npar.est.logit[i, 2] <- model$coef[2] # Put the estimate for the coefficient \n # on X in the second column\npar.est.logit[i, 3] <- sqrt(diag(vcv)[1]) # SE of the intercept\npar.est.logit[i, 4] <- sqrt(diag(vcv)[2]) # SE of the coefficient on X\n} # End the loop\n\ncp.beta0.logit <- coverage(par.est.logit[ , 1], par.est.logit[ , 3], b0,\n df = n - model$rank)\ncp.beta1.logit <- coverage(par.est.logit[ , 2], par.est.logit[ , 4], b1,\n df = n - model$rank)\n\npdf(\"logit-hist1.pdf\")\n\npar(mar = c(5, 5.25, .5, .5))\nhist(par.est.logit[ , 1], breaks = 25, col = \"gray50\", ylim = c(0, 150),\n xlab = \"\", ylab = \"\", main = \"\", axes = FALSE)\naxis(1, cex.axis = 1.25)\naxis(2, cex.axis = 1.25, las = 2)\ntitle(xlab = expression(hat(beta[0])), cex.lab = 1.5)\ntitle(ylab = expression(\"Frequency\"), line = 3.75, cex.lab = 1.5)\nabline(v = b0, lwd = 4)\ntext(.05, 70, expression(\"True\"~beta[0]~\"= 0.20\"), cex = 1.5)\nbox()\n\ndev.off()\n\npdf(\"logit-hist2.pdf\")\n\npar(mar = c(5, 5.25, .5, .5))\nhist(par.est.logit[ , 2], breaks = 25, xlim = c(.1, .9), col = \"gray50\",\n ylim = c(0, 200), xlab = \"\", ylab = \"\", main = \"\", axes = FALSE)\naxis(1, at = seq(.1, .9, .1), cex.axis = 1.25)\naxis(2, cex.axis = 1.25, las = 2)\ntitle(xlab = expression(hat(beta)[1]), cex.lab = 1.5)\ntitle(ylab = expression(\"Frequency\"), line = 3.75, cex.lab = 1.5)\nabline(v = b1, lwd = 4)\ntext(.75, 125, expression(\"True\"~beta[1]~\"= 0.50\"), cex = 1.5)\nbox()\n\ndev.off()\n\n# Probit\nset.seed(3295255) # Set the seed for reproducible results\n\nreps <- 1000 # Set the number of repetitions at the top of the script\npar.est.probit <- matrix(NA, nrow = reps, ncol = 4) # Empty matrix to store\n # the estimates \nb0 <- .2 # True value for the intercept\nb1 <- .5 # True value for the slope\nn <- 1000 # Sample size\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\n\nfor(i in 1:reps){ # Start the loop\nY <- rbinom(n, 1, pnorm(b0 + b1*X)) # The true DGP, Bernoulli trials\nmodel <- glm(Y ~ X, family = binomial (link = probit)) # Estimate probit model\nvcv <- vcov(model) # Variance-covariance matrix\npar.est.probit[i, 1] <- model$coef[1] # Put the estimate for the \n # intercept in the first column\npar.est.probit[i, 2] <- model$coef[2] # Put the estimate for the coefficient \n # on X in the second column\npar.est.probit[i, 3] <- sqrt(diag(vcv)[1]) # SE of the intercept\npar.est.probit[i, 4] <- sqrt(diag(vcv)[2]) # SE of the coefficient on X\n} # End the loop\n\nmean(par.est.probit[ , 1]) # Mean of intercept estimates\nmean(par.est.probit[ , 2]) # Mean of coefficient on X estimates\n# Coverage probability for the intercept\ncoverage(par.est.probit[ , 1], par.est.probit[ , 3], b0,\n df = n - model$rank)$coverage.probability\n# Coverage probability for the coefficient on X\ncoverage(par.est.probit[ , 2], par.est.probit[ , 4], b1,\n df = n - model$rank)$coverage.probability\n\n# Ordered Models\nlibrary(MASS)\nset.seed(8732) # Set the seed for reproducible results\n\nreps <- 1000 # Set the number of repetitions at the top of the script\npar.est.oprobit <- matrix(NA, nrow = reps, ncol = 2) # Empty matrices to store\ntaus.oprobit <- matrix(NA, nrow = reps, ncol = 3) # the estimates \nb0 <- 0 # True value for the intercept\nb1 <- .5 # True value for the slope\nn <- 1000 # Sample size\nX <- rnorm(n, 0, 1) # Create a sample of n observations on the \n # independent variable X\n\nXB <- b0 + b1*X # Systematic component\nsd.error <- 1 # SD of the error of the unobserved Y*\n# Define the true cutpoints\ntau1 <- qnorm(.1, mean = mean(XB), sd = sqrt(var(XB) + sd.error^2)) \ntau2 <- qnorm(.5, mean = mean(XB), sd = sqrt(var(XB) + sd.error^2)) \ntau3 <- qnorm(.9, mean = mean(XB), sd = sqrt(var(XB) + sd.error^2)) \n\nfor(i in 1:reps){ # Start the loop\nY.star <- rnorm(n, XB, sd.error) # The unobserved Y*\nY <- rep(NA, n) # Define Y as a vector of NAs with length n\nY[Y.star < tau1] <- 1 # Set Y equal to a value according to Y.star\nY[Y.star >= tau1 & Y.star < tau2] <- 2\nY[Y.star >= tau2 & Y.star < tau3] <- 3\nY[Y.star >= tau3] <- 4\n# Estimate ordered model\nmodel <- polr(as.ordered(Y) ~ X, method = \"probit\", Hess = TRUE) \nvcv <- vcov(model) # Variance-covariance matrix\npar.est.oprobit[i, 1] <- model$coef[1] # Put the estimate for the coefficient\n # on X in the second column\npar.est.oprobit[i, 2] <- sqrt(diag(vcv)[1]) # SE of the coefficient on X\ntaus.oprobit[i, ] <- model$zeta\ncat(\"Just completed iteration\", i, \"\\n\")\n} # End the loop\n\npdf(\"ystar.pdf\")\n\npar(mar = c(5, 5.25, .5, .5))\nplot(Y.star, Y, xlim = c(-3, 3), xlab = \"\", ylab = \"\", main = \"\",\n axes = FALSE, pch = 19)\naxis(1, at = seq(-3, 3, 1), cex.axis = 1.25)\naxis(2, at = 1:4, cex.axis = 1.25, las = 2)\ntitle(xlab = expression(\"Y* (Unobserved/Continuous)\"), cex.lab = 1.5)\ntitle(ylab = expression(\"Y (Observed/Categorical)\"), line = 3.75,\n cex.lab = 1.5)\nabline(v = c(tau1, tau2, tau3), lwd = 2, lty = 3)\ntext(tau1 - .25, 3.5, expression(tau[1]), cex = 2)\ntext(tau2 - .25, 3.5, expression(tau[2]), cex = 2)\ntext(tau3 - .25, 3.5, expression(tau[3]), cex = 2)\nbox()\n\ndev.off()\n\nmean(par.est.oprobit[ , 1]) # Mean of coefficient on X estimates\n# Compare the actual taus to the means of the tau estimates\ndata.frame(True = c(tau1, tau2, tau3), Estimated = apply(taus.oprobit, 2, mean))\n# Coverage probability for the coefficient on X\ncoverage(par.est.oprobit[ , 1], par.est.oprobit[ , 2], b1,\n df = n - length(c(coef(model), model$zeta)))$coverage.probability\n\n# Unordered Models\nlibrary(Zelig)\nset.seed(45262) # Set the seed for reproducible results\n\nreps <- 1000 # Set the number of repetitions at the top of the script\npar.est.mnl <- matrix(NA, nrow = reps, ncol = 4) # Empty matrix to store\n # the estimates \nb0A <- .2 # True values for the intercepts\nb0B <- -.2\nb1A <- .5 # True values for the slopes\nb1B <- .75\nn <- 1000 # Sample size\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\n# Compute the probabilities of each outcome based on the DGP\npA <- exp(b0A + b1A*X)/(1 + exp(b0A + b1A*X) + exp(b0B + b1B*X))\npB <- exp(b0B + b1B*X)/(1 + exp(b0A + b1A*X) + exp(b0B + b1B*X))\npC <- 1 - pA - pB\n\nfor(i in 1:reps){ # Start the loop\nY <- rep(NA, n) # Define Y as a vector of NAs with length n\nfor(j in 1:n){ # Create the dependent variable in another loop\nY[j] <- sample(c(\"A\", \"B\", \"C\"), 1, replace = TRUE,\n prob = c(pA[j], pB[j], pC[j]))\n}\n\n# Estimate a MNL model\nmodel <- zelig(as.factor(Y) ~ X, model = \"mlogit\",\n data = data.frame(Y, X), cite = FALSE)\nvcv <- vcov(model) # Variance-covariance matrix\npar.est.mnl[i, 1] <- coefficients(model)[3] # Coefficient on X, outcome 1 \npar.est.mnl[i, 2] <- coefficients(model)[4] # Coefficient on X, outcome 2\npar.est.mnl[i, 3] <- sqrt(diag(vcv)[3]) # SE of coefficient on X, outcome 1\npar.est.mnl[i, 4] <- sqrt(diag(vcv)[4]) # SE of coefficient on X, outcome 2\ncat(\"Just completed iteration\", i, \"\\n\")\n} # End the loop\n\n# Mean of coefficients on X estimates\nmean(par.est.mnl[ , 1]) # Outcome 1\nmean(par.est.mnl[ , 2]) # Outcome 2\n\n# Coverage probabilities for the coefficients on X\n# Outcome 1\ncoverage(par.est.mnl[ , 1], par.est.mnl[ , 3], b1A,\n df = n - length(coef(model)))$coverage.probability\n# Outcome 2\ncoverage(par.est.mnl[ , 2], par.est.mnl[ , 4], b1B,\n df = n - length(coef(model)))$coverage.probability\n\n# Ordered vs. MNL\nlibrary(Zelig)\nset.seed(99999)\n\nreps <- 1000 # Set the number of repetitions at the top of the script\nd.pp <- array(NA, c(4, 3, reps)) # Empty array to store \n # simulated change in probabilities\n\n# Ordered logit model DGP\nb0 <- 0 # True value for the intercept\nb1 <- .5 # True value for the slope\nn <- 1000 # Sample size\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\n\n# MNL model DGP\nb0A <- .2 # True values for the intercepts\nb0B <- -.2\nb1A <- .5 # True values for the slopes\nb1B <- .75\nn <- 1000 # Sample size\n\n# Compute the probabilities of each outcome based on the DGP\npA <- exp(b0A + b1A*X)/(1 + exp(b0A + b1A*X) + exp(b0B + b1B*X))\npB <- exp(b0B + b1B*X)/(1 + exp(b0A + b1A*X) + exp(b0B + b1B*X))\npC <- 1 - pA - pB\n \nfor(i in 1:reps){\n# Ordered dependent variable\nY.star <- rlogis(n, b0 + b1*X, 1) # The unobserved Y*\n# Define the true cutpoints\ntau1 <- quantile(Y.star, .25) \ntau2 <- quantile(Y.star, .75) \nY.o <- rep(NA, n) # Define Y as a vector of NAs with length n\nY.o[Y.star < tau1] <- 1 # Set Y equal to a value according to Y.star\nY.o[Y.star >= tau1 & Y.star < tau2] <- 2\nY.o[Y.star >= tau2] <- 3\n# Ordered data\no.data <- data.frame(Y.o, X) # Put the data in a data frame\n\n# Unordered dependent variable\nY.m <- rep(NA, n) # Define Y as a vector of NAs with length n\nfor(j in 1:n){ # Create the dependent variable in another loop\nY.m[j] <- sample(1:3, 1, replace = TRUE, prob = c(pA[j], pB[j], pC[j]))\n}\n# Unordered data\nm.data <- data.frame(Y.m, X) # Put the data in a data frame\n\n# Estimate the models with the ordered dependent variable\no.correct <- zelig(as.ordered(Y.o) ~ X, model = \"ologit\",\n data = o.data, cite = FALSE)\nm.incorrect <- zelig(as.factor(Y.o) ~ X, model = \"mlogit\",\n data = o.data, cite = FALSE)\n\n# Estimate the models with the multinomial dependent variable\nm.correct <- zelig(as.factor(Y.m) ~ X, model = \"mlogit\",\n data = m.data, cite = FALSE)\no.incorrect <- zelig(as.ordered(Y.m) ~ X, model = \"ologit\",\n data = m.data, cite = FALSE)\n\n# Set X to its minimum and maximum for each model\nx.oc <- setx(o.correct, X = min(X)) # For o.correct\nx.oc1 <- setx(o.correct, X = max(X)) \n\nx.mi <- setx(m.incorrect, X = min(X)) # For m.incorrect\nx.mi1 <- setx(m.incorrect, X = max(X)) \n\nx.mc <- setx(m.correct, X = min(X)) # For m.correct\nx.mc1 <- setx(m.correct, X = max(X))\n \nx.oi <- setx(o.incorrect, X = min(X)) # For o.incorrect\nx.oi1 <- setx(o.incorrect, X = max(X)) \n\n# Compute the change in expected probabilities of falling in each category\n# when moving from the minimum to the maximum of X\nsim.oc <- sim(o.correct, x = x.oc, x1 = x.oc1)$qi$fd\nsim.mi <- sim(m.incorrect, x = x.mi, x1 = x.mi1)$qi$fd\nsim.mc <- sim(m.correct, x = x.mc, x1 = x.mc1)$qi$fd\nsim.oi <- sim(o.incorrect, x = x.oi, x1 = x.oi1)$qi$fd\nd.pp[1, , i] <- apply(sim.oc, 2, mean)\nd.pp[2, , i] <- apply(sim.mi, 2, mean)\nd.pp[3, , i] <- apply(sim.mc, 2, mean)\nd.pp[4, , i] <- apply(sim.oi, 2, mean)\ncat(\"Just completed iteration\", i, \"of\", reps, \"\\n\")\n}\n\n# Compute the average change in probability for each of the four models\ndpp.means <- rbind(apply(d.pp[1, , ], 1, mean), apply(d.pp[2, , ], 1, mean), apply(d.pp[3, , ], 1, mean), apply(d.pp[4, , ], 1, mean))\n\n# Compute the SD of the change in probability for each of the four models\ndpp.sds <- rbind(apply(d.pp[1, , ], 1, sd), apply(d.pp[2, , ], 1, sd), apply(d.pp[3, , ], 1, sd), apply(d.pp[4, , ], 1, sd))\n\n# LaTeX table\nlibrary(xtable)\nresults <- rbind(dpp.means, dpp.sds)\n\nxtable(results, digits = 4, caption = \"Means and Standard Deviations of the Change in expected probability for Each Category\", label = \"ord-unord-results\", align = \"lrrr\")\n\n# Count Models\n# Poisson \nset.seed(3759) # Set the seed for reproducible results\n\nreps <- 1000 # Set the number of repetitions at the top of the script\npar.est.pois <- matrix(NA, nrow = reps, ncol = 4) # Empty matrix to store the\n # estimates \nb0 <- .2 # True value for the intercept\nb1 <- .5 # True value for the slope\nn <- 1000 # Sample size\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\n\nfor(i in 1:reps){ # Start the loop\nY <- rpois(n, exp(b0 + b1*X)) # The true DGP\nmodel <- glm(Y ~ X, family = \"poisson\") # Estimate Poisson model\nvcv <- vcov(model) # Variance-covariance matrix\npar.est.pois[i, 1] <- model$coef[1] # Put the estimate for the intercept\n # in the first column\npar.est.pois[i, 2] <- model$coef[2] # Put the estimate for the coefficient on\n # X in the second column\npar.est.pois[i, 3] <- sqrt(diag(vcv)[1]) # SE of the intercept\npar.est.pois[i, 4] <- sqrt(diag(vcv)[2]) # SE of the coefficient on X\n} # End the loop\n\n# Means of the coefficient estimates\nmean(par.est.pois[ , 1]) # Intercept\nmean(par.est.pois[ , 2]) # Coefficient on X\n\n# Coverage probabilities \n# Intercept\ncoverage(par.est.pois[ , 1], par.est.pois[ , 3], b0,\n df = n - model$rank)$coverage.probability\n# Coefficient on X\ncoverage(par.est.pois[ , 2], par.est.pois[ , 4], b1,\n df = n - model$rank)$coverage.probability\n\npdf(\"od1.pdf\")\n\npar(mar = c(5, 5.25, .5, .5)) \nplot(1:n, Y, ylim = c(0, 20), col = \"gray50\", xlab = \"\", ylab = \"\",\n main = \"\", axes = FALSE)\naxis(1, cex.axis = 1.25)\naxis(2, at = 0:20, cex.axis = 1.25, las = 2)\ntitle(xlab = expression(\"Observations\"), cex.lab = 1.5)\ntitle(ylab = expression(\"Y\"), line = 3.75, cex.lab = 1.5)\nabline(h = mean(Y), lwd = 2)\nabline(h = var(Y), lwd = 2, lty = 2)\nbox()\nlegend(\"topleft\", bty = \"n\", c(expression(\"Mean of Y\"),\n expression(\"Variance of Y\")), lty = c(1, 2), lwd = 2, cex = 1.5)\n\ndev.off()\n\n# Poisson vs. Negative Binomial\nlibrary(MASS)\nset.seed(763759) # Set the seed for reproducible results\n\nreps <- 1000 # Set the number of repetitions at the top of the script\npar.est.pnb <- matrix(NA, nrow = reps, ncol = 4) # Empty matrix to store the\n # estimates \nb0 <- .2 # True value for the intercept\nb1 <- .5 # True value for the slope\nn <- 1000 # Sample size\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\n \nfor(i in 1:reps){\nY <- rnbinom(n, size = .5, mu = exp(b0 + b1*X)) # Generate data with\n # overdispersion\nmodel.p <- glm(Y ~ X, family = \"poisson\") # Estimate Poisson model\nmodel.nb <- glm.nb(Y ~ X) # Estimate NB model\nvcv.p <- vcov(model.p) # Variance-covariance matrices\nvcv.nb <- vcov(model.nb)\npar.est.pnb[i, 1] <- model.p$coef[2] # Store the results\npar.est.pnb[i, 2] <- model.nb$coef[2] \npar.est.pnb[i, 3] <- sqrt(diag(vcv.p)[2]) \npar.est.pnb[i, 4] <- sqrt(diag(vcv.nb)[2])\ncat(\"Completed\", i, \"of\", reps, \"\\n\")\n}\n\n# Means of the coefficient on X estimates\nmean(par.est.pnb[ , 1]) # Poisson estimates\nmean(par.est.pnb[ , 2]) # NB estimates\n\n# MSE\nmean((par.est.pnb[ , 1])^2) # Poisson MSE\nmean((par.est.pnb[ , 2])^2) # NB MSE\n\n# Coverage probabilities \n# Poisson SEs\ncoverage(par.est.pnb[ , 1], par.est.pnb[ , 3], b1,\n df = n - model.p$rank)$coverage.probability\n# NB SEs\ncoverage(par.est.pnb[ , 2], par.est.pnb[ , 4], b1,\n df = n - model.nb$rank)$coverage.probability\n\npdf(\"od2.pdf\")\n\npar(mar = c(5, 5.25, .5, .5)) \nplot(1:n, Y, ylim = c(0, 20), col = \"gray50\", xlab = \"\", ylab = \"\",\n main = \"\", axes = FALSE)\naxis(1, cex.axis = 1.25)\naxis(2, at = 0:20, cex.axis = 1.25, las = 2)\ntitle(xlab = expression(\"Observations\"), cex.lab = 1.5)\ntitle(ylab = expression(\"Y\"), line = 3.75, cex.lab = 1.5)\nabline(h = mean(Y), lwd = 2)\nabline(h = var(Y), lwd = 2, lty = 2)\nbox()\nlegend(\"topleft\", bty = \"n\", c(expression(\"Mean of Y\"),\n expression(\"Variance of Y\")), lty = c(1, 2), lwd = 2, cex = 1.5)\n\ndev.off()\n\n# Negative Binomial vs. Zero-Inflated Negative Binomial\nlibrary(pscl)\n# Zero-inflated negative binomial random number generator\nrzinbinom <- function(n, mu, size, zprob){ \nifelse(rbinom(n, 1, zprob) == 1, 0, rnbinom(n, size = size, mu = mu))\n}\n\nset.seed(2837) # Set the seed for reproducible results\n\nreps <- 1000 # Set the number of repetitions at the top of the script\npar.est.zinb <- matrix(NA, nrow = reps, ncol = 4) # Empty matrix to store\n # the estimates \nb0z <- -.8 # True value for the inflation intercept\nb1z <- .3 # True value for the inflation slope \nb0c <- .2 # True value for the count intercept\nb1c <- .5 # True value for the count slope\nn <- 1000 # Sample size\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\nZ <- rnorm(n, X, 1) # Inflation independent variable\n\nfor(i in 1:reps){\n# Generate data with a zero-inflation component\nY.zi <- rzinbinom(n, mu = exp(b0c + b1c*X), size = .5,\nzprob = exp(b0z + b1z*Z)/(1 + exp(b0z + b1z*Z)))\n\n# Generate data with no zero-inflation component\nY.nozi <- rzinbinom(n, mu = exp(b0c + b1c*X), size = .5, zprob = 0) \nmodel.nb1 <- glm.nb(Y.zi ~ X) # Standard negative binomial\nmodel.nb2 <- glm.nb(Y.nozi ~ X)\nmodel.zinb1 <- zeroinfl(Y.zi ~ X | Z, dist = \"negbin\") # Zero-inflated model\nmodel.zinb2 <- zeroinfl(Y.nozi ~ X | Z, dist = \"negbin\") \n\n# Store the estimates of the coefficient on X (count equation)\npar.est.zinb[i, 1] <- model.nb1$coef[2] # Standard NB, with ZI\npar.est.zinb[i, 2] <- model.nb2$coef[2] # Standard NB, no ZI\npar.est.zinb[i, 3] <- as.numeric(model.zinb1$coef$count[2]) # ZI NB, with ZI\npar.est.zinb[i, 4] <- as.numeric(model.zinb2$coef$count[2]) # ZI NB, no ZI\ncat(\"Completed\", i, \"of\", reps, \"\\n\")\n}\n\npdf(\"zinb-zi.pdf\")\n\npar(mar = c(5, 5.25, .5, .5)) \nplot(density(par.est.zinb[ , 1]), xlim = c(-.5, 1.5), ylim = c(0, 3.5),\n lwd = 3, xlab = \"\", ylab = \"\", main = \"\", axes = FALSE)\nlines(density(par.est.zinb[ , 3]), lwd = 3, lty = 2)\naxis(1, cex.axis = 1.25)\naxis(2, cex.axis = 1.25, las = 2)\ntitle(xlab = expression(hat(beta[1])), cex.lab = 1.5)\ntitle(ylab = expression(\"Density\"), line = 3.75, cex.lab = 1.5)\nabline(v = b1, lwd = 2)\ntext(1, 2, expression(\"True\"~beta[1]~\"= 0.50\"), cex = 1.5)\nbox()\nlegend(\"topright\", bty = \"n\", c(expression(\"Standard NB\"),\n expression(\"ZINB\")), lty = c(1, 2), lwd = 3, cex = 1.5)\n\ndev.off()\n\npdf(\"zinb-nozi.pdf\")\n\npar(mar = c(5, 5.25, .5, .5)) \nplot(density(par.est.zinb[ , 2]), xlim = c(-.5, 1.5), ylim = c(0, 5),\n lwd = 3, xlab = \"\", ylab = \"\", main = \"\", axes = FALSE)\nlines(density(par.est.zinb[ , 4]), lwd = 3, lty = 2)\naxis(1, cex.axis = 1.25)\naxis(2, cex.axis = 1.25, las = 2)\ntitle(xlab = expression(hat(beta[1])), cex.lab = 1.5)\ntitle(ylab = expression(\"Density\"), line = 3.75, cex.lab = 1.5)\nabline(v = b1, lwd = 2)\ntext(1, 2, expression(\"True\"~beta[1]~\"= 0.50\"), cex = 1.5)\nbox()\nlegend(\"topright\", bty = \"n\", c(expression(\"Standard NB\"),\n expression(\"ZINB\")), lty = c(1, 2), lwd = 3, cex = 1.5)\n\ndev.off()\n\n# Duration Models (Cox PH)\nlibrary(survival)\nlibrary(coxrobust)\n\nset.seed(4679) # Set the seed for reproducible results\n\nreps <- 1000 # Set the number of repetitions at the top of the script\npar.est.cox <- matrix(NA, nrow = reps, ncol = 3) # Empty matrix to store\n # the estimates \nb1 <- .5 # True value for the slope\nn <- 1000 # Sample size\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\nZ <- runif(n, -1, 1) # Create an omitted variable\n\nfor(i in 1:reps){ # Start the loop\nY <- rexp(n, exp(b1*X + Z)) # Generate survival times\nYs <- Surv(Y, event = rep(1, n))\nmodel.plm <- coxph(Ys ~ X, method = \"breslow\") # Standard PLM estimator\nmodel.irr <- coxr(Ys ~ X, trunc = .95) # IRR, downweighting outliers (5%)\nmodel.irr2 <- coxr(Ys ~ X, trunc = .8) # IRR, even more downweighting (20%)\npar.est.cox[i, 1] <- model.plm$coef[1] # Store the estimates\npar.est.cox[i, 2] <- model.irr$coef[1]\npar.est.cox[i, 3] <- model.irr2$coef[1]\ncat(\"Completed\", i, \"of\", reps, \"\\n\")\n}\n\napply(par.est.cox, 2, mean)\napply(par.est.cox, 2, sd)\n\nmean((par.est.cox[ , 1] - b1)^2)\nmean((par.est.cox[ , 2] - b1)^2)\nmean((par.est.cox[ , 3] - b1)^2)\n\npdf(\"cox.pdf\")\n\npar(mar = c(5, 5.25, .5, .5)) \nplot(density(par.est.cox[ , 1]), xlim = c(.15, .65), lwd = 3, xlab = \"\",\n ylab = \"\", main = \"\", axes = FALSE)\nlines(density(par.est.cox[ , 2]), lwd = 3, lty = 2)\nlines(density(par.est.cox[ , 3]), lwd = 3, lty = 3)\naxis(1, cex.axis = 1.25)\naxis(2, cex.axis = 1.25, las = 2)\ntitle(xlab = expression(hat(beta[1])), cex.lab = 1.5)\ntitle(ylab = expression(\"Density\"), line = 3.75, cex.lab = 1.5)\nabline(v = b1, lwd = 2)\ntext(.58, 6, expression(\"True\"~beta[1]~\"= 0.50\"), cex = 1.5)\nbox()\nlegend(\"topleft\", bty = \"n\", c(expression(\"PLM\"), expression(\"IRR 5%\"),\n expression(\"IRR 20%\")), lty = c(1, 2, 3), lwd = 3, cex = 1.5)\n\ndev.off()\n\n# Computational Issues\nsource(\"parallel1.r\")\nsource(\"parallel2.r\")\n", "meta": {"hexsha": "20515435198e730f64f91128917df30a67a9ae8b", "size": 24089, "ext": "r", "lang": "R", "max_stars_repo_path": "inst/extdata/Chapter6.r", "max_stars_repo_name": "rmsharp/stepwiser", "max_stars_repo_head_hexsha": "639eb2c055aa23a1d6e4d71b6df63dd3f4ad6f6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-12T17:54:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-12T17:54:26.000Z", "max_issues_repo_path": "inst/extdata/Chapter6.r", "max_issues_repo_name": "rmsharp/stepwiser", "max_issues_repo_head_hexsha": "639eb2c055aa23a1d6e4d71b6df63dd3f4ad6f6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inst/extdata/Chapter6.r", "max_forks_repo_name": "rmsharp/stepwiser", "max_forks_repo_head_hexsha": "639eb2c055aa23a1d6e4d71b6df63dd3f4ad6f6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6853377265, "max_line_length": 171, "alphanum_fraction": 0.5975341442, "num_tokens": 8103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7331088048041415}} {"text": "dms_to_rad <- function(d, m, s) (d + m / 60 + s / 3600) * pi / 180\n\n# Volumetric mean radius is 6371 km, see http://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html\n# The diameter is thus 12742 km\n\ngreat_circle_distance <- function(lat1, long1, lat2, long2) {\n a <- sin(0.5 * (lat2 - lat1))\n b <- sin(0.5 * (long2 - long1))\n 12742 * asin(sqrt(a * a + cos(lat1) * cos(lat2) * b * b))\n}\n\n# Coordinates are found here:\n# http://www.airport-data.com/airport/BNA/\n# http://www.airport-data.com/airport/LAX/\n\ngreat_circle_distance(\n dms_to_rad(36, 7, 28.10), dms_to_rad( 86, 40, 41.50), # Nashville International Airport (BNA)\n dms_to_rad(33, 56, 32.98), dms_to_rad(118, 24, 29.05)) # Los Angeles International Airport (LAX)\n\n# Output: 2886.327\n", "meta": {"hexsha": "87bc482ae7c3a094449453e3eacda57905f284de", "size": 768, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Haversine-formula/R/haversine-formula.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Haversine-formula/R/haversine-formula.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Haversine-formula/R/haversine-formula.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 36.5714285714, "max_line_length": 102, "alphanum_fraction": 0.6575520833, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102552339746, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7330980461296693}} {"text": "# Anomaly detection\n# Examples based on the following blog:\n# http://tjo.hatenablog.com/entry/2017/01/11/190000\n# Which was based on the following book:\n# https://www.amazon.co.jp/%E5%85%A5%E9%96%80-%E6%A9%9F%E6%A2%B0%E5%AD%A6%E7%BF%92%E3%81%AB%E3%82%88%E3%82%8B%E7%95%B0%E5%B8%B8%E6%A4%9C%E7%9F%A5%E2%80%95R%E3%81%AB%E3%82%88%E3%82%8B%E5%AE%9F%E8%B7%B5%E3%82%AC%E3%82%A4%E3%83%89-%E4%BA%95%E6%89%8B-%E5%89%9B/dp/4339024910\n\nd <- read.csv('watertreatment_mod.csv')\n\nd.dist <- dist(d[,-1])\n\nd.hcl <- hclust(d.dist, method='ward.D2')\n\nplot(d.hcl, labels=d[,1])\n\n# Try k-means for 4 to 10 clusters\n\nfor (i in 4:10){\n km <- kmeans(d[,-1], centers = i)\n print(table(km$cluster))\n}\n\n# Investigate the cluster of only 3 datapoints for k > 7\nfor (i in 8:10){\n km <- kmeans(d[,-1], centers = i)\n cls <- which(table(km$cluster)==3)\n print(d$date[km$cluster==cls])\n}\n\n# Seems the 3 same dates have anomalies\n\n###################\n\n# Part 2\n# http://tjo.hatenablog.com/entry/2017/02/08/190000\n\n# Anomaly detection for 1-D case under normal distribution\n\n# Create data\n\nset.seed(1)\nx1 <- rnorm(300) # White noise\nx2 <- rep(c(15, rep(0,49)),6) # Create data spikes\nx3 <- c(rep(0,150),rep(3,150)) # Step data\n\nx <- x1 + x2 + x3\ny <- x+c(rep(0,130),30,rep(0,169)) # Add anomaly of size 30 at 131st element\n\n# Line plot\nplot(y, type = 'l')\n\n# point plot\nplot(y)\n\nmu <- mean(y)\ns2 <- mean((y - mu)^2)\nmu\ns2\n\na <- (y - mu)^2 / s2\nthr <- qchisq(0.99, 1) # Deviation from 99% threshold of Chi Sq distro\n\nplot(a)\nsegments(0, thr, 300, thr, col='red', lty = 3, lwd = 3) # draw lines\n\n# Note how the spike at 30 is looks even more like an anomaly when graphed using Chi Sq\n\n# Hotelling T2\n\n# Normally distrbuted variables in 3D\nset.seed(1)\nx <- rnorm(n = 500, mean = 1, sd = 1)\nset.seed(2)\ny <- rnorm(n = 500, mean = 1, sd = 1)\nset.seed(3)\nz <- rnorm(n = 500, mean = 1, sd = 1)\nd <- data.frame(x = x, y = y, z = z)\n\n# Add 3 anomalies\nset.seed(4)\nidx <- sample(nrow(d), 3)\nd[idx,] <- d[idx,] + 10\n\ninstall.packages('scatterplot3d')\nlibrary(scatterplot3d)\nscatterplot3d(d, pch=19, cex.symbols=0.5)\n\n# Calculate Hotelling's T^2\nX <- as.matrix(d)\nmx <- colMeans(X)\nXc <- as.matrix(X) - matrix(1, nrow(X), 1) %*% mx\nSx <- t(Xc) %*% Xc / nrow(X)\nam <- rowSums((Xc %*% solve(Sx)) * Xc)\nthr <- qchisq(0.99, 1)\nplot(am)\nsegments(0, thr, 500, thr, col='red', lty=3, lwd=3)\n\n# Plot the anomalies in red\nidx_a <- which(am > thr)\ncol_3d <- rep(1, 500)\ncol_3d[idx_a] <- 2\ncex_3d <- rep(0.5, 500)\ncex_3d[idx_a] <- 2\nscatterplot3d(d, pch=19, cex.symbols = cex_3d, color=col_3d)\n\n# Mahalanobis-Taguchi Method\n# http://tjo.hatenablog.com/entry/2017/02/08/190000\n\n# Make 3D points from normally ditributed random numbers\n\nxt <- rnorm(n = 500, mean = 1, sd = 1)\nyt <- rnorm(n = 500, mean = 1, sd = 1)\nzt <- rnorm(n = 500, mean = 1, sd = 1)\ndt <- data.frame(x = xt, y = yt, z = zt)\n\n# Insert 3 deviations in the z direction\nidxt <- sample(nrow(dt), 3)\ndt[idxt,3] <- dt[idxt,3] + 20\nscatterplot3d(dt, pch=19, cex.symbols = 0.5)\n\n# Find anomalies using Hotelling T^2 and Mahalanobis-Taguchi\nXt <- as.matrix(dt)\nmxt <- colMeans(Xt)\nXct <- as.matrix(Xt) - matrix(1, nrow(Xt), 1) %*% mxt\nSxt <- t(Xct) %*% Xct / nrow(Xt)\namt <- rowSums((Xct %*% solve(Sxt)) * Xct) / ncol(Xt)\nthrt <- 1\nplot(amt)\nsegments(0, thrt, 500, thrt, col = 'red', lty=3, lwd=3)\n\n# Plot the anomalies as red points\nidx_at <- which(amt > thrt)\ncol_3dt <- rep(1, 500)\ncol_3dt[idx_at] <- 2\ncex_3dt <- rep(0.5, 500)\ncex_3dt[idx_at] <- 2\nscatterplot3d(dt, pch=19, cex.symbols = cex_3dt, color=col_3dt)\n\n# Plot signal/noise ratio\n\npar(mfrow=c(2,2))\n\nfor (i in 1:3){\n xc_prime <- Xct[idxt[i],]\n SN1 <- 10*log10(xc_prime^2 / diag(Sxt))\n barplot(SN1)\n}", "meta": {"hexsha": "f4df3902502ebc6de0ad9ffe4199e7a4055a1314", "size": 3672, "ext": "r", "lang": "R", "max_stars_repo_path": "roppongi_ds/anomaly_detection.r", "max_stars_repo_name": "KT12/Training", "max_stars_repo_head_hexsha": "ac4de382a1387ccfe51404eb3302cc518762a781", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-17T04:44:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-17T04:44:53.000Z", "max_issues_repo_path": "roppongi_ds/anomaly_detection.r", "max_issues_repo_name": "KT12/training", "max_issues_repo_head_hexsha": "ac4de382a1387ccfe51404eb3302cc518762a781", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "roppongi_ds/anomaly_detection.r", "max_forks_repo_name": "KT12/training", "max_forks_repo_head_hexsha": "ac4de382a1387ccfe51404eb3302cc518762a781", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1506849315, "max_line_length": 270, "alphanum_fraction": 0.635620915, "num_tokens": 1544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7329929523814656}} {"text": "#' Probability of path choices using probit model.\r\n#'\r\n#' This function calculates probabilities for selection of each path on the network based on set of path disutilities (costs). The function uses a probit random utility model. Calculations are exact for two route networks. In other case the probabilities are approximated by simulation.\r\n#' @param u Vector of utlities on each path\r\n#' @param ODpair Vector indicating the OD pair serviced by each route.\r\n#' @param A Path-link incidence matrix\r\n#' @param theta Vector of standard deviations for link cost errors. Defaults to 1 in each case.\r\n#' @param Niter Number of iterations when computing probabilities by simulation. Defaults to 1000.\r\n#' @return Vector of route choice probabilities\r\n#' @keywords path route probability\r\n#' @examples\r\n#' A <- diag(2)\r\n#' ODpair <- c(1,1)\r\n#' u <- c(15,17)\r\n#' LogitPathProb(u,ODpair,A,theta=1)\r\n#' @export\r\n\r\nProbitPathProb <- function(u,ODpair,A,theta,Niter=1000){\r\n\texact <- is.matrix(A) && dim(A) == 2 && all(A == diag(2))\r\n\tif (exact){\r\n\t\tp <- pnorm(-u[1]+u[2],sd=theta*sqrt(2))\r\n\t\tp <- c(p,1-p)\r\n\t}\r\n\tif (!exact){\r\n\t\tn.paths <- ncol(A)\r\n\t\tlink.errors <- matrix(rnorm(Niter*nrow(A),mean=0,sd=theta),nrow=nrow(A))\r\n\t\tpath.errors <- t(A)%*%link.errors\r\n\t\tpath.u <- u + path.errors\r\n\t\tp <- numeric(n.paths)\r\n\t\tfor (i in unique(ODpair)){\r\n\t\t\tworking.u <- path.u[ODpair==i,]\r\n\t\t\tworking.u <- cbind(working.u,diag(nrow(working.u))) # Add artifical utilities to ensure every route included in tabulation of results\r\n\t\t\tp[ODpair==i] <- table(apply(working.u,2,which.min)) - rep(1,nrow(working.u)) # Includes removal of results from artificial utilities\t\t\r\n\t\t}\r\n\t\tp <- p/Niter\r\n\t}\r\n\tp\r\n}\r\n", "meta": {"hexsha": "2618e3c18421d2dd8b0b41f52d6fea1aac476f57", "size": 1682, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ProbitPathProb.r", "max_stars_repo_name": "MartinLHazelton/transportation", "max_stars_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ProbitPathProb.r", "max_issues_repo_name": "MartinLHazelton/transportation", "max_issues_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ProbitPathProb.r", "max_forks_repo_name": "MartinLHazelton/transportation", "max_forks_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1282051282, "max_line_length": 287, "alphanum_fraction": 0.6837098692, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7329423726440016}} {"text": "# ......................................................................................\n# ........................Exercise 12. Tests for multiple samples.......................\n# ..................Michal Béreš, Martina Litschmannová, Adéla Vrtková..................\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# * Test data for a function call example ####\n# \n\n\n# I will create some data from the normal distribution with same variances\na = as.data.frame(rnorm(n = 35, mean = 100, sd = 10))\nb = as.data.frame(rnorm(n = 30, mean = 108, sd = 10))\nc = as.data.frame(rnorm(n = 40, mean = 104, sd = 10))\nd = as.data.frame(rnorm(n = 32, mean = 112, sd = 10))\n\n# I will rename the column name\ncolnames(a) = c(\"value\")\ncolnames(b) = c(\"value\")\ncolnames(c) = c(\"value\")\ncolnames(d) = c(\"value\")\n\n# I will add a type for all frame data\na$type = \"group1\"\nb$type = \"group2\"\nc$type = \"group3\"\nd$type = \"group4\"\n\n# I glue the lines together\ndata = rbind(a,b,c,d)\n\n# Convert type to type factor (needed for some tests)\ndata$type = as.factor(data$type)\n\nhead(data)\n\nboxplot(data$value ~ data$type)\n# if there are any outliars, I will ignore them\n# I know the data is from a normal distribution!\n# I also know they have the same variance sd = 10\n\n# Overview of tests and their functions ####\n# \n# * Comparing the measures of Variability (variances) ####\n\n\n# ** Bartlett test ####\n# - verifies the equality of variances \n# - $H_0: \\sigma^2_1 = \\sigma^2_2 = \\sigma^2_3 = \\ldots$\n# - $H_A: \\neg H_0$\n# - the assumtion data normality(and of course independence and continuity)\n\n\nbartlett.test(data$value ~ data$type)\n\n# ** Levene's test ####\n# - verifies the equality of variances \n# - $H_0: \\sigma^2_1 = \\sigma^2_2 = \\sigma^2_3 = \\ldots$\n# - $H_A: \\neg H_0$\n# - only independence and continuity are required\n\n\ncar::leveneTest(data$value ~ data$type)\n\n# ** Cochran's and Hartley's test ####\n# - verifies the equality of variances \n# - require data normality and so-called balanced sorting\n# - balanced sorting means that we have approximately the same amount of data in\n# each group\n# - we will not use them\n\n\n# * Comparing the measures of Position (means or medians) ####\n# \n# ** ANOVA(analysis of variance) ####\n# - test the equality of mean values \n# - $H_0: \\mu_1 = \\mu_2 = \\mu_3 = \\ldots$\n# - $H_A: \\neg H_0$\n# - prerequisites:\n# - normality dat\n# - homoskedasticity(identical variances)\n# - (and of course independence and continuity)\n# - if we reject $H_0$ Post-Hoc analysis is required\n# - using TukeyHSD test\n# - we want the result in the form of letter scheme and effects\n\n\n# ANOVA\n# H0: mu1=mu2=mu3=mu4\n# HA:~H0(H0 negation)\n\nres = aov(data$value~ data$type)\nsummary(res)\n\n# Post-Hoc analysis\n\nTukeyHSD(res)\n\n# effect computation\nlibrary(dplyr)\n\n# overall average\nmean_overall = mean(data$value)\nmean_overall\n\n# averages in groups\neffects = data %>% group_by(type) %>% \n summarize(mean_group = mean(value))\n\n# effects\neffects$effect = effects$mean_group - mean_overall\n\n# list them sorted\neffects %>% arrange(desc(effect))\n\n# letter scheme, library rcompanion\n\n# install.packages(\"rcompanion\")\nposthoc = TukeyHSD(res)\n\n# how to get the matrix of values out of the result\nmatrix_posthoc = posthoc[[1]]\nmatrix_posthoc\n# now we make a dataframe with columns of pairs and pvalues\nposthoc_DF = data.frame(pairs = rownames(matrix_posthoc), \n pval = matrix_posthoc[,'p adj'])\nposthoc_DF\n\nrcompanion::cldList(pval ~ pairs, \n data = posthoc_DF,\n threshold = 0.05)\n\n# ** Kruskal - Wallis test ####\n# \n# - verifiesthe equality of medians\n# - $H_0: X_{0.5,1} = X_{0.5,2} = X_{0.5,3} = \\ldots$\n# - $H_A: \\neg H_0$\n# - prerequisites:\n# - data symmetry\n# - (and of course independence and continuity)\n# - if we reject $H_0$ Post-Hoc analysis is required\n# - using the Dunn test\n# - method = \"bonferroni\" \n# - we want the result in the form of letter scheme and effects\n\n\n# KW test\n# H0: X0.5,1=X0.5,2=X0.5,3=X0.5,4\n# HA:~H0(H0 negation)\n\nkruskal.test(data$value ~ data$type)\n\n# Post-Hoc analysis\n\n# install.packages(\"FSA\")\nFSA::dunnTest(data$value ~ data$type, # FSA library\n method=\"bonferroni\")\n\n# effects\n\n# overall median\nmedian_overall = median(data$value)\nmedian_overall\n\n# medians in groups\neffects = data %>% group_by(type) %>% \n summarize(median_group = median(value))\n\n# effects\neffects$effect = effects$median_group - median_overall\n\n# list them sorted\neffects %>% arrange(desc(effect))\n\n# letter scheme, library rcompanion\n\n# install.packages(\"rcompanion\")\nposthoc = FSA::dunnTest(data$value ~ data$type, # FSA library\n method=\"bonferroni\")\n\n# how to get the matrix of values out of the result\nposthoc_DF = posthoc$res\nposthoc_DF\n# its in the data frame form already\n\nrcompanion::cldList(P.adj ~ Comparison, \n data = posthoc_DF,\n threshold = 0.05)\n\n# Examples ####\n\n\n# * Example 1. ####\n# \n# 122 patients who underwent heart surgery were randomly divided into three groups \n# - **Group 1:** Patients received 50% nitrous oxide and 50% oxygen mixed continuously\n# for 24 hours.\n# - **Group 2:** Patients received 50% nitric oxide and 50% oxygen only during surgery.\n# - **Group 3:** Patients received no nitrous oxide but received 35-50% oxygen for 24\n# hours.\n# \n# The data in the sheet 1 of testy_vicevyberove.xlsx file correspond to the folic acid\n# salt concentrations in the red blood cells in all three groups 24 hours after the\n# surgery. Verify that the observed differences between the folic acid salt\n# concentrations are statistically significant, i.e. that there is an effect of the\n# composition of the mixture on the monitored parameter.\n\n\nacid = readxl::read_excel(\"data/testy_vicevyberove.xlsx\", sheet=1)\ncolnames(acid) = c(\"Group 1\",\"Group 2\",\"Group 3\") # rename columns\nhead(acid)\n\n# conversion to standard data format\nacid.s = stack(acid)\ncolnames(acid.s) = c(\"values\",\"group\")\nacid.s = na.omit(acid.s)\nhead(acid.s)\n\nboxplot(acid.s$values ~ acid.s$group, xlab = \"Test groups\", ylab = \"Folic acid salt concentration\")\n# Data do not contain any outliars\n\n# we test the normality using S-W. test\n\nacid.s %>% group_by(group) %>% \n summarise(pval_SW = shapiro.test(values)$p.value)\n\n# Information needed to set rounding\n\nacid.s %>% group_by(group) %>% \n summarise(len = length(values), st.dev = sd(values))\n\n# sd is rounded to 3 valid digits\n# sd and position measures are rounded to tenths\n\n\n# equality of variance\ns2 = acid.s %>% group_by(group) %>% \n summarise(var = sd(values)^2)\ns2 # sampling variances\n\nmax(s2$var)/min(s2$var)\n# According to the box chart and information on the ratio of the largest and smallest\n# variances(<2) we do not assume that the variances differ statistically significantly\n\n# The assumption of normality was not rejected -> Bartlett's test\n\nbartlett.test(acid.s$values ~ acid.s$group)\n\n# At the significance level of 0.05, there are no statistically significant differences in variances\n\n# We want to compare the mean values of independent samples from normal distributions\n# with same variances -> ANOVA\n# The aov() command requires data in the standard data format\n\nresults = aov(acid.s$values ~ acid.s$group) \nsummary(results) \n\n# At the significance level of 0.05, there are statistically significant differences in mean values\n\n# post-hoc analysis\nTukeyHSD(results)\n\n# effect computation\n\n# overall average\nmean_overall = mean(acid.s$values)\nmean_overall\n\n# averages in groups\neffects = acid.s %>% group_by(group) %>% \n summarize(mean_group = mean(values))\n\n# effects\neffects$effect = effects$mean_group - mean_overall\n\n# list them sorted\neffects %>% arrange(desc(effect))\n\n# letter scheme, library rcompanion\n\n# make a dataframe with columns of pairs and pvalues\nmatrix_posthoc = TukeyHSD(results)[[1]]\nposthoc_DF = data.frame(pairs = rownames(matrix_posthoc), \n pval = matrix_posthoc[,'p adj'])\n# letter scheme\nrcompanion::cldList(pval ~ pairs, \n data = posthoc_DF,\n threshold = 0.05)\n\n# * Example 2. ####\n# \n# Three breeds of rabbits are bred on the farm. An experiment was performed on sheet 2\n# of testy_vicevyberove.xlsx, the aim of which was to find out whether, even if we keep\n# all the rabbits for the same time and under the same conditions (food, environment),\n# there is a statistically significant difference between breeds in rabbit weights.\n# Verify.\n\n\nrabbits = readxl::read_excel(\"data/testy_vicevyberove.xlsx\", sheet=2)\ncolnames(rabbits) = c(\"Vienna\",\"Czech\",\"Kalif\") # rename columns\nhead(rabbits)\n\n# conversion to standard data format\nrabbits.s = stack(rabbits)\ncolnames(rabbits.s) = c(\"value\",\"group\")\nrabbits.s = na.omit(rabbits.s)\nhead(rabbits.s)\n\nboxplot(rabbits.s$value ~ rabbits.s$group)\n# data contains an outliar\n\n# Eliminate outliar\n\nrabbits.s$id = seq(1,length(rabbits.s$value))\n\noutliars = rabbits.s %>% group_by(group) %>% rstatix::identify_outliers(value)\noutliars\n\nrabbits.s$value_cleared = ifelse(rabbits.s$id %in% outliars$id, NA, rabbits.s$value)\n\n# Box chart\nboxplot(rabbits.s$value_cleared ~ rabbits.s$group)\n\nlibrary(dplyr)\n\nrabbits.s %>% group_by(group) %>% \n summarise(norm.pval = shapiro.test(value_cleared)$p.value)\n\n# At the significance level of 0.05, we do not reject the assumption of normality.\n\n# Information needed for correct rounding\nrabbits.s %>% group_by(group) %>%\n summarize(len = sum(!is.nan(value_cleared)), \n sd = sd(value_cleared, na.rm = TRUE))\n\n# sd is rounded to 2 valid digits\n# sd and position measurements round to hundredths\n\n# The assumption of normality was not rejected ->Bartlett's test\nbartlett.test(rabbits.s$value_cleared ~ rabbits.s$group) \n\n# At the significance level of 0.05, the equality of variances cannot be rejected\n\n# We want to compare the mean values of independent samples from normal\n# distributions with the same variances -> ANOVA\n# The aov() command requires data in the standard data format\n\nresults = aov(rabbits.s$value_cleared ~ rabbits.s$group)\nsummary(results) \n\n# At the significance level of 0.05, we reject the hypothesis of equality of the mean values\n\n# post-hoc analysis\nTukeyHSD(results)\n\n# effect computation\n\n# overall average\nmean_overall = mean(rabbits.s$value_cleared, na.rm = TRUE)\nmean_overall\n\n# averages in groups\neffects = rabbits.s %>% group_by(group) %>% \n summarize(mean_group = mean(value_cleared, na.rm = TRUE))\n\n# effects\neffects$effect = effects$mean_group - mean_overall\n\n# list them sorted\neffects %>% arrange(desc(effect))\n\n# * Example 3. ####\n# \n# Four manufacturers A, B, C, D sent a total of 66 products to the competition for the\n# best product quality. The jury compiled the ranking (only the position of the product\n# in the list of 66 from best to worst), which is listed in the sheet 3 of the file\n# testy_vicevyberove.xlsx. On the basis of the above data, assess whether the origin of\n# the products affects its quality.\n\n\nquality = readxl::read_excel(\"data/testy_vicevyberove.xlsx\", sheet = 3)\ncolnames(quality) = c(\"ranking\", \"manufacturer\") # rename columns\nhead(quality)\n# data is already in standard format\n\nboxplot(quality$ranking ~ quality$manufacturer)\n\n# the data are not independent by nature, also they are not continuous!\n# outliars should not be present by the nature of the dataset\n# the assumptions are corrupted for all tests -> our best bet is the most robust test in our arsenal\n# we skip directly into KW test\n\n# Symmetry verification\n\nquality %>% group_by(manufacturer) %>% \n summarize(skewness = moments::skewness(ranking))\n\n# We want to compare the medians of \"independent\" samples -> Kruskal-Wallis test\nkruskal.test(quality$ranking ~ quality$manufacturer)\n\n# At the significance level of 0.05, there are no statistically significant differences in medians\n\n# * Example 4. ####\n# \n# The effect of three types of medicaments on blood clotting was studied (so called\n# thrombin time). Data of 42 monitored persons are recorded in the sheet 4 of the file\n# testy_vicevyberove.xlsx. Does the thrombin time depend on which preparation was used?\n\n\ntrombin.s = readxl::read_excel(\"data/testy_vicevyberove.xlsx\", \n sheet=4, skip = 1)\ncolnames(trombin.s) = c(\"value\",\"group\") # rename columns\n\nhead(trombin.s)\n# data is already in standard format\n\n\n# exploratory analysis\nboxplot(trombin.s$value ~ trombin.s$group)\n# no outliars\n\n# verification of normality\nlibrary(dplyr)\n\ntrombin.s %>% group_by(group) %>%\n summarize(norm.pval = shapiro.test(value)$p.value)\n\n# At the significance level of 0.05 we reject the assumption of normality(for A)\n\n# we can at least test the equality of variances -> same variances\n# means better KW test result in terms of type II error\n\n# The assumption of normality was rejected -> Levene's test\n\ncar::leveneTest(trombin.s$value ~ trombin.s$group) \n\n# the assumption of homoskedasticity was rejected (at significance 0.05)\n\n# Symmetry verification\ntrombin.s %>% group_by(group) %>% \n summarize(skewness = moments::skewness(value))\n# we do not reject the assumption of data symmetry\n\n# We want to compare medians (data not from normal dist.)-> Kruskal - Wallis test\n\nkruskal.test(trombin.s$value,trombin.s$group)\n\n# At the significance level of 0.05, we found statistically significant differences in medians\n\nFSA::dunnTest(trombin.s$value~trombin.s$group,method = \"bonferroni\") \n\n# effect counting\nlibrary(dplyr)\n\n# overall average\nmedian_overall = median(trombin.s$value)\nmedian_overall\n\n# averages in groups\neffects = trombin.s %>% group_by(group) %>% \n summarize(median_group = median(value))\n\n# effects\neffects$effect = effects$median_group - median_overall\n\n# List sorted\neffects %>% arrange(desc(effect))\n\n# * Example 5.(multiple groups) ####\n# \n# When Snow White got to the seven dwarves, she sensed an opportunity to make a lot of\n# money. The Dwarves basically fell in love with the Snow White and immediately handed\n# over all of their mined gold. However, even this is not enough for Snow White and she\n# feels that she could benefit more from the dwarves. Therefore, she began to record how\n# many kilograms of gold a day she received from each of the dwarves(snehurka.xlsx).\n# Verify that the dwarves differ in the amount of gold mined.\n\n\ngold = readxl::read_excel(\"data/snehurka.xlsx\")\ncolnames(gold) = c(\"ammount\",\"dwarf\")\nhead(gold)\n# data is in the standard data format\n\nboxplot(gold$ammount ~ gold$dwarf)\n# data does not outliars\n\n# verification of normality\nlibrary(dplyr)\n\ngold %>% group_by(dwarf) %>%\n summarize(p.val = shapiro.test(ammount)$p.value)\n\n# The assumption of normality was not rejected -> Bartlett's test\nbartlett.test(gold$ammount ~ gold$dwarf) \n\n# At the significance level of 0.05, there are no statistically significant differences in variances\n\n# ANOVA\nresults = aov(gold$ammount ~ gold$dwarf) \nsummary(results) \n\n# POST-HOC\nres = TukeyHSD(results)[[1]]\nres\n\n# effects computation\nlibrary(dplyr)\n\n# overall average\noverall = mean(gold$ammount)\noverall\n\n# averages in groups\neffects = gold %>% group_by(dwarf) %>% \n summarize(mean_dwarf = mean(ammount))\n\n# effects\neffects$effect = effects$mean_dwarf - overall\n\n# list sorted\neffects %>% arrange(desc(effect))\n\n# letter scheme, library rcompanion\n\n# make a dataframe with columns of pairs and pvalues\nmatrix_posthoc = TukeyHSD(results)[[1]]\nposthoc_DF = data.frame(pairs = rownames(matrix_posthoc), \n pval = matrix_posthoc[,'p adj'])\n# letter scheme\nrcompanion::cldList(pval ~ pairs, \n data = posthoc_DF,\n threshold = 0.05)\n\n\n\n", "meta": {"hexsha": "b255e6323d474f80e1e2b6af3da468a67a28005f", "size": 15783, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 12/T14_hypothesis_testing3.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise 12/T14_hypothesis_testing3.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise 12/T14_hypothesis_testing3.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 29.2820037106, "max_line_length": 100, "alphanum_fraction": 0.7060761579, "num_tokens": 4282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7328144775208455}} {"text": "#функция на разпределение на две случайни велични: F X,Y(x,y) = P(X<=x, Y<=y)\n#две случайни величини X, Y са независими, ако за всяко x,y e изпълнено: F X,Yx,y) = F X(x) * F Y(y) или P(X=x, Y=y) = P(X=x) * P(Y=y)\n#ковариация на две случайни величини: cov(X,Y) = E(XY) - EX*EY\n#корелация на две случайни величини: cor(X,Y) = cov(X,y)/sqrt(DX*DY)\n#ако X,Y са независими, то cor = 0, обратното не е вярно\n#ако корелацията клони към 1 или -1, значи X и Y са зависими\n#за графики: scatterplot и pairs\n#cor=1\nx=c(1:10)\ny=c(1:10)\ncor(x,y)\nplot(x,y)\n\n#cor=-1\nx=c(1:10)\ny=c(10:1)\ncor(x,y)\nplot(x,y)\nplot(y,x)\n\n#cor~0\nx=rnorm(100)\ny=rexp(100)\ncor(x,y)\nplot(x,y)\n\n#многомерно нормално разпределение\n#n-мерна случайна величина X = (X1,..,Xn) с нормално разпределение N(m,K), K=E((X - m)(X - m)transp) ковариационна матрица\ninstall.packages('mvtnorm')\nlibrary('mvtnorm')\nx=y=seq(-5,5, length=50)\nf=function(x,y)dmvnorm(cbind(x,y))\nz=outer(x,y,f)\npersp(x,y,z, theta=10, phi=20,expand=0.5, col=\"light blue\")\npersp(x,y,z, theta=10, phi=20,expand=0.5, col=\"light blue\", shade=0.75)\n\n\n\n#-----------------------------------------------------\n\n#01\nx=iris[,1:4]\ncor(x)\npairs(x)\n\n#02\n#Kz ковариация на X=(X1, X2, X2) -> по диагонала е DXi = E(Xi^2) - (EXi)^2\n#другите елементи на матрицата са ковариацията на елементите два по два\nKz = matrix(c(16, -14, 12, -14, 49, -21, 12, -21, 36), ncol = 3, byrow = TRUE)\ncor(Kz) #като че ли не го смята никак правилно\n#супер грозен начин за решаване, но май е по-верен? :)\n#не се прави така, нямам идея как се прави, но и не ни трябва да го знем за момента\ncov.X1.X2 = Kz[1,2] / sqrt(Kz[1,1]*Kz[2,2])\ncov.X1.X3 = Kz[1,3] / sqrt(Kz[1,1]*Kz[3,3])\ncov.X2.X3 = Kz[2,3] / sqrt(Kz[2,2]*Kz[3,3])\ncov.X = matrix(c(1, cov.X1.X2, cov.X1.X3, cov.X1.X2, 1, cov.X2.X3, cov.X1.X3, cov.X2.X3, 1), ncol = 3, byrow = TRUE)\n", "meta": {"hexsha": "9df870aa275a9423a22bd326005330a864917f3a", "size": 1823, "ext": "r", "lang": "R", "max_stars_repo_path": "week9.r", "max_stars_repo_name": "StelaN/Statistics-R", "max_stars_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-17T10:22:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-17T10:22:32.000Z", "max_issues_repo_path": "week9.r", "max_issues_repo_name": "StelaN/Statistics-R", "max_issues_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week9.r", "max_forks_repo_name": "StelaN/Statistics-R", "max_forks_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-06T13:38:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-06T13:38:34.000Z", "avg_line_length": 31.9824561404, "max_line_length": 134, "alphanum_fraction": 0.6313768513, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347868191549, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.73278721741269}} {"text": "#' Quadratic form of a matrix and a vector\n#'\n#' We compute the quadratic form of a vector and a matrix in an efficient\n#' manner. Let `x` be a real vector of length `p`, and let `A` be\n#' a p x p real matrix. Then, we compute the quadratic form \\eqn{q = x' A x}.\n#'\n#' A naive way to compute the quadratic form is to explicitly write\n#' `t(x) \\%*\\% A \\%*\\% x`, but for large `p`, this operation is\n#' inefficient. We provide a more efficient method below.\n#'\n#' Note that we have adapted the code from:\n#' \\url{http://tolstoy.newcastle.edu.au/R/help/05/11/14989.html}\n#'\n#' @param A matrix of dimension p x p\n#' @param x vector of length p\n#' @return scalar value\nquadform <- function(A, x) {\n drop(crossprod(x, A %*% x))\n}\n\n#' Quadratic Form of the inverse of a matrix and a vector\n#'\n#' We compute the quadratic form of a vector and the inverse of a matrix in an\n#' efficient manner. Let `x` be a real vector of length `p`, and let\n#' `A` be a p x p nonsingular matrix. Then, we compute the quadratic form\n#' \\eqn{q = x' A^{-1} x}.\n#'\n#' A naive way to compute the quadratic form is to explicitly write\n#' `t(x) \\%*\\% solve(A) \\%*\\% x`, but for large `p`, this operation is\n#' inefficient. We provide a more efficient method below.\n#'\n#' Note that we have adapted the code from:\n#' \\url{http://tolstoy.newcastle.edu.au/R/help/05/11/14989.html}\n#'\n#' @param A matrix that is p x p and nonsingular\n#' @param x vector of length p\n#' @return scalar value\nquadform_inv <- function(A, x) {\n drop(crossprod(x, solve(A, x)))\n}\n\n#' Centers the observations in a matrix by their respective class sample means\n#'\n#' @inheritParams lda_diag\n#' @param y vector of class labels for each training observation\n#' @return matrix with observations centered by its corresponding class sample\n#' mean\ncenter_data <- function(x, y) {\n x <- pred_to_matrix(x)\n y <- outcome_to_factor(y)\n complete <- complete.cases(x) & complete.cases(y)\n x <- x[complete,,drop = FALSE]\n y <- y[complete]\n\n # Notice that the resulting centered data are sorted by class and do not\n # preserve the original ordering of the data.\n x_centered <- tapply(seq_along(y), y, function(i) {\n scale(x[i, ], center = TRUE, scale = FALSE)\n })\n x_centered <- do.call(rbind, x_centered)\n\n # Sorts the centered data to preserve the original ordering.\n orig_ordering <- do.call(c, tapply(seq_along(y), y, identity))\n x_centered[orig_ordering, ] <- x_centered\n x_centered\n}\n\n#' Computes the inverse of a symmetric, positive-definite matrix using the\n#' Cholesky decomposition\n#'\n#' This often faster than [solve()] for larger matrices.\n#' See, for example:\n#' \\url{http://blog.phytools.org/2012/12/faster-inversion-of-square-symmetric.html}\n#' and\n#' \\url{http://stats.stackexchange.com/questions/14951/efficient-calculation-of-matrix-inverse-in-r}.\n#'\n#' @export\n#' @param x symmetric, positive-definite matrix\n#' @return the inverse of `x`\nsolve_chol <- function(x) {\n chol2inv(chol(x))\n}\n\n#' Computes the log determinant of a matrix.\n#'\n#' @export\n#' @param x matrix\n#' @return log determinant of `x`\nlog_determinant <- function(x) {\n # The call to 'as.vector' removes the attributes returned by 'determinant'\n as.vector(determinant(x, logarithm=TRUE)$modulus)\n}\n\n#' Computes multivariate normal density with a diagonal covariance matrix\n#'\n#' Alternative to `mvtnorm::dmvnorm`\n#'\n#' @importFrom stats dnorm\n#' @param x matrix\n#' @param mean vector of means\n#' @param sigma vector containing diagonal covariance matrix\n#' @return multivariate normal density\ndmvnorm_diag <- function(x, mean, sigma) {\n exp(sum(dnorm(x, mean=mean, sd=sqrt(sigma), log=TRUE)))\n}\n\n#' Computes posterior probabilities via Bayes Theorem under normality\n#'\n#' @importFrom mvtnorm dmvnorm\n#'\n#' @param x matrix of observations\n#' @param means list of means for each class\n#' @param covs list of covariance matrices for each class\n#' @param priors list of prior probabilities for each class\n#' @return matrix of posterior probabilities for each observation\nposterior_probs <- function(x, means, covs, priors) {\n if (is.vector(x)) {\n x <- matrix(x, nrow=1)\n }\n x <- pred_to_matrix(x)\n\n posterior <- mapply(function(xbar_k, cov_k, prior_k) {\n if (is.vector(cov_k)) {\n post_k <- apply(x, 1, function(obs) {\n dmvnorm_diag(x=obs, mean=xbar_k, sigma=cov_k)\n })\n } else {\n post_k <- dmvnorm(x=x, mean=xbar_k, sigma=cov_k)\n }\n prior_k * post_k\n }, means, covs, priors)\n\n if (is.vector(posterior)) {\n posterior <- posterior / sum(posterior)\n } else {\n posterior <- posterior / rowSums(posterior)\n }\n\n posterior\n}\n\n\n\npred_to_matrix <- function(x) {\n if (is.vector(x)) {\n rlang::abort(\"'x' should be a matrix or data frame.\")\n }\n \n if (is.null(colnames(x))) {\n rlang::abort(\"'x' should have column names.\")\n }\n if (!is.matrix(x)) {\n x <- as.matrix(x)\n if (is.character(x)) {\n rlang::abort(\n paste(\n \"When the predictors data were converted to a matrix, the matrix was\",\n \"no longer numeric. Were there non-numeric columns in the original\",\n \"data?\"\n )\n )\n }\n }\n x\n}\n\noutcome_to_factor <- function(y) {\n if (is.numeric(y) | is.matrix(y) | is.data.frame(y)) {\n rlang::abort(\n paste(\n \"The outcome data should be a character or factor vector.\"\n )\n )\n }\n if (!is.factor(y)) {\n y <- as.factor(y)\n }\n y\n}\n\nformat_priors <- function(x) {\n priors <- vapply(x$est, function(x) x$prior, numeric(1))\n paste0(names(priors), \" (\", round(priors * 100, 2), \"%)\", collapse = \", \")\n}\n\nprint_basics <- function(x, ...) {\n cat(\"Sample Size:\", x$N, \"\\n\")\n cat(\"Number of Features:\", x$p, \"\\n\\n\")\n cat(\"Classes and Prior Probabilities:\\n \")\n cat(format_priors(x), \"\\n\")\n}\n\nno_form_env <- function(x) {\n attr(x, \".Environment\") <- rlang::base_env()\n x\n}\n\n\nnew_discrim_object <- function(x, cls) {\n class(x) <- cls\n has_terms <- any(names(x) == \".terms\")\n \n if (has_terms) {\n attr(x$.terms, \".Environment\") <- rlang::base_env()\n class(x) <- c(paste0(cls, \"_formula\"), cls)\n }\n x\n}\n\nprocess_newdata <- function(object, x) {\n if (is.null(colnames(x))) {\n rlang::abort(\"'newdata' should have column names.\")\n }\n has_terms <- any(names(object) == \".terms\")\n if (has_terms) {\n .terms <- object$.terms\n .terms <- stats::delete.response(.terms)\n x <- stats::model.frame(.terms, x, na.action = stats::na.pass) #, xlev = object$xlevels)\n x <- model.matrix(.terms, x)\n attr(x, \"contrasts\") <- NULL\n attr(x, \"assign\") <- NULL\n } \n x <- x[, object$col_names, drop = FALSE]\n as.matrix(x)\n \n}\n\nmin_index <- function(x) {\n if (any(is.na(x))) {\n NA_integer_\n } else {\n which.min(x)\n }\n}\n\nscore_to_class <- function(x, object) {\n if (is.vector(x)) {\n min_scores <- min_index(x)\n } else {\n min_scores <- apply(x, 2, min_index)\n }\n factor(object$groups[min_scores], levels = object$groups)\n}\n\n", "meta": {"hexsha": "ee6f11e59663a8ec289decada619c040aa19a227", "size": 6901, "ext": "r", "lang": "R", "max_stars_repo_path": "R/helper.r", "max_stars_repo_name": "topepo/sparsediscrim", "max_stars_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:13:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T21:44:00.000Z", "max_issues_repo_path": "R/helper.r", "max_issues_repo_name": "topepo/sparsediscrim", "max_issues_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-26T12:02:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:00:06.000Z", "max_forks_repo_path": "R/helper.r", "max_forks_repo_name": "topepo/sparsediscrim", "max_forks_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1673469388, "max_line_length": 101, "alphanum_fraction": 0.6535284741, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7327477879920586}} {"text": "hcf <- function(x, y) {\nwhile(y) {\ntemp = y\ny = x %% y\nx = temp\n}\nreturn(x)\n}", "meta": {"hexsha": "88d32671767bcc0b850acce7a4cb1b88b5c33043", "size": 77, "ext": "r", "lang": "R", "max_stars_repo_path": "program_to_find_GCD_using_euclidean_algorithm.r", "max_stars_repo_name": "MarcosFloresta/R_Examples", "max_stars_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "program_to_find_GCD_using_euclidean_algorithm.r", "max_issues_repo_name": "MarcosFloresta/R_Examples", "max_issues_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "program_to_find_GCD_using_euclidean_algorithm.r", "max_forks_repo_name": "MarcosFloresta/R_Examples", "max_forks_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 9.625, "max_line_length": 23, "alphanum_fraction": 0.5064935065, "num_tokens": 32, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7325538742926193}} {"text": "#' Stochastic User Equilibrium\r\n#'\r\n#' This function calculates stochastic user equilibrium (SUE) using the method of successive averages. Output is a list of SUE route flows x and corresponding path costs u.\r\n#' @param ODdemand Vector of origin-destination (OD) travel demands\r\n#' @param ODpair Vector indicating the OD pair serviced by each route (ordered by columns of the path-link incidence matrix, A).\r\n#' @param A Path-link incidence matrix\r\n#' @param Alpha Vector of free flow travel time parameters for each link\r\n#' @param Beta Vector of capacity parameters for each link\r\n#' @param pow Polynomial order of cost function for each link. Defaults to 4.\r\n#' @param RUM Choice of random utility model. Can be \"logit\" (the default) or \"probit\".\r\n#' @param x.ini Initialization route flows for SUE algorithm (optional). \r\n#' @param theta A dispersion parameter. For the logit model, a single value specifying the logit parameter. For the probit model, a vector of standard deviations for the individual link cost errors. Defaults to 1.\r\n#' @param tol Tolerance for convergence assessment (measured as route mean squared difference between current flow vector and the search direction). Defaults of 1e-4.\r\n#' @param verbose Should progress of algorithm be printed out? Defaults to FALSE.\r\n#' @return Output is a list of SUE route flows x and corresponding path costs u.\r\n#' @keywords SUE\r\n#' @examples\r\n#' A <- matrix(c(0,1,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,1),ncol=4,byrow=T) \r\n#' Alpha <- rep(10,7)\r\n#' Beta <- rep(50,7)\r\n#' pow <- rep(4,7)\r\n#' ODpair <- c(1,1,2,2)\r\n#' ODdemand <- c(50,50)\r\n#' theta <- 0.7\r\n#' SUE(ODdemand,ODpair,A=A,Alpha=Alpha,Beta=Beta,pow=pow,theta=theta,verbose=F)\r\n#' @export\r\n\r\nSUE <- function(ODdemand,ODpair,A,Alpha,Beta,pow=4,RUM=\"logit\",x.ini = NULL,theta=1,tol=1e-4,verbose=F){\r\n\tif (any(ODdemand<=0)){ stop(\"All OD demands must be strictly positive\") }\r\n \tODdemand.rep <- rep(ODdemand,unname(table(ODpair)))\r\n if(is.null(x.ini)) x.ini <- rep(ODdemand/unname(table(ODpair)), unname(table(ODpair)))\r\n x <- x.ini\r\n \tgap <- 1\r\n \titer <- 1\r\n \twhile(gap > tol){\r\n\t\tu <- PathCost(x=x,A=A,Alpha=Alpha,Beta=Beta,pow=pow)\r\n \t\ty <- PathProb(u=u,ODpair=ODpair,A=A,RUM=RUM,theta=theta)*ODdemand.rep\r\n \t\tgap <- sqrt(mean(((x-y)/ODdemand.rep)^2))\r\n \t\tif(verbose) cat(gap,\"\\n\")\r\n \t\tif(gap > tol){\r\n \t\tx <- x + (y-x)/iter\r\n \t\t\titer <- iter + 1\r\n\t\t} \r\n \t}\r\n\tlist(x=unname(x),u=u)\r\n}", "meta": {"hexsha": "61f9e21c8ce1d1336f5c47d0fb9ead4d00aea969", "size": 2456, "ext": "r", "lang": "R", "max_stars_repo_path": "R/SUE.r", "max_stars_repo_name": "MartinLHazelton/transportation", "max_stars_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/SUE.r", "max_issues_repo_name": "MartinLHazelton/transportation", "max_issues_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/SUE.r", "max_forks_repo_name": "MartinLHazelton/transportation", "max_forks_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.3913043478, "max_line_length": 214, "alphanum_fraction": 0.6799674267, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7324184160493957}} {"text": "# here is an ecample of how you would compute the sum for the first 20 integers\n20*(20+1)/2\n\n# however, we can define a variable to use the formula for other values of variable n\nn <- 20\nn*(n+1)/2\n\n# remember the '<-' is how you would assign values to an object \nn <- 25\nn*(n+1)/2\n\n# below is an example that would calculate the sum of the first 100 integers\nn <- 100\nn*(n+1)/2\n", "meta": {"hexsha": "9fb133ad82ecd54ceaaf408135f0ee0b41956822", "size": 378, "ext": "r", "lang": "R", "max_stars_repo_path": "Variables/Variables.r", "max_stars_repo_name": "Proff-Matth/R-Basics", "max_stars_repo_head_hexsha": "5055d8b2e4a52f8809f729f48f77f9481e606048", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-24T00:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-24T00:52:37.000Z", "max_issues_repo_path": "Variables/Variables.r", "max_issues_repo_name": "Proff-Matth/R-Basics", "max_issues_repo_head_hexsha": "5055d8b2e4a52f8809f729f48f77f9481e606048", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Variables/Variables.r", "max_forks_repo_name": "Proff-Matth/R-Basics", "max_forks_repo_head_hexsha": "5055d8b2e4a52f8809f729f48f77f9481e606048", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-24T15:19:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T22:27:40.000Z", "avg_line_length": 25.2, "max_line_length": 85, "alphanum_fraction": 0.6984126984, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7322711826703875}} {"text": "#Copyright (c) 2016 Riccardo Francescato\na <- c(15,31,47,54,60)\nb <- c(12,15,21,28,30)\ncat(paste(\"Mean of a= \",mean(a)))\ncat(paste(\"Mean of b= \",mean(b)))\ncat(paste(\"Variance of a= \",var(a)))\ncat(paste(\"Variance of b= \",var(b)))\ncat(paste(\"Covariance= \",cov(a, b)))\ncat(paste(\"Corr. coef.= \",cor(a, b)))", "meta": {"hexsha": "60514493b3a16e1af9bb296db86cfb6b0938f048", "size": 303, "ext": "r", "lang": "R", "max_stars_repo_path": "Correlation_coefficent.r", "max_stars_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_stars_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Correlation_coefficent.r", "max_issues_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_issues_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Correlation_coefficent.r", "max_forks_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_forks_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6666666667, "max_line_length": 40, "alphanum_fraction": 0.6171617162, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.732263585330774}} {"text": "## ----echo=FALSE---------------------------------------------------------------\nrequire(Hmisc)\nknitrSet('mle')\noptions(width=70)\n\n\n## ----loglik,echo=FALSE,cap='log likelihood functions for three one-sample binomial problems',bty='l'----\np <- seq(.01, .99, by=.001)\nloglike <- function(p, s, n) s*log(p)+(n-s)*log(1-p)\nscore <- function(p, s, n) s/p-(n-s)/(1-p)\ninfo <- function(p, s, n) n/p/(1-p)\ns <- c(50, 60, 12)\nn <- c(100, 100, 20)\nlt <- c(1, 3, 4)\ncl <- 0.7\nplot(1:2, 1:2, xlim=c(0,1), ylim=c(-150,-10), xlab=\"P\",\n ylab=\"Log Likelihood\", type=\"n\")\nlabl <- paste(\"s=\", s, \" n=\", n, sep=\"\")\nlegend(.125, -110, labl, lty=lt, bty=\"n\", cex=cl)\nq <- par()$usr\nfor(i in 1:3) {\n lines(p, loglike(p, s[i], n[i]), lty=lt[i])\n lines(c(.5, .5), c(q[3], loglike(.5, s[i], n[i])), lty=2)\n lines(c(q[1], .5), c(loglike(.5, s[i], n[i]), loglike(.5, s[i], n[i])), lty=2)\n pe <- s[i]/n[i]\n lines(c(pe, pe), c(q[3], loglike(pe, s[i], n[i])), lty=2)\n lines(c(q[1], pe), c(loglike(pe, s[i], n[i]), loglike(pe, s[i], n[i])), lty=2)\n}\n\n\n## ----score,echo=FALSE,cap='Score functions ($\\\\partial\\\\log L/\\\\partial P$)',bty='l'----\nplot(0, 0, xlim=c(0,1), ylim=c(-500,600), xlab=\"P\", ylab=\"Score\", type=\"n\")\nlegend(.05, -225, labl, lty=lt, bty=\"n\", cex=cl)\nfor(i in 1:3) {\n lines(p, score(p, s[i], n[i]), lty=lt[i])\n q <- par()$usr\n lines(c(.5, .5), c(q[3], score(.5, s[i], n[i])), lty=2)\n lines(c(q[1], .5), c(score(.5, s[i], n[i]), score(.5, s[i], n[i])), lty=2)\n pe <- s[i]/n[i]\n lines(c(pe, pe), c(q[3], score(pe, s[i], n[i])), lty=2)\n lines(c(q[1], pe), c(score(pe, s[i], n[i]), score(pe, s[i], n[i])), lty=2)\n}\n\n## ----information,echo=FALSE,cap='Information functions ($- \\\\partial^{2}\\\\log L/\\\\partial P^{2})$',bty='l'----\nplot(0, 0, xlim=c(0,1), ylim=c(80,1200), xlab=\"P\", ylab=\"Information\", type=\"n\")\nw <- c(1,3)\nlegend(.4, 1000, paste(\"n=\", n[w], sep=\"\"), lty=lt[w], bty=\"n\", cex=cl)\nfor(i in w) lines(p, info(p, s[i], n[i]), lty=lt[i])\n\n\n## ----results='asis'-----------------------------------------------------------\nrequire(rms)\noptions(prType='latex')\nn <- 200\nset.seed(15)\nx1 <- rnorm(n)\nlogit <- x1/2\ny <- ifelse(runif(n) <= plogis(logit), 1, 0)\ndd <- datadist(x1); options(datadist='dd')\nf <- lrm(y ~ pol(x1,2), x=TRUE, y=TRUE)\nf\nanova(f)\n\n\n## ----bootor,cap='Distribution of 1000 bootstrap x=1:5 log odds ratios',h=2,w=3----\n# Get 2-row design matrix for obtaining predicted values\n# for x = 1 and 5\nX <- cbind(Intercept=1,\n predict(f, data.frame(x1=c(1,5)), type='x'))\nXdif <- X[2,,drop=FALSE] - X[1,,drop=FALSE]\nXdif\nb <- bootcov(f, B=1000)\nboot.log.odds.ratio <- b$boot.Coef %*% t(Xdif)\nsd(boot.log.odds.ratio)\n# This is the same as from summary(b, x=c(1,5)) as summary\n# uses the bootstrap covariance matrix\nsummary(b, x1=c(1,5))[1, 'S.E.']\n# Compare this s.d. with one from information matrix\nsummary(f, x1=c(1,5))[1,'S.E.']\n# Compute percentiles of bootstrap odds ratio\nexp(quantile(boot.log.odds.ratio, c(.025, .975)))\n# Automatic:\nsummary(b, x1=c(1,5))[' Odds Ratio',]\nprint(contrast(b, list(x1=5), list(x1=1), fun=exp))\n# Figure (*\\ref{fig:mle-bootor}*)\nhist(boot.log.odds.ratio, nclass=100, xlab='log(OR)', main='')\n\n\n## ----bootvary,h=4,w=6.5,cache=TRUE,cap='Predicted log odds and confidence bands for seven types of confidence intervals. Seven categories are ordered top to bottom corresponding to order of lower confidence bands at \\\\texttt{x1=5}. Dotted lines are for Wald--type methods that yield symmetric confidence intervals and assume normality of point estimators.',scap='Seven types of confidence bands'----\nx1s <- seq(0, 5, length=100)\npwald <- Predict(f, x1=x1s)\npsand <- Predict(robcov(f), x1=x1s)\npbootcov <- Predict(b, x1=x1s, usebootcoef=FALSE)\npbootnp <- Predict(b, x1=x1s)\npbootbca <- Predict(b, x1=x1s, boot.type='bca')\npbootbas <- Predict(b, x1=x1s, boot.type='basic')\npsimult <- Predict(b, x1=x1s, conf.type='simultaneous')\nz <- rbind('Boot percentile' = pbootnp,\n 'Robust sandwich' = psand,\n 'Boot BCa' = pbootbca,\n 'Boot covariance+Wald'= pbootcov,\n Wald = pwald,\n 'Boot basic' = pbootbas,\n Simultaneous = psimult)\n\nz$class <- ifelse(z$.set. %in% c('Boot percentile','Boot bca',\n 'Boot basic'), 'Other', 'Wald')\nggplot(z, groups=c('.set.', 'class'),\n conf='line', ylim=c(-1, 9), legend.label=FALSE)\n\n\n## ----pmle,w=5,h=3.25,fig.align='right',cap='Penalized least squares estimates for an unnecessary five-knot restricted cubic spline function. In the left graph all parameters (except the intercept) are penalized. The effective d.f.\\\\ are $4, 3.21, 2.71, 2.30, 2.03, 1.82$, and $1.51$. In the right graph, only parameters associated with nonlinear functions of $X_{1}$ are penalized. The effective d.f.\\ are $4, 3.22, 2.73, 2.34, 2.11, 1.96$, and $1.68$.',scap='Penalized least squares estimates'----\nset.seed(191)\nx1 <- rnorm(100)\ny <- x1 + rnorm(100)\npens <- df <- aic <- c(0,.07,.5,2,6,15,60)\nall <- nl <- list()\n\nfor(penalize in 1:2) {\n for(i in 1:length(pens)) {\n f <- ols(y ~ rcs(x1,5), penalty=\n list(simple=if(penalize==1)pens[i] else 0, \n nonlinear=pens[i]))\n df[i] <- f$stats['d.f.']\n aic[i] <- AIC(f)\n nam <- paste(if(penalize == 1) 'all' else 'nl',\n ' penalty:', pens[i], sep='')\n nam <- as.character(pens[i])\n p <- Predict(f, x1=seq(-2.5, 2.5, length=100),\n conf.int=FALSE)\n if(penalize == 1) all[[nam]] <- p else nl[[nam]] <- p\n }\n print(rbind(df=df, aic=aic))\n}\nall <- do.call('rbind', all); all$type <- 'Penalize All'\nnl <- do.call('rbind', nl) ; nl$type <- 'Penalize Nonlinear'\nboth <- as.data.frame(rbind.data.frame(all, nl))\nboth$Penalty <- both$.set.\nggplot(both, aes(x=x1, y=yhat, color=Penalty)) + geom_line() +\n geom_abline(col=gray(.7)) + facet_grid(~ type)\n# Figure (*\\ref{fig:mle-pmle}*)\n\n", "meta": {"hexsha": "849c127a41cc5b23ad551f79954ebe3fb17c9b9c", "size": 5925, "ext": "r", "lang": "R", "max_stars_repo_path": "RMScode/9_maximum_likelihood.r", "max_stars_repo_name": "fabarrios/Regression", "max_stars_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-01T18:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T18:27:09.000Z", "max_issues_repo_path": "RMScode/9_maximum_likelihood.r", "max_issues_repo_name": "fabarrios/Regression", "max_issues_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-23T23:59:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T23:59:10.000Z", "max_forks_repo_path": "RMScode/9_maximum_likelihood.r", "max_forks_repo_name": "fabarrios/Regression", "max_forks_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-24T03:43:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T03:43:53.000Z", "avg_line_length": 41.4335664336, "max_line_length": 504, "alphanum_fraction": 0.576371308, "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970685907242, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7320683601331655}} {"text": "rref <- function(m) {\n pivot <- 1\n norow <- nrow(m)\n nocolumn <- ncol(m)\n for(r in 1:norow) {\n if ( nocolumn <= pivot ) break;\n i <- r\n while( m[i,pivot] == 0 ) {\n i <- i + 1\n if ( norow == i ) {\n i <- r\n pivot <- pivot + 1\n if ( nocolumn == pivot ) return(m)\n }\n }\n trow <- m[i, ]\n m[i, ] <- m[r, ]\n m[r, ] <- trow\n m[r, ] <- m[r, ] / m[r, pivot]\n for(i in 1:norow) {\n if ( i != r )\n m[i, ] <- m[i, ] - m[r, ] * m[i, pivot]\n }\n pivot <- pivot + 1\n }\n return(m)\n}\n\nm <- matrix(c(1, 2, -1, -4,\n 2, 3, -1, -11,\n -2, 0, -3, 22), 3, 4, byrow=TRUE)\nprint(m)\nprint(rref(m))\n", "meta": {"hexsha": "327927c078d1e519e5d20a52a73b88eb3ad98c8e", "size": 681, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Reduced-row-echelon-form/R/reduced-row-echelon-form.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Reduced-row-echelon-form/R/reduced-row-echelon-form.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Reduced-row-echelon-form/R/reduced-row-echelon-form.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 20.0294117647, "max_line_length": 47, "alphanum_fraction": 0.3788546256, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7320678577436495}} {"text": "library(\"plot3D\")\nlibrary(\"plotrix\")\nlibrary(\"scatterplot3d\")\nlibrary(\"animation\")\n\n################################################################################\n# 1\n################################################################################\n\nx <- seq(0, 10, by = 0.001)\nplot(x, dnorm(x, 5, 1), type = 'l')\ntitle(\"1-d Gaussian function\")\n\n################################################################################\n# 2\n################################################################################\n\nx <- seq(0, 10, 0.1)\ny <- x\nf <- function(x, y) {\n mean <- 5\n distanceToMean <- sqrt( (x - mean)^2 + (y - mean)^2 )\n return(dnorm(distanceToMean, 0, 1))\n}\nz <- outer(x, y, f)\npersp(x, y, z, theta = 30, phi = 30, col = \"lightblue\", ticktype = \"detailed\")\ntitle(\"2-d Gaussian function\")\n\n################################################################################\n# 3\n################################################################################\n\nx <- seq(1, 10, 0.001)\nhist(rnorm(x, 5, 1), breaks = 100)\n# title(\"1-d Gaussian random data histogram\")\n\n################################################################################\n# 4\n################################################################################\n\nacc <- matrix(0, 40, 40)\nx <- rnorm(10000, 5, 1)\ny <- rnorm(10000, 5, 1)\n\nplot(x, y)\ntitle(\"2-d Gaussian random data\")\n\nfor (i in 1:10000) {\n xi <- ceiling(x[i] * 4)\n yi <- ceiling(y[i] * 4)\n acc[xi, yi] <- acc[xi, yi] + 1\n}\nhist3D(z = acc, ticktype = \"detailed\",)\ntitle(\"2-d Gaussian random data histogram\")\n\n################################################################################\n# 5\n################################################################################\n\ntcol <- terrain.colors(12)\ncontour(acc, col = tcol, lty = \"solid\")\ntitle(\"2-d Gaussian random data contour\")\n\n################################################################################\n# 6\n################################################################################\n\nplot(NA, xlim=c(0,10), ylim=c(0,10), xlab=\"x\", ylab=\"y\")\nsegments(0, -1, 11, 10)\ntitle(\"x - y = 1\")\n\n################################################################################\n# 7\n################################################################################\n\nplot(NA, xlim=c(-2,2), ylim=c(-2,2), xlab=\"x\", ylab=\"y\")\ndraw.circle(0, 0, 1)\ntitle(\"x² + y² = 1\")\n\n################################################################################\n# 8\n################################################################################\n\nplot(NA, xlim=c(-2,2), ylim=c(-2,2), xlab=\"x\", ylab=\"y\")\ndraw.ellipse(0, 0, 1, 2)\ntitle(\"x² + y²/4 = 1\")\n\n################################################################################\n# 9\n################################################################################\n\nf <- function(x,y) x^2 - (y^2)/4 - 1\nx <- y <- seq(-10,10,length=100)\nz <- outer(x,y,f)\ncontour(\n x = x, y = x, z = z,\n levels = 0, las = 1, drawlabels = FALSE, lwd = 3,\n xlab = \"x\", ylab = \"y\"\n)\ntitle(\"x² - y²/4 = 1\")\n\n\n################################################################################\n# 10\n################################################################################\n\nx <- 1:100\ny <- x * 2\n\nplot(x, y)\ntitle(\"2x - y = 0\")\n\n################################################################################\n# 11\n################################################################################\n\nx <- seq(-2, 2, by = 0.04)\ny <- sqrt(4 - x ^ 2)\n\nplot(x, y,\n asp = 1, xlim = c(-2,2), ylim = c(-2,2),\n xlab = \"x\", ylab = \"y\")\npar(new = TRUE)\nplot(x, -y,\n asp = 1, xlim = c(-2,2), ylim = c(-2,2),\n xlab = \"x\", ylab = \"y\")\n\ntitle(\"x² + y² = 4\")\n\n################################################################################\n# 12\n################################################################################\n\nx <- seq(-2, 2, by = 0.04)\ny <- sqrt(1 - (x ^ 2) / 4)\n\nplot(x, y,\n asp = 1, xlim = c(-2,2), ylim = c(-2,2),\n xlab = \"x\", ylab = \"y\")\npar(new = TRUE)\nplot(x, -y,\n asp = 1, xlim = c(-2,2), ylim = c(-2,2),\n xlab = \"x\", ylab = \"y\")\n\ntitle(\"x²/4 + y² = 4\")\n\n################################################################################\n# 13\n################################################################################\n\nx <- seq(-1, 1, by = 0.02)\ny <- 1 / x\n\nplot(x, y)\ntitle(\"xy = 1\")\n\n################################################################################\n# 14\n################################################################################\n\ni <- 0:96\nr <- 6.5 * (104 - i) / 104\ntheta <- pi * i / 16\nx <- r * sin(theta)\ny <- r * cos(theta)\n\nplot(x, y,\n asp = 1, xlim = c(-8,8), ylim = c(-8,8),\n xlab = \"x\", ylab = \"y\", col = \"red\")\npar(new = TRUE)\nx <- - r * sin(theta)\ny <- - r * cos(theta)\nplot(x, y,\n asp = 1, xlim = c(-8,8), ylim = c(-8,8),\n xlab = \"x\", ylab = \"y\", col = \"blue\")\ntitle(\"2 spirals\")\n\n################################################################################\n# 15\n################################################################################\n\nx1 <- c(0, 0, 1, 0)\ny1 <- c(1, 0, 1, 1)\nz1 <- c(1, 1, 1, 0)\n\nx2 <- c(0, 1, 1, 1)\ny2 <- c(0, 0, 0, 1)\nz2 <- c(0, 0, 1, 0)\n\npoints1 <- cbind(x1, y1, z1)\npoints2 <- cbind(x2, y2, z2)\n\ngraph <- scatterplot3d(points1, color = \"blue\", type = \"p\",\n xlim = c(0, 1), ylim = c(0, 1), zlim = c(-0.1, 1.1),\n xlab = \"x\", ylab = \"y\", zlab = \"z\")\ngraph$points3d(points2, col = \"red\", type = \"p\")\ngraph$plane3d(c(0.4, 1, -0.5))\ntitle(\"hyperplane\")\n\n################################################################################\n# 16\n################################################################################\n\ni <- 1:1000\ntheta <- (pi * i) / 1000\nr <- rnorm(1000, 1, 0.1)\n\nx <- r * cos(theta)\ny <- r * sin(theta)\n\nplot(x, y,\n asp = 1, xlim = c(-2,3), ylim = c(-2,2),\n xlab = \"x\", ylab = \"y\", col = \"red\")\npar(new = TRUE)\nx <- r * cos(theta) + 1\ny <- - r * sin(theta)\nplot(x, y,\n asp = 1, xlim = c(-2,3), ylim = c(-2,2),\n xlab = \"x\", ylab = \"y\", col = \"blue\")\ntitle(\"2 moons\")\n\n################################################################################\n# 16\n################################################################################\n\nsaveGIF({\n for(i in 1:100){\n curve(sin(x), from = -5 + (i * 0.05), to = 5 + (i * 0.05), col = \"red\", ylab = \"\")\n curve(sin(x/2), from = -5 + (i * 0.05), to = 5 + (i * 0.05), add = TRUE, col = \"blue\", ylab = \"\")\n curve(sin(x/3), from = -5 + (i * 0.05), to = 5 + (i * 0.05), add = TRUE, col = \"green\", ylab = \"\")\n curve(sin(x/4), from = -5 + (i * 0.05), to = 5 + (i * 0.05), add = TRUE, col = \"cyan\", ylab = \"\")\n curve(sin(x/5), from = -5 + (i * 0.05), to = 5 + (i * 0.05), add = TRUE, col = \"orange\", ylab = \"\")\n legend(\"topright\", legend = c(\"sin(x)\", \"sin(x/2)\", \"sin(x/3)\", \"sin(x/4)\", \"sin(x/5)\"), fill = c(\"red\", \"blue\", \"green\", \"cyan\", \"orange\"), bty = \"n\")\n }\n}, interval = 0.1, ani.width = 550, ani.height = 350)\n", "meta": {"hexsha": "b35ca95578f356587757a269c2bac6ad0c6a4baa", "size": 6998, "ext": "r", "lang": "R", "max_stars_repo_path": "erste/main.r", "max_stars_repo_name": "banacorn/neuron", "max_stars_repo_head_hexsha": "e05367a976cb43c607198b5b93ed4d9222e76160", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "erste/main.r", "max_issues_repo_name": "banacorn/neuron", "max_issues_repo_head_hexsha": "e05367a976cb43c607198b5b93ed4d9222e76160", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "erste/main.r", "max_forks_repo_name": "banacorn/neuron", "max_forks_repo_head_hexsha": "e05367a976cb43c607198b5b93ed4d9222e76160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6525423729, "max_line_length": 155, "alphanum_fraction": 0.2956559017, "num_tokens": 1993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7320606147414245}} {"text": "###############################################################################\n#\n# library \n# \nlibrary(VGAM) # zeta function\nlibrary(R.matlab) # read matlab file just for test purpose\n#\n###############################################################################\n#\n# test zone \n#\n###############################################################################\nruntest <- function(){\n #read a matlab file\n #x generated by x = randht(10000,'xmin',15,'powerlaw',2.5) with matlab (continuous law)\n x<-readMat(file(\"x_2.5_15_10000.mat\",\"rb\"))$x[,1]\n #plfit matlab:alpha=2.4975,xmin=18.5752,D=0.0062\n plfit(x)\n #plfit R:alpha=2.497485,xmin=18.57524,D=0.006174977\n #x0 generated by x0 =floor(x) with matlab (big discrete approximation)\n x0<-readMat(file(\"x0_2.5_15_10000.mat\",\"rb\"))$x[,1]\n #plfit matlab:alpha=2.4700,xmin=15,D=0.0056\n plfit(x0)\n #plfit r:alpha=2.47,xmin=15,D=0.00564463\n\n \n}\n###############################################################################\n#\n# PLFIT fits a power-law distributional model to data.\n#\n# PLFIT(x) estimates x_min and alpha according to the goodness-of-fit\n# based method described in Clauset, Shalizi, Newman (2007). x is a\n# vector of observations of some quantity to which we wish to fit the\n# power-law distribution p(x) ~ x^-alpha for x >= xmin.\n# PLFIT automatically detects whether x is composed of real or integer\n# values, and applies the appropriate method. For discrete data, if\n# min(x) > 1000, PLFIT uses the continuous approximation, which is\n# a reliable in this regime.\n#\n# The fitting procedure works as follows:\n# 1) For each possible choice of x_min, we estimate alpha via the\n# method of maximum likelihood, and calculate the Kolmogorov-Smirnov\n# goodness-of-fit statistic D.\n# 2) We then select as our estimate of x_min, the value that gives the\n# minimum value D over all values of x_min.\n#\n# Note that this procedure gives no estimate of the uncertainty of the\n# fitted parameters, nor of the validity of the fit.\n#\n# Example:\n# x <- (1-runif(10000))^(-1/(2.5-1))\n# plfit(x)\n#\n#\n# Version 1.0 (2008 February)\n# Version 1.1 (2008 February)\n# - correction : division by zero if limit >= max(x) because the unique R function do no sort\n# and the matlab function do...\n# Version 1.1 (minor correction 2009 August)\n# - correction : lines 230 zdiff calcul was wrong when xmin=0 (thanks to Naoki Masuda)\n# - gpl version updated to v3.0 (asked by Felipe Ortega)\n# Version 1.2 (2011 August)\n# - correction for method \"limit\" thanks to David R. Pugh \n# xmins <- xmins[xmins<=limit] is now xmins <- xmins[xmins>=limit]\n# - \"fixed\" method added for xmins from David R. Pugh\n# - modifications by Alan Di Vittorio:\n# - correction : zdiff calculation was wrong when xmin==1\n# - the previous zdiff correction was incorrect\n# - correction : x has to have at least two unique values\n# - additional discrete x input test : discrete x cannot contain the value 0\n# - added option to truncate continuous xmin search when # of obs gets small\n#\n# Copyright (C) 2008,2011 Laurent Dubroca laurent.dubroca_at_gmail.com \n# (Stazione Zoologica Anton Dohrn, Napoli, Italy)\n# Distributed under GPL 3.0 \n# http://www.gnu.org/copyleft/gpl.html\n# PLFIT comes with ABSOLUTELY NO WARRANTY\n# Matlab to R translation based on the original code of Aaron Clauset (Santa Fe Institute)\n# Source: http://www.santafe.edu/~aaronc/powerlaws/\n#\n# Notes:\n#\n# 1. In order to implement the integer-based methods in Matlab, the numeric\n# maximization of the log-likelihood function was used. This requires\n# that we specify the range of scaling parameters considered. We set\n# this range to be seq(1.5,3.5,0.01) by default. This vector can be\n# set by the user like so,\n#\n# a <- plfit(x,\"range\",seq(1.001,5,0.001))\n#\n# 2. PLFIT can be told to limit the range of values considered as estimates\n# for xmin in two ways. First, it can be instructed to sample these\n# possible values like so,\n#\n# a <- plfit(x,\"sample\",100)\n#\n# which uses 100 uniformly distributed values on the sorted list of\n# unique values in the data set. Alternatively, it can simply omit all\n# candidates below a hard limit, like so\n#\n# a <- plfit(x,\"limit\",3.4)\n#\n# In the case of discrete data, it rounds the limit to the nearest\n# integer.\n#\n# Finally, if you wish to force the threshold parameter to take a specific value \n# (useful for bootstrapping), simply call plfit() like so\n# \n# a <- plfit(x,\"fixed\",3.5)\n#\n# 3. When the input sample size is small (e.g., < 100), the estimator is\n# known to be slightly biased (toward larger values of alpha). To\n# explicitly use an experimental finite-size correction, call PLFIT like\n# so\n#\n# a <- plfit(x,finite=TRUE)\n#\n# 4. For continuous data, PLFIT can return erroneously large estimates of \n# alpha when xmin is so large that the number of obs x >= xmin is very \n# small. To prevent this, we can truncate the search over xmin values \n# before the finite-size bias becomes significant by calling PLFIT as\n# \n# a = plfit(x,nosmall=TRUE);\n# \n# which skips values xmin with finite size bias > 0.1.\n#\n###############################################################################\nplfit<-function(x=rpareto(1000,10,2.5),method=\"limit\",value=c(),finite=FALSE,nowarn=FALSE,nosmall=FALSE){\n #init method value to NULL\t\n vec <- c() ; sampl <- c() ; limit <- c(); fixed <- c()\n###########################################################################################\n#\n# test and trap for bad input\n#\n switch(method, \n range = vec <- value,\n sample = sampl <- value,\n limit = limit <- value,\n fixed = fixed <- value,\n argok <- 0)\n \n if(exists(\"argok\")){stop(\"(plfit) Unrecognized method\")}\n\n if( !is.null(vec) && (!is.vector(vec) || min(vec)<=1 || length(vec)<=1) ){\n print(paste(\"(plfit) Error: ''range'' argument must contain a vector > 1; using default.\"))\n vec <- c()\n }\n if( !is.null(sampl) && ( !(sampl==floor(sampl)) || length(sampl)>1 || sampl<2 ) ){\n print(paste(\"(plfit) Error: ''sample'' argument must be a positive integer > 2; using default.\"))\n sample <- c()\n }\n if( !is.null(limit) && (length(limit)>1 || limit<1) ){\n print(paste(\"(plfit) Error: ''limit'' argument must be a positive >=1; using default.\"))\n limit <- c()\n }\n if( !is.null(fixed) && (length(fixed)>1 || fixed<=0) ){\n print(paste(\"(plfit) Error: ''fixed'' argument must be a positive >0; using default.\"))\n fixed <- c() \n } \n\n# select method (discrete or continuous) for fitting and test if x is a vector\n fdattype<-\"unknow\"\n if( is.vector(x,\"numeric\") ){ fdattype<-\"real\" }\n if( all(x==floor(x)) && is.vector(x) ){ fdattype<-\"integer\" }\n if( all(x==floor(x)) && min(x) > 1000 && length(x) > 100 ){ fdattype <- \"real\" }\n if( fdattype==\"unknow\" ){ stop(\"(plfit) Error: x must contain only reals or only integers.\") }\n\n#\n# end test and trap for bad input\n#\n###########################################################################################\n\n###########################################################################################\n#\n# estimate xmin and alpha in the continuous case\n#\n if( fdattype==\"real\" ){\n\n xmins <- sort(unique(x))\n xmins <- xmins[-length(xmins)]\n\n if( !is.null(limit) ){\n xmins <- xmins[xmins>=limit]\n } \n if( !is.null(fixed) ){\n xmins <- fixed\n }\n if( !is.null(sampl) ){ \n xmins <- xmins[unique(round(seq(1,length(xmins),length.out=sampl)))]\n }\n \n dat <- rep(0,length(xmins))\n z <- sort(x)\n \n for( xm in 1:length(xmins) ){\n xmin <- xmins[xm]\n z <- z[z>=xmin]\n n <- length(z)\n # estimate alpha using direct MLE\n a <- n/sum(log(z/xmin))\n # truncate search if nosmall is selected\n if( nosmall ){\n if((a-1)/sqrt(n) > 0.1){\n dat <- dat[1:(xm-1)]\n print(paste(\"(plfit) Warning : xmin search truncated beyond\",xmins[xm-1]))\n break\n }\n }\n # compute KS statistic\n cx <- c(0:(n-1))/n\n cf <- 1-(xmin/z)^a\n dat[xm] <- max(abs(cf-cx))\n }\n \n D <- min(dat)\n xmin <- xmins[min(which(dat<=D))]\n z <- x[x>=xmin]\n n <- length(z)\n alpha <- 1 + n/sum(log(z/xmin))\n\n if( finite ){\n alpha <- alpha*(n-1)/n+1/n # finite-size correction\n }\n if( n<50 && !finite && !nowarn){\n print(\"(plfit) Warning : finite-size bias may be present\")\n }\n\n }\n#\n# end continuous case\n#\n###########################################################################################\n\n###########################################################################################\n#\n# estimate xmin and alpha in the discrete case\n#\n if( fdattype==\"integer\" ){\n\n if( is.null(vec) ){ vec<-seq(1.5,3.5,.01) } # covers range of most practical scaling parameters\n zvec <- zeta(vec)\n\n xmins <- sort(unique(x))\n xmins <- xmins[-length(xmins)]\n\n if( !is.null(limit) ){\n limit <- round(limit)\n xmins <- xmins[xmins>=limit]\n } \n\n if( !is.null(fixed) ){\n xmins <- fixed\n }\n\n if( !is.null(sampl) ){ \n xmins <- xmins[unique(round(seq(1,length(xmins),length.out=sampl)))]\n }\n\n if( is.null(xmins) || length(xmins) < 2){\n stop(\"(plfit) error: x must contain at least two unique values.\")\n }\n\n if(length(which(xmins==0) > 0)){\n stop(\"(plfit) error: x must not contain the value 0.\")\n }\n\n xmax <- max(x)\n dat <- matrix(0,nrow=length(xmins),ncol=2)\n z <- x\n for( xm in 1:length(xmins) ){\n xmin <- xmins[xm]\n z <- z[z>=xmin]\n n <- length(z)\n # estimate alpha via direct maximization of likelihood function\n # vectorized version of numerical calculation\n # matlab: zdiff = sum( repmat((1:xmin-1)',1,length(vec)).^-repmat(vec,xmin-1,1) ,1);\n if(xmin==1){\n zdiff <- rep(0,length(vec))\n }else{\n zdiff <- apply(rep(t(1:(xmin-1)),length(vec))^-t(kronecker(t(array(1,xmin-1)),vec)),2,sum)\n }\n # matlab: L = -vec.*sum(log(z)) - n.*log(zvec - zdiff);\n L <- -vec*sum(log(z)) - n*log(zvec - zdiff);\n I <- which.max(L)\n # compute KS statistic\n fit <- cumsum((((xmin:xmax)^-vec[I])) / (zvec[I] - sum((1:(xmin-1))^-vec[I])))\n cdi <- cumsum(hist(z,c(min(z)-1,(xmin+.5):xmax,max(z)+1),plot=FALSE)$counts/n)\n dat[xm,] <- c(max(abs( fit - cdi )),vec[I])\n }\n D <- min(dat[,1])\n I <- which.min(dat[,1])\n xmin <- xmins[I]\n n <- sum(x>=xmin)\n alpha <- dat[I,2]\n\n if( finite ){\n alpha <- alpha*(n-1)/n+1/n # finite-size correction\n }\n if( n<50 && !finite && !nowarn){\n print(\"(plfit) Warning : finite-size bias may be present\")\n }\n\n }\n#\n# end discrete case\n#\n###########################################################################################\n\n# return xmin, alpha and D in a list\n return(list(xmin=xmin,alpha=alpha,D=D))\n}\n", "meta": {"hexsha": "da0f4e714eb0ecb70aa9afefb447166c322787f2", "size": 11102, "ext": "r", "lang": "R", "max_stars_repo_path": "R/powerlaw/plfit.r", "max_stars_repo_name": "lsaravia/MarineFoodWebsSmallWorld", "max_stars_repo_head_hexsha": "b045b92d97e624b8ad2a780d208b02a0309cfb27", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/powerlaw/plfit.r", "max_issues_repo_name": "lsaravia/MarineFoodWebsSmallWorld", "max_issues_repo_head_hexsha": "b045b92d97e624b8ad2a780d208b02a0309cfb27", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-12-01T15:29:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-30T13:05:54.000Z", "max_forks_repo_path": "R/powerlaw/plfit.r", "max_forks_repo_name": "lsaravia/MarineFoodWebsSmallWorld", "max_forks_repo_head_hexsha": "b045b92d97e624b8ad2a780d208b02a0309cfb27", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-20T21:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T17:05:54.000Z", "avg_line_length": 35.4696485623, "max_line_length": 105, "alphanum_fraction": 0.5604395604, "num_tokens": 3082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7320112234520653}} {"text": "function()\r\n{\r\n n=as.integer(readline(prompt = \"Enter any number\"))\r\n fact=1\r\n for(i in 1:n)\r\n {\r\n fact=fact*i\r\n }\r\n print(paste(\"Factorial is \",fact))\r\n} \r\nmulti<- function()\r\n{\r\n no=as.integer(readline(prompt = \"Enter no to print its multplicatio table \"))\r\n mult=1\r\n for(i in 1:10)\r\n {\r\n mult=no*i\r\n print(paste(no,\"X\",i,\"=\",mult))\r\n }\r\n}\r\nmulti()\r\n\r\nprimeno <- function()\r\n{\r\n flag=1\r\n num=as.integer(readline(prompt = \"Enter no to check prime\"))\r\n mult=1\r\n i=1\r\n temp=num-1\r\n for(i in 2:temp)\r\n {\r\n if(num%%i==0)\r\n {\r\n \r\n flag=0\r\n break\r\n }\r\n }\r\n ifelse(flag==0,\"no is not prime\",\"no is prime\")\r\n}\r\nprimeno()\r\n\r\n\r\nfibonacci<-function()\r\n{\r\n f1=0\r\n f2=1\r\n f3=0\r\n num=as.integer(readline(prompt = \"Enter a number\"))\r\n print(f1)\r\n print(f2)\r\n while(num>0) {\r\n f3=f1+f2\r\n print(f3)\r\n f1=f2\r\n f2=f3\r\n num=num-1\r\n }\r\n}\r\nfibonacci()\r\n\r\nSumOfN<-function()\r\n{\r\n n=as.integer(readline(prompt = \"Enter a number\"))\r\n i=1\r\n sum=0\r\n repeat\r\n {\r\n sum=sum+i\r\n i=i+1\r\n if(i>n)\r\n {\r\n break\r\n }\r\n }\r\n print(sum)\r\n}\r\nSumOfN()\r\n\r\nSumOfDigit<-function()\r\n{\r\n n=as.integer(readline(prompt = \"Enter a number\"))\r\n sum=0\r\n rem=0\r\n while(n>0)\r\n {\r\n rem=n%%10\r\n sum=sum+rem\r\n n=n%/%10\r\n \r\n }\r\n print(paste(\"Sum of digits is : \",sum))\r\n}\r\nSumOfDigit()\r\n\r\nPerfectNumber=function()\r\n{\r\n n=as.integer(readline(prompt = \"Enter a number\"))\r\n temp=n-1\r\n sum=0\r\n for(i in 1:temp)\r\n {\r\n if(n%%i==0)\r\n sum=sum+i\r\n }\r\n if(sum==n)\r\n print(\"No is perfect \")\r\n else\r\n print(\"No is not perfect\")\r\n}\r\nPerfectNumber()", "meta": {"hexsha": "dd2a093bb61d53c4e642adfdfb885281eb68d88d", "size": 1625, "ext": "r", "lang": "R", "max_stars_repo_path": "DifferentFunctions.r", "max_stars_repo_name": "ninadsumant/RProgramming", "max_stars_repo_head_hexsha": "62aaf73e33d8e65f0f17a89c358feecef973cd5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DifferentFunctions.r", "max_issues_repo_name": "ninadsumant/RProgramming", "max_issues_repo_head_hexsha": "62aaf73e33d8e65f0f17a89c358feecef973cd5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DifferentFunctions.r", "max_forks_repo_name": "ninadsumant/RProgramming", "max_forks_repo_head_hexsha": "62aaf73e33d8e65f0f17a89c358feecef973cd5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6396396396, "max_line_length": 80, "alphanum_fraction": 0.5212307692, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.731929765872758}} {"text": "kf = function(q) {\n (asin(2*q-1)+pi/2)/pi\n}\ndata = data.frame(q=x, k=kf(x), q2=x^2, q3=x^3, q4=x^4)\n\n### train on data in [0.03, 0.5], but we only use the polynomial for\n### data in [0.05, 0.5]\nlimit = 0.03\nm = lm(k~q+q2+q3+q4, data[data$q>limit,])\ndata$m = 0\ndata[data$q>limit,]$m = predict(m)\nm$coefficients\n\ndata$z = 2*data$q-1\ndata = cbind(data, data.frame(t2=cos(2*acos(data$z)), t3=cos(3*acos(data$z)),\n t4=cos(4*acos(data$z)),\n t5=cos(5*acos(data$z)),\n t6=cos(6*acos(data$z)),\n t7=cos(7*acos(data$z)),\n t8=cos(8*acos(data$z)),\n t9=cos(9*acos(data$z))\n))\nm.cheb = lm(k~z+t2+t3+t4+t5+t6+t7+t8+t9, data[data$q>limit,])\n\ndata$m.cheb = 0\ndata[data$q>limit,]$m.cheb = predict(m.cheb)\n\nplot(m-k~q, data[data$q>limit,], type='l')\nlines(m.cheb-k~q, data[data$q>0.05,], type='l', col='red')\n", "meta": {"hexsha": "520dca8d816db85843cdc9dcb73ab0fb806f62cf", "size": 809, "ext": "r", "lang": "R", "max_stars_repo_path": "approx.r", "max_stars_repo_name": "tdunning/t-digest-benchmark", "max_stars_repo_head_hexsha": "6e6f128577613785bddb4ab87fa1c2141bb159e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-01-05T09:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-27T19:32:20.000Z", "max_issues_repo_path": "approx.r", "max_issues_repo_name": "tdunning/t-digest-benchmark", "max_issues_repo_head_hexsha": "6e6f128577613785bddb4ab87fa1c2141bb159e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "approx.r", "max_forks_repo_name": "tdunning/t-digest-benchmark", "max_forks_repo_head_hexsha": "6e6f128577613785bddb4ab87fa1c2141bb159e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-06T23:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-06T23:46:39.000Z", "avg_line_length": 26.9666666667, "max_line_length": 77, "alphanum_fraction": 0.5945611867, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7317300679947502}} {"text": "## Dale W.R. Rosenthal, 2018\n## You are free to distribute and use this code so long as you attribute\n## it to me or cite the text.\n## The legal disclaimer in _A Quantitative Primer on Investments with R_\n## applies to this code. Use or distribution without these comment lines\n## is forbidden.\n\ny <- seq(0.5, 8.5, by=0.01) # range of yields\nd6m <- 1/(1+y/2/100) # 6-month discount factor\nc1 <- 4.5 # annual coupon\nb1 <- c1/2*(d6m+d6m^2+d6m^3+d6m^4) + 100*d6m^4 # 2Y bond\nb2 <- c1/(y/100)*(1-d6m^10) + 100*d6m^10 # 5Y bond\nb3 <- c1/(y/100)*(1-d6m^20) + 100*d6m^20 # 10Y bond\nb4 <- c1/(y/100)*(1-d6m^40) + 100*d6m^40 # 20Y bond\n\nplot(y,b4, type='l', xlim=c(1,8), lty=1, lwd=2, col=\"purple\")\nlines(y, b3, lty=2, lwd=2, col=\"magenta\")\nlines(y, b2, lty=3, lwd=2, col=\"red\")\nlines(y, b1, lty=4, lwd=2, col=\"orange\")\nabline(h=100, lty=1, lwd=1, col=\"gray\")\nlegend.text <- c(\"20Y\", \"10Y\", \"5Y\", \"2Y\")\nlegend(\"topright\", legend.text, lty=1:4, lwd=2, col=c(\"purple\",\"magenta\",\"red\",\"orange\"))\n", "meta": {"hexsha": "0f8b996fd1a215b7aff48ddbc0984f13a698efff", "size": 1012, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch11-yields-vs-prices.r", "max_stars_repo_name": "bmoretz/Quantitative-Investments", "max_stars_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-26T05:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T21:50:54.000Z", "max_issues_repo_path": "Quantitative Primer/samples/ch11-yields-vs-prices.r", "max_issues_repo_name": "bmoretz/Quantitative-Investments", "max_issues_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quantitative Primer/samples/ch11-yields-vs-prices.r", "max_forks_repo_name": "bmoretz/Quantitative-Investments", "max_forks_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-03T09:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:50:55.000Z", "avg_line_length": 44.0, "max_line_length": 89, "alphanum_fraction": 0.6195652174, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7317210383316496}} {"text": "## Dexter Barrows\n## dbarrows.github.io\n## McMaster University\n## 2016\n\nlibrary(deSolve)\nlibrary(rstan)\nlibrary(shinystan)\nlibrary(ggplot2)\nlibrary(RColorBrewer)\nlibrary(reshape2)\n\nSIR <- function(Time, State, Pars) {\n \n with(as.list(c(State, Pars)), {\n \n B <- R0*r/N\n BSI <- B*S*I\n rI <- r*I\n \n dS = -BSI\n dI = BSI - rI\n dR = rI\n \n return(list(c(dS, dI, dR)))\n \n })\n \n}\n\npars <- c(R0 <- 3.0, # average number of new infected individuals per infectious person\n r <- 0.1, # recovery rate\n N <- 500) # population size\n\nT <- 100\ny_ini <- c(S = 495, I = 5, R = 0)\ntimes <- seq(0, T, by = 1)\n\nodeout <- ode(y_ini, times, SIR, pars)\n\nset.seed(1001)\nsigma <- 10\ninfec_counts_raw <- odeout[,3] + rnorm(T+1, 0, sigma)\ninfec_counts <- ifelse(infec_counts_raw < 0, 0, infec_counts_raw)\n\ng <- qplot(0:T, odeout[,3], geom = \"line\", xlab = \"Time (weeks)\", ylab = \"Infection Count\") +\n\t\tgeom_point(aes(y = infec_counts)) +\n\t\ttheme_bw()\n\nprint(g)\nggsave(g, filename=\"dataplot.pdf\", height=4, width=6.5)\n\nsPw <- 7\ndatlen <- (T-1)*7 + 1\n\ndata <- matrix(data = -1, nrow = T+1, ncol = sPw)\ndata[,1] <- infec_counts\nstandata <- as.vector(t(data))[1:datlen]\n\nsir_data <- list( T = datlen, # simulation time\n y = standata, # infection count data\n N = 500, # population size\n h = 1/sPw ) # step size per day \n \nrstan_options(auto_write = TRUE)\noptions(mc.cores = parallel::detectCores())\nstan_options <- list( chains = 4, # number of chains\n iter = 2000, # iterations per chain\n warmup = 1000, # warmup interations\n thin = 2) # thinning number\nfit <- stan(file = \"d_sirode_euler.stan\",\n data = sir_data,\n chains = stan_options$chains,\n iter = stan_options$iter,\n warmup = stan_options$warmup,\n thin = stan_options$thin )\n\nexfit <- extract(fit, permuted = TRUE, inc_warmup = FALSE)\n\nR0points <- exfit$R0\nR0kernel <- qplot(R0points, geom = \"density\", xlab = expression(R[0]), ylab = \"frequency\") +\n\t\t\t\tgeom_vline(aes(xintercept=R0), linetype=\"dashed\", size=1, color=\"grey50\") +\n\t\t\t\ttheme_bw()\n\nprint(R0kernel)\nggsave(R0kernel, filename=\"kernelR0.pdf\", height=3, width=3.25)\n\nrpoints <- exfit$r\nrkernel <- qplot(rpoints, geom = \"density\", xlab = \"r\", ylab = \"frequency\") +\n\t\t\t\tgeom_vline(aes(xintercept=r), linetype=\"dashed\", size=1, color=\"grey50\") +\n\t\t\t\ttheme_bw()\n\nprint(rkernel)\nggsave(rkernel, filename=\"kernelr.pdf\", height=3, width=3.25)\n\nsigmapoints <- exfit$sigma\nsigmakernel <- qplot(sigmapoints, geom = \"density\", xlab = expression(sigma), ylab = \"frequency\") +\n\t\t\t\tgeom_vline(aes(xintercept=sigma), linetype=\"dashed\", size=1, color=\"grey50\") +\n\t\t\t\ttheme_bw()\n\nprint(sigmakernel)\nggsave(sigmakernel, filename=\"kernelsigma.pdf\", height=3, width=3.25)\n\ninfecpoints <- exfit$y0[,2]\ninfeckernel <- qplot(infecpoints, geom = \"density\", xlab = \"Initial Infected\", ylab = \"frequency\") +\n\t\t\t\tgeom_vline(aes(xintercept=y_ini[['I']]), linetype=\"dashed\", size=1, color=\"grey50\") +\n\t\t\t\ttheme_bw()\n\nprint(infeckernel)\nggsave(infeckernel, filename=\"kernelinfec.pdf\", height=3, width=3.25)\n\nexfit <- extract(fit, permuted = FALSE, inc_warmup = FALSE)\nplotdata <- melt(exfit[,,\"R0\"])\ntracefitR0 <- ggplot() +\n geom_line(data = plotdata,\n aes(x = iterations,\n y = value,\n color = factor(chains, labels = 1:stan_options$chains))) +\n labs(x = \"Sample\", y = expression(R[0]), color = \"Chain\") +\n scale_color_brewer(palette=\"Greys\") +\n theme_bw()\n\nprint(tracefitR0)\nggsave(tracefitR0, filename=\"traceplotR0.pdf\", height=4, width=6.5)\n\nexfit <- extract(fit, permuted = FALSE, inc_warmup = TRUE)\nplotdata <- melt(exfit[,,\"R0\"])\ntracefitR0 <- ggplot() +\n geom_line(data = plotdata,\n aes(x = iterations,\n y = value,\n color = factor(chains, labels = 1:stan_options$chains))) +\n labs(x = \"Sample\", y = expression(R[0]), color = \"Chain\") +\n scale_color_brewer(palette=\"Greys\") +\n theme_bw()\n\nprint(tracefitR0)\nggsave(tracefitR0, filename=\"traceplotR0_inc.pdf\", height=4, width=6.5)\n\nsso <- as.shinystan(fit)\nsso <- launch_shinystan(sso)", "meta": {"hexsha": "459ce9815d101cdfeba9b399fd400b21dc6d4cd6", "size": 4493, "ext": "r", "lang": "R", "max_stars_repo_path": "code/hmc/d_sir_stan.r", "max_stars_repo_name": "dbarrows/epidemic-forecasting", "max_stars_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/hmc/d_sir_stan.r", "max_issues_repo_name": "dbarrows/epidemic-forecasting", "max_issues_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/hmc/d_sir_stan.r", "max_forks_repo_name": "dbarrows/epidemic-forecasting", "max_forks_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.865248227, "max_line_length": 100, "alphanum_fraction": 0.5849098598, "num_tokens": 1376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7315222671334212}} {"text": "## See http://stats.stackexchange.com/questions/147733/equation-of-a-fitted-smooth-spline-and-its-analytical-derivative\n\n## This fits a natural spline (linear tail restricted) using the truncated\n## power basis. Default knots are not used; instead specify 4 knots.\nrequire(rms)\nx <- 1:11\ny <- c(0.2,0.40, 0.6, 0.75, 0.88, 0.99, 1.1, 1.15, 1.16, 1.16, 1.16 )\ndd <- datadist(x); options(datadist='dd')\n\nf <- ols(y ~ rcs(x, c(3, 5, 7, 9)))\nf\nanova(f)\nggplot(Predict(f)) + geom_point(aes(x=x, y=y), data=data.frame(x,y))\nFunction(f) ## if have latex installed can also use latex(f)\n\n## Function re-expresses the restricted cubic spline in simplest form\n\n## The first derivative is:\n\n## function(x) 0.174 - 3 * 0.00279 * pmax(x - 3, 0) ^ 2 + 3 * 0.0015 * pmax(x - 5, 0) ^ 2 + ...\n", "meta": {"hexsha": "bea2e559384b5645e2f9eaed4f9c670365200504", "size": 778, "ext": "r", "lang": "R", "max_stars_repo_path": "SilveR/R/library/rms/tests/rcs.r", "max_stars_repo_name": "robalexclark/SilveR-Dev", "max_stars_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-27T10:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:57:34.000Z", "max_issues_repo_path": "SilveR/R/library/rms/tests/rcs.r", "max_issues_repo_name": "robalexclark/SilveR-Dev", "max_issues_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-12-28T07:09:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:33:50.000Z", "max_forks_repo_path": "SilveR/R/library/rms/tests/rcs.r", "max_forks_repo_name": "robalexclark/SilveR-Dev", "max_forks_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-03-05T05:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T07:52:04.000Z", "avg_line_length": 37.0476190476, "max_line_length": 119, "alphanum_fraction": 0.6606683805, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7315222562670395}} {"text": "model_deterministic_simulateR <- function(init_obs, period_start, times, pars, fix_pars){\n ode_solveR <- function(stage_pars, fix_pars, old_values) {\n ## stage pars\n b = stage_pars[1]\n r = stage_pars[2]\n ## fixed pars\n alpha= fix_pars[1]\n beta_1 = fix_pars[2] \n delta_1 = fix_pars[3]\n lambda = fix_pars[4]\n mu = fix_pars[5]\n mu_c = fix_pars[6]\n De = fix_pars[7]\n Dr = fix_pars[8]\n N = fix_pars[9]\n ## old values\n S = old_values[1]\n E = old_values[2]\n U = old_values[3]\n P = old_values[4]\n RU = old_values[5]\n RR = old_values[6]\n DU = old_values[7]\n DR = old_values[8] \n ## new values\n \n S_new = S - 0.5* b * S * (P + alpha* U) / N + lambda * N - mu * S\n E_new = E + 0.5 * b * S * (P + alpha * U ) / N - E / De - mu * E\n U_new = U + (1 - r) * E / De - U / (beta_1 * Dr) - delta_1 * mu_c * U - mu * U\n P_new = P + r * E / De - P / Dr - mu_c * P - mu * P\n RU_new <- RU + U / (beta_1 * Dr) - mu * RU\n RR_new <- RR + P / Dr - mu * RR\n DU_new <- DU + delta_1 * mu_c * U\n DR_new <- DR + mu_c * P \n est_P_new_n <- E\n est_P_new_prob <- r/ De \n est_RD_new_n <- P\n est_RD_new_prob_R <- 1 / Dr \n est_RD_new_prob_D <- mu_c \n \n return(c(S_new, E_new, U_new, P_new,RU_new, RR_new, DU_new, DR_new, \n est_P_new_n, est_P_new_prob,\n est_RD_new_n, est_RD_new_prob_R, est_RD_new_prob_D))\n }\n n_period = length(period_start)\n ymat = matrix(0, length(times), length(init_obs) + 6)\n ymat[, 1] = times\n \n colnames(ymat) <- c(\"time\", names(init_obs), \"est_p_n\", \"est_p_prob\", \"est_RD_n\", \"est_RD_prob_R\", \"est_RD_prob_D\")\n \n which.period <- function(i, phase = period_start){ # function to determine which period i falls in\n sum(i >= phase)\n }\n \n for(i in 1:length(times)){\n stage_pars <- c(b = pars[which.period(i)], r = pars[n_period + which.period(i)])\n if(i == 1) {\n old_values <- init_obs\n } else {\n old_values <- ymat[i - 1, 2:9]\n }\n ymat[i, 2:14] <- ode_solveR(stage_pars = stage_pars, fix_pars = fix_pars, old_values = old_values)\n }\n return(ymat)\n}", "meta": {"hexsha": "e503a651738874ed7fcc77ec55073f64af14826d", "size": 2114, "ext": "r", "lang": "R", "max_stars_repo_path": "model/seir/model_deterministic_simulateR.r", "max_stars_repo_name": "umich-cphds/covid_india_wave2", "max_stars_repo_head_hexsha": "32124bf9d51908d007d409d9bcc160eaebd2c74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/seir/model_deterministic_simulateR.r", "max_issues_repo_name": "umich-cphds/covid_india_wave2", "max_issues_repo_head_hexsha": "32124bf9d51908d007d409d9bcc160eaebd2c74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/seir/model_deterministic_simulateR.r", "max_forks_repo_name": "umich-cphds/covid_india_wave2", "max_forks_repo_head_hexsha": "32124bf9d51908d007d409d9bcc160eaebd2c74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5230769231, "max_line_length": 117, "alphanum_fraction": 0.5747398297, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7314854886425544}} {"text": "\r\nweight <- function(euclidean.dist, sigma) {\r\n\treturn (exp(-euclidean.dist^2 / (2*sigma^2)))\r\n}\r\n\r\ndwnn <- function(knowledge.base, query, sigma=0.5) {\r\n\r\n\tclassId = ncol(knowledge.base)\r\n\r\n\teuclidean.dist = \r\n\t apply(knowledge.base, 1, function(row) { \r\n\t\t\tsqrt(sum((row[1:(classId-1)] - query)^2)) })\r\n\r\n \tw = weight(euclidean.dist, sigma)\r\n\tY = knowledge.base[,classId]\r\n\r\n\ty = sum(w * Y) / sum(w)\r\n\r\n\treturn (y)\r\n}\r\n\r\ndwnn.recursive <- function(dataset, time.delay, train.from=1, train.to=floor((nrow(dataset)*2)/3), sigma=0.5) {\r\n\r\n\toriginal.dataset = dataset\r\n\tncol = ncol(dataset)\r\n\r\n\tfor (to in (train.to+1):nrow(dataset)) {\r\n\t\tquery = as.numeric(dataset[(to-time.delay),2:ncol])\r\n\t\ty = dwnn(dataset[train.from:(to-1),], query, sigma)\r\n\t\tdataset[to,] = c(query, y)\r\n\t}\r\n\r\n\tret = list()\r\n\tret$original.dataset = original.dataset\r\n\tret$predicted.dataset = dataset\r\n\r\n\treturn (ret)\r\n}\r\n\r\nconcept.drift <- function(series, m, d, window.length=250, by=1) {\r\n\r\n\tdataset = embedd(series, m=m, d=d)\r\n\tdivergence = c() #rep(NA, floor(window.length/by))\r\n\r\n\tfor (window.start in seq(1, nrow(dataset)-2*window.length+1, by=by)) {\r\n\t\tcat(\"nrow: \", nrow(dataset), \" Window start \", window.start, \" predicting to \", (window.start+2*window.length-1),\"\\n\")\r\n\t\ttwo.windows = dataset[window.start:(window.start+2*window.length-1),]\r\n\t\tresult = dwnn.recursive(two.windows, time.delay=d, train.from=1, train.to=window.length)\r\n\t\tdivergence = c(divergence, sum((result$original.dataset[,m] - result$predicted.dataset[,m])^2))\r\n\t}\r\n\r\n\treturn (divergence)\r\n}\r\n\r\n#### TESTING ####\r\nrequire(tseriesChaos)\r\ntest.sin <- function(sigma=0.5) {\r\n\tseries = sin(2*pi*seq(0,9,len=1000))\r\n\tdataset = embedd(series, m=3, d=10)\r\n\tresult = dwnn.recursive(dataset, time.delay=10, sigma=sigma)\r\n\r\n\tplot(result$original.dataset[,3])\r\n\tlines(result$predicted.dataset[,3], col=2)\r\n}\r\n\r\n#### DATASETS ####\r\nexperiment1 <- function(sigma=0.2104335, m=3, d=10, window.length=250, by=1) {\r\n\r\n\tseries = c(sin(2*pi*seq(0,9,len=1000)), sin(3*pi*seq(0,9,len=1000)), 1.5*sin(3*pi*seq(0,9,len=1000)))\r\n\r\n\tdiv = concept.drift(series, m=m, d=d, window.length=window.length, by=by)\r\n\tdiv = c(rep(NA, floor(length(series)-length(div))/2), div, rep(NA, floor(length(series)-length(div))/2))\r\n\r\n\tpdf(\"experiment1.pdf\")\r\n\tpar(mfrow=c(2,1))\r\n\tplot(series, xlab=\"Time\", ylab=\"Observation values\", main=\"(a) Data stream\")\r\n\tplot(div, xlab=\"Time\", ylab=\"Squared-error values\", main=\"(b) Prediction error\")\r\n\tdev.off()\r\n\r\n\tret = list()\r\n\tret$series = series\r\n\tret$div = div\r\n\r\n\treturn (ret)\r\n}\r\n\r\nexperiment2 <- function(sigma=0.00483608, m=2, d=1, window.length=250, by=1) {\r\n\r\n\tseries = c()\r\n\tx = 0.5\r\n\tfor (r in seq(2.5,4,len=2000)) {\r\n\t\tseries = c(series, x)\r\n\t\tx = r*x*(1-x)\r\n\t}\r\n\r\n\tdiv = concept.drift(series, m=m, d=d, window.length=window.length, by=by)\r\n\tdiv = c(rep(NA, floor(length(series)-length(div))/2), div, rep(NA, floor(length(series)-length(div))/2))\r\n\r\n\tpdf(\"experiment2.pdf\")\r\n\tpar(mfrow=c(2,1))\r\n\tplot(series, xlab=\"Time\", ylab=\"Observation values\", main=\"(a) Data stream\")\r\n\tplot(div, xlab=\"Time\", ylab=\"Squared-error values\", main=\"(b) Prediction error\")\r\n\tdev.off()\r\n\r\n\tret = list()\r\n\tret$series = series\r\n\tret$div = div\r\n\r\n\treturn (ret)\r\n}\r\n\r\nexperiment3 <- function(sigma=12.35516, m=3, d=10, window.length=250, by=1) {\r\n\r\n\tseries = sunspot.month\r\n\tdiv = concept.drift(series, m=m, d=d, window.length=window.length, by=by)\r\n\tdiv = c(rep(NA, floor(length(series)-length(div))/2), div, rep(NA, floor(length(series)-length(div))/2))\r\n\r\n\tpdf(\"experiment3.pdf\")\r\n\tpar(mfrow=c(2,1))\r\n\tplot(series, xlab=\"Year\", ylab=\"Observation values\", main=\"(a) Data stream\")\r\n\tplot(div, xlab=\"Time\", ylab=\"Squared-error values\", main=\"(b) Prediction error\")\r\n\tdev.off()\r\n\r\n\tret = list()\r\n\tret$series = series\r\n\tret$div = div\r\n\r\n\treturn (ret)\r\n}\r\n\r\nexperiment4 <- function(sigma=49.92655, m=3, d=1, window.length=250, by=1) {\r\n\r\n\tdata = read.csv(\"SP500TR.csv\")\r\n\trange = 4000:7566\r\n\tdate = format(as.Date(data[range,1]), \"%m-%Y\")\r\n\tseries = data[range,6]\r\n\r\n\tdiv = concept.drift(series, m=m, d=d, window.length=window.length, by=by)\r\n\tdiv = c(rep(NA, floor(length(series)-length(div))/2), div, rep(NA, floor(length(series)-length(div))/2))\r\n\r\n\tpdf(\"experiment4.pdf\")\r\n\tpar(mfrow=c(2,1))\r\n\tseq = floor(seq(1, length(series), len = 8))\r\n\tplot(series, xlab=\"Month-Year\", ylab=\"Observation values\", main=\"(a) Data stream\", xaxt=\"n\")\r\n\taxis(1, at= seq, labels = date[seq])\r\n\tplot(div, xlab=\"Time\", ylab=\"Squared-error values\", main=\"(b) Prediction error\")\r\n\tdev.off()\r\n\r\n\tret = list()\r\n\tret$series = series\r\n\tret$div = div\r\n\r\n\treturn (ret)\r\n}\r\n\r\nexperiment5 <- function(sigma=0.1111036, m=3, d=1, window.length=250, by=1) {\r\n\r\n\t# http://berkeleyearth.lbl.gov/auto/Global/Land_and_Ocean_complete.txt\r\n\tdata = read.table(\"Land_and_Ocean_complete.txt\")\r\n\ttmpDate = data[,1:2]\r\n\tdate = 0\r\n\tfor (i in 1:nrow(tmpDate))\r\n\t date[i] = sprintf(\"%d-%d\", tmpDate[i, 2], tmpDate[i, 1])\r\n\tseries = data[,3]\r\n\r\n\tdiv = concept.drift(series, m=m, d=d, window.length=window.length, by=by)\r\n\tdiv = c(rep(NA, floor(length(series)-length(div))/2), div, rep(NA, floor(length(series)-length(div))/2))\r\n\r\n\tpdf(\"experiment5.pdf\")\r\n\tpar(mfrow=c(2,1))\r\n\tseq = floor(seq(1, length(series), len = 8))\r\n\tplot(series, xlab=\"Month-Year\", ylab=\"Observation values\", main=\"(a) Data stream\", xaxt=\"n\")\r\n axis(1, at=seq, labels = date[seq])\r\n\tplot(div, xlab=\"Time\", ylab=\"Squared-error values\", main=\"(b) Prediction error\")\r\n\tdev.off()\r\n\r\n\tret = list()\r\n\tret$series = series\r\n\tret$div = div\r\n\r\n\treturn (ret)\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "0450ef5d063cabc0e1fd15903dad5915b2644bbc", "size": 5532, "ext": "r", "lang": "R", "max_stars_repo_path": "fcdd.r", "max_stars_repo_name": "pagliosa/FCDD", "max_stars_repo_head_hexsha": "dc13ae3638137e2a4c9e9f77178feaf64cf39b17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-10T10:39:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T10:39:10.000Z", "max_issues_repo_path": "fcdd.r", "max_issues_repo_name": "pagliosa/FCDD", "max_issues_repo_head_hexsha": "dc13ae3638137e2a4c9e9f77178feaf64cf39b17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fcdd.r", "max_forks_repo_name": "pagliosa/FCDD", "max_forks_repo_head_hexsha": "dc13ae3638137e2a4c9e9f77178feaf64cf39b17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-21T13:47:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-21T13:47:40.000Z", "avg_line_length": 29.9027027027, "max_line_length": 121, "alphanum_fraction": 0.6375632683, "num_tokens": 1749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.7313437127199864}} {"text": "#probability theory: A concise course by Y.A. Rozanov\n\n#Chapter 1:\n\n#1\n1/factorial(4)\n\n#2\n# 1 cube with all sides painted cut into 1000 cubes. 10 * 10 * 10 = 1000, \n# so each of the three axixs(axes?) is cut into ten pieces\n# each cube can have 0,1,2,3 faces painted, \n# 6 cubes have 3 painted faces - 6 corners\n# 96 cubes have 2 painted faces - 3 axes * 8 cubes left on each edge after removing the corners * four sides of each face (faces are squares)\n# 384 cubes have 1 painted face - 6 sides * 8^2 cubes left on each side after removing cubes with > 1 side painted\n# 514 cubes have 0 painted faces - 1000 cubes - 384 - 96 - 6 (cubes with >=1 faces painted)\n96/1000\n\n#5\n#pr(hit)\na <- 0.8\nb <- 0.7\n#pr(neither a nor b hit)\na2 <- 1-a\nb2 <- 1-b\ncat(b2*a2)\n#ans\n1-(b2*a2)\n\n#7\n# 4 threes, 4 sevens, 4 aces\n# (a, b, c)\n\n# total number of ways to choose 3 cards\nN <- choose(52,3)\n# number of ways to chose three seven and ace\nn <- 4^3\n# N(a)/N\nn/N\n\n\n#14\nstirling <- function(n){\n\treturn(sqrt(2*pi*n) * ((n^n) / exp(n)))\n}\nchooseWIthStirling <- function(n, k) {\n\tnum <- stirling(n)\n\tden <- stirling(k) * stirling(n - k)\n\treturn(num/den)\n}\nchooseWIthStirling(26,13)^2 / chooseWIthStirling(52,26)\n\n\n# 15\nn <- 2^50\nN <- chooseWIthStirling(100,50)\nn/N\n\n", "meta": {"hexsha": "d5e33e0daa028f6b0e0698f4749ce5e61e895be6", "size": 1245, "ext": "r", "lang": "R", "max_stars_repo_path": "probabilityTheory_AConciseCourseProblemSets.r", "max_stars_repo_name": "DU-ds/MiscRScripts", "max_stars_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "probabilityTheory_AConciseCourseProblemSets.r", "max_issues_repo_name": "DU-ds/MiscRScripts", "max_issues_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "probabilityTheory_AConciseCourseProblemSets.r", "max_forks_repo_name": "DU-ds/MiscRScripts", "max_forks_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4655172414, "max_line_length": 141, "alphanum_fraction": 0.6634538153, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7312299058066104}} {"text": "library(rstudioapi)\nlibrary(CCA)\nlibrary(ggplot2)\nlibrary(readr)\nlibrary(knitr)\nthis.dir <- dirname(rstudioapi::getActiveDocumentContext()$path)\nsetwd(this.dir)\n\n################# 2 ################# \ntwo_markets <- read_delim(\"two-markets.DAT\", \" \", escape_double = FALSE, trim_ws = TRUE)\nBio = two_markets[,1:3]\nEnergy = two_markets[,4:5]\nccal<-cc(X=Bio,Y = Energy)\nmatcor(Bio,Energy)\nccal$cor \n#Test\nev <- (1 - ccal$cor^2)\nn <- dim(Bio)[1]\np <- length(Bio)\nq <- length(Energy)\nk <- min(p, q)\nm <- n - 3/2 - (p + q)/2\nw <- rev(cumprod(rev(ev)))\ndf = (p-1+1)*(q-1+1)\nt1stat = -log(w[1])*(m)\nt1critical = qchisq(1-0.05,df)\n\n\nm <- n - 3/2 - (p + q)/2\nt2stat = -log(w[2])*m\np = p-1;q=q-1\ndf = (p-1+1)*(q-1+1)\nt2critical = qchisq(1-0.05,df)\n\n\ncolnames(ccal$xcoef) <- paste0(\"U\", 1:2)\nkable(ccal$xcoef)\ncolnames(ccal$ycoef) <- paste0(\"V\", 1:2) \nkable(ccal$ycoef)\n\n\nrho_u_x2 <- ccal$scores$corr.Y.xscores\ncolnames(rho_u_x2) <- paste0(\"U\", 1:2) \nkable(rho_u_x2)\n\nrho_v_x1 <- ccal$scores$corr.X.yscores \ncolnames(rho_v_x1) <- paste0(\"V\", 1:2) \nkable(rho_v_x1)\n######### 3 ################\nx1 = c(12, 18)\nx2 = c(36, 24)\nsp = matrix(c(2.4,1.7,1.7,3.4), ncol=2)\nd = x1-x2\nn1 = 400\nn2 = 133\nT2 = d%*%solve((1/n1+1/n2)*sp)%*%d # 29455.07\np = 2\ncritical = ((n1+n2-2)*p/(n1+n2-p-1))*qf(1-0.05,2,n1+n2-p-1)\n\nl = t(x1-x2)%*%solve(sp)\nr = 0.5*t(x1-x2)%*%solve(sp)%*%(x1+x2)\nR = log((1/2)*(1/3))\nRR=R+r\n\nt(t(l))%*%c(18,24)>=RR\n\n############ 5 ##################\np = 4;n = 61\nd= as.matrix(c(0.6,-8.4,-0.1,-10.7))\nsd = as.matrix(rbind(c(5,0,1,0),c(0,2,-1,1),c(1,-1,4,1),c(0,1,1,4)))\nT2 =n*t(d)%*%solve(sd)%*%d\nqf(1-0.05, p, n-p)*(n-1)*p/(n-p)\n\ncv = qt(1-0.05/8, 60)\n#Drama\ns1 = sd[1,1]\nc(d[1]-cv*sqrt(s1/n),d[1]+cv*sqrt(s1/n))\n#Horror\ns2 = sd[2,2]\nc(d[2]-cv*sqrt(s2/n),d[2]+cv*sqrt(s2/n))\n#Action\ns3 = sd[3,3]\nc(d[3]-cv*sqrt(s3/n),d[3]+cv*sqrt(s3/n))\n#Comedy\ns4 = sd[4,4]\nc(d[4]-cv*sqrt(s4/n),d[4]+cv*sqrt(s4/n))\n", "meta": {"hexsha": "536b49a56fa532124a5e8c19a8c62eb413cd80d6", "size": 1898, "ext": "r", "lang": "R", "max_stars_repo_path": "Statistics/STA 135/Final.r", "max_stars_repo_name": "HaozheGuAsh/Undergrate", "max_stars_repo_head_hexsha": "2b75ef3ae06b6c2350edc4b0b03f516a194cca99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/STA 135/Final.r", "max_issues_repo_name": "HaozheGuAsh/Undergrate", "max_issues_repo_head_hexsha": "2b75ef3ae06b6c2350edc4b0b03f516a194cca99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/STA 135/Final.r", "max_forks_repo_name": "HaozheGuAsh/Undergrate", "max_forks_repo_head_hexsha": "2b75ef3ae06b6c2350edc4b0b03f516a194cca99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.816091954, "max_line_length": 88, "alphanum_fraction": 0.5569020021, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7312265860117093}} {"text": "# Cargar libreria forecast, fBasic, fArma, urca,\nlibrary(forecast)\nlibrary(fBasics) \nlibrary(car)\nlibrary(fArma) \nlibrary(urca) \n \n\n# Entrada de datos desde un archivo de texto\n(z=ts(scan(\"f:/udea/Economet2/ejemplo_1.txt\")))\n\n# ETAPA DE IDENTIFICACI?N\n# gr?fica de la serie\nplot.ts(z)\nplot.ts(z, type=\"o\")\n\n# An?lisis de estabilidad de la varianza: Es necesario usar la\n# transformaci?n Box-Cox?\n\n# An?lisis gr?fico\npar(mfrow=c(2,1))\nplot.ts(z)\nplot.ts(diff(z))\n\n# Estimaci?n de la transformaci?n usando la librer?a car \n(tBoxCox=powerTransform(z))\nsummary(tBoxCox)\n\n# transformaci?n usando ra?z cuarta\ntz=z^.25\n\n# gr?fica de la serie original y transformada con Lambda=.25\npar(mfrow=c(2,1))\nplot.ts(z, type=\"o\")\nplot.ts(z^.25, type=\"o\")\n \n# gr?fica de la serie diferenciada original y transformada\npar(mfrow=c(2,1))\nplot.ts(diff(z))\nplot.ts(diff(z^.25))\n\n# se sigue el proceso de identificaci?n usando z^.25\n# determinaci?n del valor de d\n# gr?fica de la serie transformada\nplot.ts(z^.25)\n# correlogramas muestrales de la serie transformada \npar(mfrow=c(2,1))\nAcf(z^.25, lag.max=30, ci=0,ylim=c(-1,1))\npacf(z^.25, lag.max=30, ci=0, ylim=c(-1,1))\n\n# La serie es no estacionaria: Qu? tipo de serie es TS o DS?\n# prueba de ra?ces unitarias usando la librer?a urca\n(maxlag=floor(12*(length(z)/100)^(1/4)))\nru_tz=ur.df(z^.25, type = c(\"trend\"), lags=maxlag, selectlags = c(\"BIC\"))\nsummary(ru_tz)\nru_tz=ur.df(z^.25, type = c(\"trend\"), lags=maxlag, selectlags = c(\"AIC\"))\nsummary(ru_tz)\n\n # validaci?n de la ecuaci?n ADF\n resid=ru_tz@testreg$residuals # residuales del modelo ADF\n plot(ru_tz)\n auto.arima(resid, max.p=5, max.q=5) # busqueda \"autom?tica\" \n cheq=Arima(resid, c(0,0,0), include.constant=TRUE) \n summary(cheq) \n tsdiag(cheq, gof.lag=15)\n # Verificacion de normalidad en los residuales\n qqnorm(resid, xlab = \"Cuantiles Te?ricos\", ylab = \"Cuantiles Muestrales\")\n qqline(resid)\n shapiro.test(resid) # prueba de Shapiro-Wilks\n jarqueberaTest(resid ) # prueba Jarque-Bera en libreria fBasics\n\n# el modelo ADF satisface los supuestos b?sicos\n#Conclusi?n: La serie z^.25 contiene al menos una ra?z unitaria.\n\n# Examen de m?s ra?ces unitarias\n# gr?fica de la serie diferenciada una vez\nplot.ts(diff(z^.25), type=\"l\")\n# prueba de si hay ra?z unitarias en z^.25 diferenciada una vez.\nru_dif_tz=ur.df(diff(z^.25), type = c(\"drift\"), lags=maxlag, selectlags = c(\"BIC\"))\nsummary(ru_dif_tz) \n# reespecificaci?n del modelo con lags=0\nru_dif_tz=ur.df(diff(z^.25), type = c(\"drift\"), lags=0)\nsummary(ru_dif_tz) # valide la ecuaci?n usada para la prueba\n#Conclusi?n: La serie z^.25 diferenciada no contiene r?iz unitaria.\n# Por tanto, la serie z^.25 pertenece a la clase de modelos ARIMA con deriva y d=1.\n\n# determinaci?n de los valores de (p, q) del modelos ARMA para (1-B)z^.25\n# correlogramas muestrales para z diferenciada una vez\npar(mfrow=c(2,1))\nAcf(diff(z^.25), lag.max=12, ci=0, ylim=c(-1,1))\npacf(diff(z^.25), lag.max=12, ci=0, ylim=c(-1,1))\n\n# correlogramas muestrales para z^.25 diferenciada una vez con bandas\npar(mfrow=c(2,1))\nAcf(diff(z^.25), lag.max=12, ci=0)\npacf(diff(z^.25), lag.max=12)\n\n# selecci?n \"autom?tica\" del modelo\nauto.arima(z^.25, d=1, max.p=5, max.q=5, ic=c(\"aic\"))\nauto.arima(z^.25, max.p=5, max.q=5, ic=c(\"bic\"))\n\n# Conclusi?n: modelo seleccionado es: (1-phi1*B)(1-B)z^.25=constante+at, \n# es decir, z^.25 sigue un modelo ARIMA(1,1,0) con deriva.\n# la tendencia observada en la gr?fica de z^.25 es una mezcla de tendencia aleatoria y detemin?stica lineal \n\n# ETAPA DE ESTIMACI?N\n# estimaci?n ML exacta con valores iniciales dados por la estimaci?n condicional\nmod1_CSS_ML=Arima(z, c(1, 1, 0), include.drift=TRUE, lambda=.25, method = c(\"CSS-ML\"))\nsummary(mod1_CSS_ML) \n(res1_CSS_ML=residuals(mod1_CSS_ML))\n\n# ETAPA DE DIAGN?STICOS\n# ra?ces de los polinomios\n# usando la librer?a fArma\ncoeficAR=c(coef(mod1_CSS_ML)[1])\n# vector con el coeficiente AR\narmaRoots(coeficAR) # obtiene las ra?ces \n# otra forma: usando librer?a forecast usando el inverso de las ra?ces del polinomio\nplot(mod1_CSS_ML)\n\n# An?lisis de los residuales\ntsdiag(mod1_CSS_ML)\n\n# chequeo de observaciones at?picas extremas (no es un an?lisis completo de outliers)\nres1_est=res1_CSS_ML/(mod1_CSS_ML$sigma2^.5) # estandarizaci?n de los residuales\nplot.ts(res1_est, type=\"o\")\nabline(a=-3, b=0)\nabline(a=3, b=0)\n\n# n?mero de observaciones esperadas fuera de los limites (-3, 3) bajo normalidad\n(Nobs_Esp=round(length(z)*2*pnorm(-3, mean = 0, sd = 1, lower.tail = TRUE)))\n\n# detecci?n de las observaciones at?picas\nind=(abs(res1_est)>3.0)\nsum(ind)\n(grupo=cbind(res1_est, ind))\n\n# chequeo de normalidad\n# gr?fico cuantil-cuantil\nqqnorm(res1_est, xlab = \"Cuantiles Te?ricos\", ylab = \"Cuantiles Muestrales\",\n xlim=c(-4,4), ylim=c(-4,4))\nqqline(res1_est)\n \n# histograma, densidad kernel y gr?fico normal\nplot(density(res1_est))\nmu<-mean(res1_est)\nsigm<-sd(res1_est)\nx<-seq(-4,4,length=100)\ny<-dnorm(x,mu,sigm)\nhist(res1_est,prob=T,ylim=c(0,.45),xlim=c(-4,4),col=\"yellow\")\nlines(density(res1_est))\nlines(x,y,lwd=2,col=\"blue\")\n# conclusi?n: No se detecta alejamiento fuerte de la normalidad\n\n# pruebas de normalidad\nshapiro.test(res1_est) # prueba de Shapiro-Wilks\nnormalTest(res1_est, method=(\"jb\")) # En la librer?a fBasics: puede realizar otras pruebas\n # \"ks\" for the Kolmogorov-Smirnov one?sample test, \n # \"sw\" for the Shapiro-Wilk test, \n # \"jb\" for the Jarque-Bera Test, \n # \"da\" for the D'Agostino Test. The default value is \"ks\"\n# conclusi?n: No se rechaza la normalidad.\n\n# valores ajustados del modelo para z transformada\nmod1_CSS_MLn=Arima(z^.25, c(1, 1, 0), include.drift=TRUE, method = c(\"CSS-ML\"))\nsummary(mod1_CSS_ML)n) \n(res1_CSS_MLn=residuals(mod1_CSS_MLn))\n\n(ajustn=z^.25-residuals(mod1_CSS_MLn)) \n# gr?fico para los valores ajustados y los valores observados\nts.plot(z^.25,ajustn) # gr?fico de las series contra el tiempo\nlines(z^.25, col=\"black\")\nlines(ajustn, col=\"red\")\n\nplot(as.vector(z^.25),as.vector(ajustn), type=\"p\") # gr?fico de dispersi?n de la serie observada \nabline(0,1) # contra la serie ajustada\n\n# detecci?n de observaciones at?picas\nind=(abs(res1_est)>3.0)\nsum(ind)\n(grupo=cbind(res1_est, ind))\n\n# n?mero de observaciones esperadas fuera del intervalo (-3, 3)\n(num_obs=length(z)*2*pnorm(-3.0, mean = 0, sd = 1, lower.tail = TRUE))\n\n# Evaluaci?n de Pron?sticos: se contruye el modelo usando 245 datos y se dejan\n# los ?ltimos 5 para evaluar la capacidad de pron?stico del modelo \n# estimaci?n ML exacta con valores iniciales dados por la estimaci?n condicional\nnum_pron=5\n(mod_Evalpron=Arima(z[1:(length(z)-num_pron)], c(1, 1, 0), include.drift=TRUE, lambda=.25, method = c(\"CSS-ML\")))\nsummary(mod_Evalpron) \n\n(z_pred<-forecast(mod_Evalpron, h=num_pron, lambda=mod1_CSS_ML$lambda, fan=TRUE))\nplot(forecast(z_pred))\n\n(z_pred<-forecast(mod_Evalpron, h=num_pron, level=c(95), lambda=mod1_CSS_ML$lambda))\nplot(forecast(z_pred))\n\n# EVALUACI?N DE LOS PRON?STICOS\n(real=ts(z[(length(z)-num_pron+1):length(z)]))\ncbind(real, ts(z_pred$mean))\n\n# gr?fico de reales, pron?sticos\nts.plot(real, ts(z_pred$mean),type=\"o\")\nlines(ts(z_pred$mean), col=\"red\")\n\n# gr?fico de reales, pron?sticos e intervalo de predicci?n\nts.plot(real, ts(z_pred$mean), ts(z_pred$lower), ts(z_pred$upper), type=\"o\")\nlines(ts(z_pred$mean), col=\"red\")\nlines(ts(z_pred$lower), col=\"blue\")\nlines(ts(z_pred$upper), col=\"blue\")\n\n# C?lculo de medidas de evaluaci?n de los pron?sticos\n(recm=(mean((real-ts(z_pred$mean))^2))^.5) # rmse\n(recmp=(mean(((real-ts(z_pred$mean))/real)^2))^.5) # rmspe\n\n(eam=mean(abs(real-ts(z_pred$mean)))) # mae\n(eamp=mean(abs((real-ts(z_pred$mean))/real))) # mape\n\n# descomposici?n del error cuadr?tico medio\n(ecm=(mean((real-ts(z_pred$mean))^2))) # c?lculo del error cuadr?tico medio\n\n# proporci?n de sesgo\n(prop_sesgo_med=(mean(ts(z_pred$mean))-mean(real))^2/ecm) \n\n# c?lculo de varianza sesgadas\nsigmap=((length(real)-1)/length(real)*var(ts(z_pred$mean)))^.5 # c?lculo de desv. estand. de los pron?sticos\nsigmar=((length(real)-1)/length(real)*var(ts(real)))^.5 # c?lculo de desv. estand. de los datos\n\n# proporci?n de varianza\n(prop_sesgo_var=(sigmap-sigmar)^2/ecm) \n\n# proporci?n de covarianza\n(prop_covar=2*(1-cor(ts(z_pred$mean), real))*sigmap*sigmar/ecm)\nprop_sesgo_med+prop_sesgo_var+prop_covar # verificaci?n de c?lculos\n\n# Verdaderos Pron?sticos\n(z_pron<-forecast(mod1_CSS_ML, h=10, level=c(90), lambda=mod1_CSS_ML$lambda, fan=FALSE))\nplot(forecast(z_pron))\n\n\n", "meta": {"hexsha": "3612a74c1f1c26c4024b4414196a46c94d0132e6", "size": 8784, "ext": "r", "lang": "R", "max_stars_repo_path": "src/00_preprocessing_and_eda/01_eda.r", "max_stars_repo_name": "svasquezro29/time-series-analysis", "max_stars_repo_head_hexsha": "ab1f5a6e1f8ef7a314b39c2437f252a7b68a0e4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/00_preprocessing_and_eda/01_eda.r", "max_issues_repo_name": "svasquezro29/time-series-analysis", "max_issues_repo_head_hexsha": "ab1f5a6e1f8ef7a314b39c2437f252a7b68a0e4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/00_preprocessing_and_eda/01_eda.r", "max_forks_repo_name": "svasquezro29/time-series-analysis", "max_forks_repo_head_hexsha": "ab1f5a6e1f8ef7a314b39c2437f252a7b68a0e4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2975206612, "max_line_length": 113, "alphanum_fraction": 0.6839708561, "num_tokens": 3055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7310184309061287}} {"text": "ybar=33\r\nsigma=8.4\r\nn=35\r\nalpha = .05 \r\n# critical value\r\nz.alpha = qnorm(1-alpha) \r\nz1=function(mu0){\r\n z=abs((ybar- mu0)/(sigma/sqrt(n)))\r\n b=pnorm(z.alpha-z)\r\n return(b)\r\n}\r\nmuo=c(33,32,31,30,29,28,27,26,25) \r\nbeta=c(z1(33),z1(32),z1(31),z1(30),z1(29),z1(28),z1(27),z1(26),z1(25))\r\npwr=1-beta\r\nrbind(muo,beta,pwr) \r\n\r\n ", "meta": {"hexsha": "62e37921eb4a50ba87d8fda3b3d5d63b05b8b1ad", "size": 327, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.10/Ex5_10.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.10/Ex5_10.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.10/Ex5_10.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 19.2352941176, "max_line_length": 71, "alphanum_fraction": 0.5902140673, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7310181543051895}} {"text": "=begin\n # sample-m-factorize01.rb\n\n require \"algebra\"\n P = MPolynomial(Integer)\n x, y, z = P.vars(\"xyz\")\n f = x**3 + y**3 + z**3 - 3*x*y*z\n p f.factorize #=> (x + y + z)(x^2 - xy - xz + y^2 - yz + z^2)\n \n PQ = MPolynomial(Rational)\n x, y, z = PQ.vars(\"xyz\")\n f = x**3 + y**3/8 + z**3 - 3*x*y*z/2\n p f.factorize #=> (1/8)(2x + y + 2z)(4x^2 - 2xy - 4xz + y^2 - 2yz + 4z^2)\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "9c1b2c5f1536b80b658e45ea4e343f652351316d", "size": 404, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-m-factorize01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-m-factorize01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-m-factorize01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.25, "max_line_length": 75, "alphanum_fraction": 0.4925742574, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7307013593161165}} {"text": "## ----author info, include=F----------------------------------------------\n## Author: Yanchang Zhao\n## Email: yanchang@RDataMining.com\n## Website: http://www.RDataMining.com\n## Date: 9 December 2018\n\n## ----load libraries, include=F, echo=F-----------------------------------\n## load required packages\nlibrary(dtw)\nlibrary(wavelets)\nlibrary(party)\n\n## ------------------------------------------------------------------------\na <- ts(1:20, frequency=12, start=c(2011,3))\nprint(a)\nstr(a)\nattributes(a)\n\n## ----out.width=\".85\\\\textwidth\"------------------------------------------\nplot(AirPassengers)\n\n## ----out.width=\".9\\\\textwidth\"-------------------------------------------\napts <- ts(AirPassengers, frequency = 12)\nf <- decompose(apts)\nplot(f$figure, type=\"b\") # seasonal figures\n\n## ----out.width=\".75\\\\textwidth\"------------------------------------------\nplot(f)\n\n## ----tidy=F--------------------------------------------------------------\n# build an ARIMA model\nfit <- arima(AirPassengers, order=c(1,0,0), \n list(order=c(2,1,0), period=12))\nfore <- predict(fit, n.ahead=24)\n# error bounds at 95% confidence level\nU <- fore$pred + 2*fore$se\nL <- fore$pred - 2*fore$se\n\n## ----plot-forecast, fig.show=\"hide\", tidy=F------------------------------\nts.plot(AirPassengers, fore$pred, U, L, \n col = c(1, 2, 4, 4), lty = c(1, 1, 2, 2))\nlegend(\"topleft\", col = c(1, 2, 4), lty = c(1, 1, 2),\n c(\"Actual\", \"Forecast\", \"Error Bounds (95% Confidence)\"))\n\n## ----echo=F, out.width=\"\\\\textwidth\"-------------------------------------\nts.plot(AirPassengers, fore$pred, U, L, \n col = c(1, 2, 4, 4), lty = c(1, 1, 2, 2))\nlegend(\"topleft\", col = c(1, 2, 4), lty = c(1, 1, 2),\n c(\"Actual\", \"Forecast\", \"Error Bounds (95% Confidence)\"))\n\n## ----fig.show=\"hide\"-----------------------------------------------------\nlibrary(dtw)\nidx <- seq(0, 2*pi, len=100)\na <- sin(idx) + runif(100)/10\nb <- cos(idx)\nalign <- dtw(a, b, step=asymmetricP1, keep=T)\ndtwPlotTwoWay(align)\n\n## ----echo=F, out.height=\".8\\\\textheight\"---------------------------------\ndtwPlotTwoWay(align)\n\n## ----fig.show='hide', tidy=F---------------------------------------------\n# read data into R\n# sep=\"\": the separator is white space, i.e., one\n# or more spaces, tabs, newlines or carriage returns\nsc <- read.table(\"./data/synthetic_control.data\", header=F, sep=\"\")\n# show one sample from each class\nidx <- c(1, 101, 201, 301, 401, 501)\nsample1 <- t(sc[idx,])\nplot.ts(sample1, main=\"\")\n\n## ----echo=F, out.height=\"\\\\textheight\"-----------------------------------\nplot.ts(sample1, main=\"\")\n\n## ----echo=F--------------------------------------------------------------\nset.seed(17)\n\n## ----fig.show='hide'-----------------------------------------------------\n# sample n cases from every class\nn <- 10\ns <- sample(1:100, n)\nidx <- c(s, 100+s, 200+s, 300+s, 400+s, 500+s)\nsample2 <- sc[idx,]\nobservedLabels <- rep(1:6, each=n)\n# hierarchical clustering with Euclidean distance \nhc <- hclust(dist(sample2), method=\"ave\")\nplot(hc, labels=observedLabels, main=\"\")\n\n## ----echo=F, out.height=\"\\\\textheight\"-----------------------------------\nplot(hc, labels=observedLabels, main=\"\")\n\n## ------------------------------------------------------------------------\n# cut tree to get 8 clusters\nmemb <- cutree(hc, k=8)\ntable(observedLabels, memb)\n\n## ----fig.show='hide'-----------------------------------------------------\nmyDist <- dist(sample2, method=\"DTW\")\nhc <- hclust(myDist, method=\"average\")\nplot(hc, labels=observedLabels, main=\"\")\n# cut tree to get 8 clusters\nmemb <- cutree(hc, k=8)\ntable(observedLabels, memb)\n\n## ----echo=F, out.height=\"\\\\textheight\"-----------------------------------\nplot(hc, labels=observedLabels, main=\"\")\n\n## ----tidy=F--------------------------------------------------------------\nclassId <- rep(as.character(1:6), each = 100)\nnewSc <- data.frame(cbind(classId, sc)) \nlibrary(party)\nct <- ctree(classId ~ ., data = newSc, \n controls = ctree_control(minsplit = 20, \n minbucket = 5, maxdepth = 5)) \n\n## ------------------------------------------------------------------------\npClassId <- predict(ct)\ntable(classId, pClassId)\n# accuracy\n(sum(classId==pClassId)) / nrow(sc)\n\n## ------------------------------------------------------------------------\n# extract DWT (with Haar filter) coefficients\nlibrary(wavelets)\nwtData <- NULL\nfor (i in 1:nrow(sc)) {\n a <- t(sc[i,])\n wt <- dwt(a, filter=\"haar\", boundary=\"periodic\")\n wtData <- rbind(wtData, \n unlist(c(wt@W, wt@V[[wt@level]])))\n}\nwtData <- as.data.frame(wtData)\nwtSc <- data.frame(cbind(classId, wtData))\n\n## ----tidy=F--------------------------------------------------------------\nct <- ctree(classId ~ ., data = wtSc, \n controls = ctree_control(minsplit=20, minbucket=5, \n maxdepth=5))\npClassId <- predict(ct) \ntable(classId, pClassId)\n(sum(classId==pClassId)) / nrow(wtSc)\n\n## ----fig.width=18, fig.height=8, out.height=\".85\\\\textheight\", out.width=\"1.1\\\\textwidth\"----\nplot(ct, ip_args=list(pval=F), ep_args=list(digits=0))\n\n## ----echo=F--------------------------------------------------------------\nset.seed(100)\n\n## ------------------------------------------------------------------------\nk <- 20\nnewTS <- sc[501,] + runif(100)*15\ndistances <- dist(newTS, sc, method=\"DTW\")\ns <- sort(as.vector(distances), index.return=TRUE)\n# class IDs of k nearest neighbours\ntable(classId[s$ix[1:k]])\n\n", "meta": {"hexsha": "4b41b74c6e119114ec1dfd10ac7fea2284a529fa", "size": 5482, "ext": "r", "lang": "R", "max_stars_repo_path": "Scripts/RDM-script-time-series-analysis.r", "max_stars_repo_name": "enriqueescobar-askida/Kinito.R.DataMining", "max_stars_repo_head_hexsha": "766ece2ad9a30a0dc78a9fa9b27efdfb1be96ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scripts/RDM-script-time-series-analysis.r", "max_issues_repo_name": "enriqueescobar-askida/Kinito.R.DataMining", "max_issues_repo_head_hexsha": "766ece2ad9a30a0dc78a9fa9b27efdfb1be96ace", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scripts/RDM-script-time-series-analysis.r", "max_forks_repo_name": "enriqueescobar-askida/Kinito.R.DataMining", "max_forks_repo_head_hexsha": "766ece2ad9a30a0dc78a9fa9b27efdfb1be96ace", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9171974522, "max_line_length": 95, "alphanum_fraction": 0.4728201386, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.7306894274492256}} {"text": "#' The zero-truncated compund poisson-lognormal distributions mixture\n#'\n#' Density function and random generation for Zero-Truncated \n#' Poisson Lognormal distribution with parameters `mu`, `sig`, and `theta`.\n#'\n#' Type 1 ZTPLN truncates zero based on Poisson-lognormal distribution and \n#' type 2 ZTPLN truncates zero based on zero-truncated Poisson distribution.\n#' For mathematical details, please see `vignette(\"ztpln\")`\n#'\n#' @param n number of random values to return.\n#' @param mu vector of mean of lognormal distribution in sample.\n#' @param sig vector standard deviation of lognormal distribution in sample.\n#' @param theta vector of mixture weights\n#' @param x\tvector of (non-negative integer) quantiles.\n#' @param log logical; if TRUE, probabilities p are given as log(p).\n#' @param type1 logical; if TRUE, Use type 1 ztpln else use type 2. \n#' @return dztplnm gives the (log) density and rztplnm generates\n#' random variates.\n#' function, qpois gives the quantile function, and rpois generates random\n#' deviates.\n#' @seealso \\code{\\link{dztpln}}\n#' @examples\n#' rztplnm(n = 100, mu = c(0, 5), sig = c(1, 2), theta = c(0.2, 0.8))\n#' dztplnm(x = 1:100, mu = c(0, 5), sig = c(1, 2), theta = c(0.2, 0.8))\n#' dztplnm(x = 1:100, mu = c(0, 5), sig = c(1, 2), theta = c(0.2, 0.8), type1 = FALSE)\n#' @export\ndztplnm <- function(x, mu, sig, theta, log = FALSE, type1 = TRUE) {\n if (length(mu) != length(sig) |\n length(mu) != length(theta) |\n length(sig) != length(theta)) {\n stop(\"The length of vectors of mean, \n variance and mixture weight need to be same.\")\n }\n if (sum(theta) != 1) warning(\"Sum of the mixture weight should be 1.\")\n theta <- theta / sum(theta)\n if (type1) {\n lik <- do_dztplnm(x, mu, sig, theta)\n } else lik <- do_dztplnm2(x, mu, sig, theta)\n if (log) return(log(lik)) else return(lik)\n}\n\n#' @rdname dztplnm\n#' @export\nrztplnm <- function(n, mu, sig, theta, type1 = TRUE) {\n # theta: mixture weight for the first compoment\n if (length(mu) != length(sig) | length(mu) != length(theta) |\n length(sig) != length(theta)) {\n stop(\"The length of vectors of mean, \n variance and mixture weight need to be same.\")\n }\n if (sum(theta) != 1) warning(\"Sum of the mixture weight should be 1.\")\n z <- rmultinom(n, 1, theta)\n z2 <- as.numeric(z * seq(1, length(mu)))\n z3 <- z2[z2 > 0]\n if (type1) do_vec2_rztpln1(n, mu[z3], sig[z3]) else do_vec2_rztpln2(n, mu[z3], sig[z3])\n}\n", "meta": {"hexsha": "e1507b5d3db51735f3204578e28047fa5af6af47", "size": 2443, "ext": "r", "lang": "R", "max_stars_repo_path": "R/dztplnm.r", "max_stars_repo_name": "mattocci27/poilog2", "max_stars_repo_head_hexsha": "5d2a6e6dc4238a9bb61a02126a99fe8b8205ef35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/dztplnm.r", "max_issues_repo_name": "mattocci27/poilog2", "max_issues_repo_head_hexsha": "5d2a6e6dc4238a9bb61a02126a99fe8b8205ef35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/dztplnm.r", "max_forks_repo_name": "mattocci27/poilog2", "max_forks_repo_head_hexsha": "5d2a6e6dc4238a9bb61a02126a99fe8b8205ef35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8596491228, "max_line_length": 89, "alphanum_fraction": 0.6606631191, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7302837772958782}} {"text": "# Example : 2.7A Chapter : 2.7 Pageno : 114\n# Multiplication by Permutation matrices\nP<-matrix(c(0,0,1,1,0,0,0,1,0),ncol=3)\nA<-matrix(c(1,4,5,4,2,6,5,6,3),ncol=3)\nQ<-t(P)\nPA<-P%*%A\nPAQ<-PA%*%Q\nprint(\"P*A\")\nprint(PA)\nprint(\"P*A*Q\")\nprint(PAQ)", "meta": {"hexsha": "34dc004beea27fb809339fcb4af4b328ea9732f2", "size": 245, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.7.a/Ex2_2.7A.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.7.a/Ex2_2.7A.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.7.a/Ex2_2.7A.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 22.2727272727, "max_line_length": 47, "alphanum_fraction": 0.612244898, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7302618393165616}} {"text": "#' Draws a t-distribution curve and shades rejection regions\n#' \n#' @param df degrees of freedom.\n#' @param alpha significance level\n#' @param h0 null hypothesis value\n#' @param sides one of: both, left, right\n#' @param t_calc calculated test statistics\n#' @examples\n#' shade(49, 0.05, 0, t_calc=1.1)\nshade <- function(df, alpha, h0 = 0, sides='both', t_calc=NULL) {\n e_alpha = alpha\n if(sides == 'both'){\n e_alpha = alpha / 2\n }\n cv = abs(qt(e_alpha, df))\n curve(dt(x, df), from = -4, to = 4, ylab='P(x)', xaxt='n') \n abline(v = 0, col = \"black\", lwd = 0.5)\n labels = h0\n at = 0\n if(sides == 'both' | sides == 'left'){\n x <- seq(-4, -abs(cv), len = 100) \n y <- dt(x, df)\n polygon(c(x, -abs(cv)), c(y, min(y)), col = \"blue\", border = NA)\n lines(c(-cv, -cv), c(0, dt(-cv, df)), col = \"black\", lwd = 1)\n text(-cv - (4 - cv) / 2, 0.05, e_alpha)\n labels = c(round(-cv, 3), labels)\n at = c(-cv, at)\n }\n if(sides == 'both' | sides == 'right'){\n x <- seq(abs(cv), 4, len = 100)\n y <- dt(x, df)\n polygon(c(abs(cv), x), c(min(y), y), col = \"blue\", border = NA)\n lines(c(cv, cv), c(0, dt(cv, df)), col = \"black\", lwd = 1)\n text(cv + (4 - cv) / 2, 0.05, e_alpha)\n labels = c(labels, round(cv, 3))\n at = c(at, cv)\n }\n if(is.numeric(t_calc)){\n abline(v = t_calc, col = \"red\", lwd = 2)\n text(t_calc + 0.5, 0.2, t_calc, col = \"red\")\n }\n axis(1, at=at, labels=labels)\n}", "meta": {"hexsha": "225e77bd444497e103f0d0bba548b8fd6e0d73bc", "size": 1419, "ext": "r", "lang": "R", "max_stars_repo_path": "shade.r", "max_stars_repo_name": "VolodymyrOrlov/MSDS6371", "max_stars_repo_head_hexsha": "bf1e90f7da04f8480c5b7538c5b8274fe2a9126f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shade.r", "max_issues_repo_name": "VolodymyrOrlov/MSDS6371", "max_issues_repo_head_hexsha": "bf1e90f7da04f8480c5b7538c5b8274fe2a9126f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shade.r", "max_forks_repo_name": "VolodymyrOrlov/MSDS6371", "max_forks_repo_head_hexsha": "bf1e90f7da04f8480c5b7538c5b8274fe2a9126f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0, "max_line_length": 68, "alphanum_fraction": 0.5412262156, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7302618308762657}} {"text": "## Dexter Barrows\n## dbarrows.github.com\n## McMaster University\n## 2016\n\nStocSIR <- function(y, pars, T, steps) {\n\n out <- matrix(NA, nrow = (T+1), ncol = 4)\n\n R0 <- pars[['R0']]\n r <- pars[['r']]\n N <- pars[['N']]\n eta <- pars[['eta']]\n berr <- pars[['berr']]\n\n S <- y[['S']]\n I <- y[['I']]\n R <- y[['R']]\n\n B0 <- R0 * r / N\n B <- B0\n\n out[1,] <- c(S,I,R,B)\n\n h <- 1 / steps\n\n for ( i in 1:(T*steps) ) {\n\n B <- exp( log(B) + eta*(log(B0) - log(B)) + rnorm(1, 0, berr) )\n\n BSI <- B*S*I\n rI <- r*I\n\n dS <- -BSI\n dI <- BSI - rI\n dR <- rI\n\n S <- S + h*dS\n I <- I + h*dI\n R <- R + h*dR\n\n if (i %% steps == 0)\n out[i/steps+1,] <- c(S,I,R,B)\n\n }\n\n return(out)\n\n}\n\n### Suggested parameters\n#\n# T <- 60\n# i_infec <- 5\n# steps <- 7\n# N <- 500\n# sigma <- 10\n#\n# pars <- c(R0 = 3.0, # new infected people per infected person\n# r = 0.1, # recovery rate\n# N = 500, # population size\n# eta = 0.5, # geometric random walk\n# berr = 0.5) # Beta geometric walk noise", "meta": {"hexsha": "33e1ba5b4c67088038b0632e6b37c6e92768354e", "size": 1152, "ext": "r", "lang": "R", "max_stars_repo_path": "code/sir-functions/StocSIR.r", "max_stars_repo_name": "dbarrows/epidemic-forecasting", "max_stars_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/sir-functions/StocSIR.r", "max_issues_repo_name": "dbarrows/epidemic-forecasting", "max_issues_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/sir-functions/StocSIR.r", "max_forks_repo_name": "dbarrows/epidemic-forecasting", "max_forks_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2857142857, "max_line_length": 71, "alphanum_fraction": 0.4071180556, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7300500531111983}} {"text": "exp(1) # e\npi # pi\nsqrt(x) # square root\nlog(x) # natural logarithm\nlog10(x) # base 10 logarithm\nlog(x, y) # arbitrary base logarithm\nexp(x) # exponential\nabs(x) # absolute value\nfloor(x) # floor\nceiling(x) # ceiling\nx^y # power\n", "meta": {"hexsha": "37e381320af16306c81fea496e9d23a56bcdc979", "size": 356, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Real-constants-and-functions/R/real-constants-and-functions.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Real-constants-and-functions/R/real-constants-and-functions.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Real-constants-and-functions/R/real-constants-and-functions.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 29.6666666667, "max_line_length": 45, "alphanum_fraction": 0.441011236, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877684006775, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.7299694178219729}} {"text": "NAME\tAckermann\n\nMODE\tREDUCTION\n\nSORTS\tNAT\n\nSIGNATURE\n\t0 : -> NAT\n\ts : NAT -> NAT\n\t+ : NAT NAT -> NAT\n\t* : NAT NAT -> NAT\n\tfac : NAT -> NAT\n\tack : NAT NAT -> NAT\n\nORDERING KBO\n ack = 1, fac = 1, * = 1, + = 1, s = 1, 0 = 1\n\tack > fac > * > + > s > 0\n\nVARIABLES\n\tx,y : NAT\n\nEQUATIONS\n\t+(x,0) = x\n\t+(x,s(y)) = s(+(x,y))\n\t*(x,0) = 0\n\t*(x,s(y)) = +(*(x,y),x)\n\tfac(0) = s(0)\n\tfac(s(x)) = *(s(x),fac(x))\n\tack(0,y) = s(y)\n\tack(s(x),0) = ack(x,s(0))\n\tack(s(x),s(y)) = ack(x,ack(s(x),y))\n\nCONCLUSION fac(s(s(s(s(s(0)))))) = ack(s(s(s(0))),0)\n\t*(ack(s(s(s(0))),0),0) = *(0,ack(s(s(s(0))),0))\n", "meta": {"hexsha": "a0b646785b5d801b83d50a81a88ed3e88dbb0adf", "size": 589, "ext": "rd", "lang": "R", "max_stars_repo_path": "src/test/resources/specs/Ackermann.rd", "max_stars_repo_name": "falsewasnottrue/forstmeister", "max_stars_repo_head_hexsha": "a6402a479d6218b71b12369a97dab8f61e3f9717", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/resources/specs/Ackermann.rd", "max_issues_repo_name": "falsewasnottrue/forstmeister", "max_issues_repo_head_hexsha": "a6402a479d6218b71b12369a97dab8f61e3f9717", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/resources/specs/Ackermann.rd", "max_forks_repo_name": "falsewasnottrue/forstmeister", "max_forks_repo_head_hexsha": "a6402a479d6218b71b12369a97dab8f61e3f9717", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8285714286, "max_line_length": 52, "alphanum_fraction": 0.4499151104, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7298975183329386}} {"text": "#!/usr/bin/env Rscript\n\n# sum_of_odds.r - calculate sum of odd integers\n\nversion__ = 1.1\ndate__ = '2021-01-14'\n\nup_to <- 170\n\nis_odd <- function(x)\n{\n remainder <- x %% 2\n if (remainder == 0) return(FALSE)\n else return(TRUE)\n}\n\nsum <- 0\nnumber_of_odds <- 0\nlast_odd <- 0\n\nfor (i in 0:up_to)\n{\n if (is_odd(i))\n {\n sum <- sum + i\n number_of_odds <- number_of_odds + 1\n last_odd <- i\n }\n}\n\nif (sum == number_of_odds ^ 2)\n{\n if (number_of_odds == 0) { ; }\n else if (number_of_odds < 7) print(sum)\n else cat('1 + 3 + 5 + ... +', last_odd - 1,\n '+', last_odd, '=', sum, \"\\n\")\n} else warning('Unexpected error: ', sum)\n", "meta": {"hexsha": "be426a5a9a8fe1569e451c01dd502fb2ae13f113", "size": 655, "ext": "r", "lang": "R", "max_stars_repo_path": "samples/sum_of_odds/sum_of_odds.r", "max_stars_repo_name": "glires/Eicosalingual", "max_stars_repo_head_hexsha": "63317b5c043787f072fe18260c5b799b24a420fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "samples/sum_of_odds/sum_of_odds.r", "max_issues_repo_name": "glires/Eicosalingual", "max_issues_repo_head_hexsha": "63317b5c043787f072fe18260c5b799b24a420fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/sum_of_odds/sum_of_odds.r", "max_forks_repo_name": "glires/Eicosalingual", "max_forks_repo_head_hexsha": "63317b5c043787f072fe18260c5b799b24a420fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2368421053, "max_line_length": 47, "alphanum_fraction": 0.5633587786, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7298929489110164}} {"text": "# 1. 验证序列平稳性\nlibrary(forecast)\nlibrary(tseries)\nplot.ts(hua_train)\nhua_train<-as.numeric(unlist(hua_train))\nndiffs(hua_train)\ndhua_train<-diff(hua_train)\nplot.ts(dhua_train)\nADF<-adf.test(dhua_train)\nADF # 原假设:存在单位根(存在单位根为非平稳时间序列);拒绝原假设:序列平稳\n\n# 2. 模型自动定阶及拟合\nfit <- auto.arima(hua_train)\nfit\naccuracy(fit)\n\n\npacf (dhua_train, 40, ylim=range(-1,1))\nacf (dhua_train, 40, ylim=range(-1,1))\nfit <- arima(hua_train,order=c(12,1,3))\n\n# 3. 模型诊断\nqqnorm(fit$residuals)\nqqline(fit$residuals)\nBox.test(fit$residuals,type = \"Ljung-Box\")\n\n\n# 4. 用ARIMA进行预测\nforecast(fit,1)\nplot(forecast(fit,1),xlab=\"month\",ylab=\"Monthly runoff\")\n", "meta": {"hexsha": "ba038d83e7430aa8e2102e3136f2cc6e5e69d1da", "size": 615, "ext": "r", "lang": "R", "max_stars_repo_path": "tools/arima_demo4.r", "max_stars_repo_name": "zjy8006/MonthlyRunoffForecastByAutoReg", "max_stars_repo_head_hexsha": "661fcb5dcdfbbb2ec6861e1668a035b50e69f7c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-18T06:45:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T06:38:23.000Z", "max_issues_repo_path": "tools/arima_demo4.r", "max_issues_repo_name": "zjy8006/MonthlyRunoffForecastByAutoReg", "max_issues_repo_head_hexsha": "661fcb5dcdfbbb2ec6861e1668a035b50e69f7c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/arima_demo4.r", "max_forks_repo_name": "zjy8006/MonthlyRunoffForecastByAutoReg", "max_forks_repo_head_hexsha": "661fcb5dcdfbbb2ec6861e1668a035b50e69f7c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-17T02:56:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T02:56:18.000Z", "avg_line_length": 19.8387096774, "max_line_length": 56, "alphanum_fraction": 0.7382113821, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.7298635933072738}} {"text": "# median for interval data \r\nMedian_calculate <- function(frequencies, intervals, sep = NULL, trim = NULL) {\r\n # If \"sep\" is specified, the function will try to create the \r\n # required \"intervals\" matrix. \"trim\" removes any unwanted \r\n # characters before attempting to convert the ranges to numeric.\r\n if (!is.null(sep)) {\r\n if (is.null(trim)) pattern <- \"\"\r\n else if (trim == \"cut\") pattern <- \"\\\\[|\\\\]|\\\\(|\\\\)\"\r\n else pattern <- trim\r\n intervals <- sapply(strsplit(gsub(pattern, \"\", intervals), sep), as.numeric)\r\n }\r\n \r\n Midpoints <- rowMeans(intervals)\r\n cf <- cumsum(frequencies)\r\n Midrow <- findInterval(max(cf)/2, cf) + 1\r\n L <- intervals[1, Midrow] # lower class boundary of median class\r\n h <- diff(intervals[, Midrow]) # size of median class\r\n f <- frequencies[Midrow] # frequency of median class\r\n cf2 <- cf[Midrow - 1] # cumulative frequency class before median class\r\n n_2 <- max(cf)/2 # total observations divided by 2\r\n \r\n unname(L + (n_2 - cf2)/f * h)\r\n}\r\n\r\n\r\nmydataframe <- structure(list(Class_interval = c(\"16.25-18.75\", \"18.75-21.25\", \"21.25-23.75\", \r\n \"23.75-26.25\", \"26.25-28.75\", \" 28.75-31.25\", \" 31.25-33.75\", \"33.75-36.25\", \r\n \"36.25-38.75\", \" 38.75- 41.25\",\"41.25- 43.75\"), freq = c(2L, 7L, 7L, 14L, \r\n 17L, 24L, 11L, 11L, 3L, 3L,1L)), .Names = c(\"class_interval\", \"freq\"), \r\n class = \"data.frame\", row.names = c(NA, -11L))\r\nprint(mydataframe)\r\n\r\nMedian_calculate(mydataframe$freq, mydataframe$class_interval, sep = \"-\")\r\n\r\n", "meta": {"hexsha": "467de39f374a7f9fd9282099d72c8c9f7db7d400", "size": 1673, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH3/EX3.4/Ex3_4.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH3/EX3.4/Ex3_4.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH3/EX3.4/Ex3_4.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 47.8, "max_line_length": 144, "alphanum_fraction": 0.555887627, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7297071578462974}} {"text": "primes <- c(2, 3, 5, 7, 11, 13)\nisPrime <- function(a) {\n i <- 1\n while (a %% primes[i] > 0) {\n if (primes[i] * primes[i] > a) {\n primes <<- append(primes, a)\n return(TRUE)\n }\n i <- i + 1\n }\n FALSE\n}\n\nprimeSeq <- function() {\n p0 <- 1\n i <- 0\n return(function() {\n if (p0 <= length(primes)) {\n i <<- primes[p0]\n p0 <<- p0 + 1\n return(i)\n }\n i <<- i + 2\n while (!isPrime(i)) {\n i <<- i + 2\n }\n p0 <<- p0 + 1\n return(i)\n })\n}\n\nisPalindrome <- function(s) {\n return(s == sapply(lapply(strsplit(s, \"\"), rev), paste, collapse=\"\"))\n}\n\nmaxPrime <- 0\nnextPrime <- primeSeq()\nj <- nextPrime()\nwhile (j < 1000) {\n if (isPalindrome(toString(j))) {\n maxPrime <- j\n }\n j <- nextPrime()\n}\ncat(maxPrime, sep=\"\\n\")\n", "meta": {"hexsha": "d54b2af501841fd243e3a28420c128181dd82a35", "size": 774, "ext": "r", "lang": "R", "max_stars_repo_path": "easy/prime_palindrome.r", "max_stars_repo_name": "IlkhamGaysin/ce-challenges", "max_stars_repo_head_hexsha": "ac6b8c1fc4b6c098e380b9d694e93e614f6c969b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-06-24T17:09:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-03T11:44:54.000Z", "max_issues_repo_path": "easy/prime_palindrome.r", "max_issues_repo_name": "IlkhamGaysin/ce-challenges", "max_issues_repo_head_hexsha": "ac6b8c1fc4b6c098e380b9d694e93e614f6c969b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "easy/prime_palindrome.r", "max_forks_repo_name": "IlkhamGaysin/ce-challenges", "max_forks_repo_head_hexsha": "ac6b8c1fc4b6c098e380b9d694e93e614f6c969b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8260869565, "max_line_length": 71, "alphanum_fraction": 0.480620155, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7294614433390232}} {"text": "rk4 <- function(f, x0, y0, x1, n) {\n vx <- double(n + 1)\n vy <- double(n + 1)\n vx[1] <- x <- x0\n vy[1] <- y <- y0\n h <- (x1 - x0)/n\n for(i in 1:n) {\n k1 <- h*f(x, y)\n k2 <- h*f(x + 0.5*h, y + 0.5*k1)\n k3 <- h*f(x + 0.5*h, y + 0.5*k2)\n k4 <- h*f(x + h, y + k3)\n vx[i + 1] <- x <- x0 + i*h\n vy[i + 1] <- y <- y + (k1 + k2 + k2 + k3 + k3 + k4)/6\n }\n cbind(vx, vy)\n}\n\nsol <- rk4(function(x, y) x*sqrt(y), 0, 1, 10, 100)\ncbind(sol, sol[, 2] - (4 + sol[, 1]^2)^2/16)[seq(1, 101, 10), ]\n\n vx vy\n [1,] 0 1.000000 0.000000e+00\n [2,] 1 1.562500 -1.457219e-07\n [3,] 2 3.999999 -9.194792e-07\n [4,] 3 10.562497 -2.909562e-06\n [5,] 4 24.999994 -6.234909e-06\n [6,] 5 52.562489 -1.081970e-05\n [7,] 6 99.999983 -1.659460e-05\n [8,] 7 175.562476 -2.351773e-05\n [9,] 8 288.999968 -3.156520e-05\n[10,] 9 451.562459 -4.072316e-05\n[11,] 10 675.999949 -5.098329e-05\n", "meta": {"hexsha": "e8c6ed50fa680abddc5dfbae46545d0e8c89d433", "size": 941, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Runge-Kutta-method/R/runge-kutta-method.r", "max_stars_repo_name": "mullikine/RosettaCodeData", "max_stars_repo_head_hexsha": "4f0027c6ce83daa36118ee8b67915a13cd23ab67", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Runge-Kutta-method/R/runge-kutta-method.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Runge-Kutta-method/R/runge-kutta-method.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 28.5151515152, "max_line_length": 63, "alphanum_fraction": 0.4569606801, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.7294067383930819}} {"text": "## Author: Sergio García Prado\n## Title: Exercises with Solutions 2\n\nrm(list = ls())\n\nQ <- matrix(c(-20, 20, 0, 0, 0, 0,\n 30, -50, 20, 0, 0, 0,\n 0, 60, -80, 20, 0, 0,\n 0, 0, 60, -80, 20, 0,\n 0, 0, 0, 60, -80, 20,\n 0, 0, 0, 0, 60, -60),\n 6, 6, byrow = TRUE)\n\n(A <- cbind(Q[, 1:(nrow(Q) - 1)], rep(1, nrow(Q))))\n# -20\t 20\t 0\t 0\t 0\t1\n# 30\t-50\t 20\t 0\t 0\t1\n# 0\t 60\t-80\t 20\t 0\t1\n# 0\t 0\t 60\t-80\t 20\t1\n# 0\t 0\t 0\t 60\t-80\t1\n# 0\t 0\t 0\t 0\t 60\t1\n\n## Should be solved via detailed balance equations...\n(stationary <- solve(A)[nrow(A), ])\n# 0.501030927835052 0.334020618556701 0.111340206185567\n# 0.037113402061855 0.012371134020618 0.004123711340206\n\n(r <- -Q / diag(Q))\n# -1.0\t1.00\t0.00\t0.00\t0.00\t0.00\n# 0.6 -1.00\t0.40\t0.00\t0.00\t0.00\n# 0.0 0.75 -1.00\t0.25\t0.00\t0.00\n# 0.0\t0.00\t0.75 -1.00\t0.25\t0.00\n# 0.0\t0.00\t0.00\t0.75 -1.00\t0.25\n# 0.0\t0.00\t0.00\t0.00\t1.00 -1.00\n\n(not.busy <- r[4, 3])\n# 0.75\n", "meta": {"hexsha": "a31d9258dab6fed3279cb868909e08ed43098bf2", "size": 1030, "ext": "r", "lang": "R", "max_stars_repo_path": "stochastic-processes/proposed-exercises/continuous-3.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "stochastic-processes/proposed-exercises/continuous-3.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "stochastic-processes/proposed-exercises/continuous-3.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8378378378, "max_line_length": 55, "alphanum_fraction": 0.4689320388, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7292845266993699}} {"text": "## Stern-Brocot sequence\n## 12/19/16 aev\nSternBrocot <- function(n){\n V <- 1; k <- n/2;\n for (i in 1:k)\n { V[2*i] = V[i]; V[2*i+1] = V[i] + V[i+1];}\n return(V);\n}\n\n## Required tests:\nrequire(pracma);\n{\ncat(\" *** The first 15:\",SternBrocot(15),\"\\n\");\ncat(\" *** The first i@n:\",\"\\n\");\nV=SternBrocot(40);\nfor (i in 1:10) {j=match(i,V); cat(i,\"@\",j,\",\")}\nV=SternBrocot(1200);\ni=100; j=match(i,V); cat(i,\"@\",j,\"\\n\");\nV=SternBrocot(1000); j=1;\nfor (i in 2:1000) {j=j*gcd(V[i-1],V[i])}\nif(j==1) {cat(\" *** All GCDs=1!\\n\")} else {cat(\" *** All GCDs!=1??\\n\")}\n}\n", "meta": {"hexsha": "9819d242cbddb3aa5ce9809834effffd7bc5892a", "size": 559, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Stern-Brocot-sequence/R/stern-brocot-sequence.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Stern-Brocot-sequence/R/stern-brocot-sequence.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Stern-Brocot-sequence/R/stern-brocot-sequence.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 24.3043478261, "max_line_length": 71, "alphanum_fraction": 0.518783542, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7291219468620818}} {"text": "n = 100 #100 cards\nsample(n)==(1:n) # is a vector of length n, the ith element of which equals 1 if the ith card matches its position in the deck and 0 otherwise\nsum(sample(n)==(1:n)) # adds up the elements of the vector, giving us the number of matching cards\nres = replicate(10^5,sum(sample(n)==(1:n))) # repeat the experiment 10^5 times, res contains the numbers of matched cards from each run of the experiment\nsum(res >= 1)/10^5 # add up the number of times where there was at least one matching card, and we divide by the number of simulations\n# you should get 1-1/e~0.63\n", "meta": {"hexsha": "dd1f8af98841b57a647efa49a3a7718ef45eff75", "size": 578, "ext": "r", "lang": "R", "max_stars_repo_path": "files/stat345/matching_problem_R_code.r", "max_stars_repo_name": "anastasiiakim/anastasiiakim.github.io", "max_stars_repo_head_hexsha": "83aad58339ba629dd4e63ffb833d1ec5a172ad12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-03T03:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-21T14:15:29.000Z", "max_issues_repo_path": "files/stat345/matching_problem_R_code.r", "max_issues_repo_name": "anastasiiakim/anastasiiakim.github.io", "max_issues_repo_head_hexsha": "83aad58339ba629dd4e63ffb833d1ec5a172ad12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/stat345/matching_problem_R_code.r", "max_forks_repo_name": "anastasiiakim/anastasiiakim.github.io", "max_forks_repo_head_hexsha": "83aad58339ba629dd4e63ffb833d1ec5a172ad12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-15T06:27:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T06:27:06.000Z", "avg_line_length": 82.5714285714, "max_line_length": 153, "alphanum_fraction": 0.7335640138, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7290207609663671}} {"text": "#conditions\nRosenbrock <- function(x){\n x1 <- x[1]\n x2 <- x[2]\n 100 * (x2 - x1 * x1)^2 + (1 - x1)^2\n}\n\nRosenbrock_cap <- function(x){\n if (x[1] + x[2] <= 3){\n r <- Inf\n }else{\n r = Rosenbrock(x)\n }\n return(r)\n}\n\nlower <- c(-10,-10)\nupper <- -lower\n\nset.seed(1234)\nDEoptim::DEoptim(Rosenbrock, lower, upper)\nDEoptim::DEoptim(Rosenbrock_cap, lower, upper)\n\n\n\n## Rosenbrock Banana function\n## The function has a global minimum f(x) = 0 at the point (1,1). \n## Note that the vector of parameters to be optimized must be the first \n## argument of the objective function passed to DEoptim.\nRosenbrock <- function(x){\n x1 <- x[1]\n x2 <- x[2]\n 100 * (x2 - x1 * x1)^2 + (1 - x1)^2\n}\n\n## DEoptim searches for minima of the objective function between\n## lower and upper bounds on each parameter to be optimized. Therefore\n## in the call to DEoptim we specify vectors that comprise the\n## lower and upper bounds; these vectors are the same length as the\n## parameter vector.\nlower <- c(-10,-10)\nupper <- -lower\n\n## run DEoptim and set a seed first for replicability\nset.seed(1234)\nDEoptim(Rosenbrock, lower, upper)\n\n## increase the population size\nDEoptim(Rosenbrock, lower, upper, DEoptim.control(NP = 100))\n\n## change other settings and store the output\noutDEoptim <- DEoptim(Rosenbrock, lower, upper, DEoptim.control(NP = 80,\n itermax = 400, F = 1.2, CR = 0.7))\n\n## plot the output\nplot(outDEoptim)\n\n## 'Wild' function, global minimum at about -15.81515\nWild <- function(x)\n 10 * sin(0.3 * x) * sin(1.3 * x^2) +\n 0.00001 * x^4 + 0.2 * x + 80\n\nplot(Wild, -50, 50, n = 1000, main = \"'Wild function'\")\n\noutDEoptim <- DEoptim(Wild, lower = -50, upper = 50,\n control = DEoptim.control(trace = FALSE))\n\nplot(outDEoptim)\n\nDEoptim(Wild, lower = -50, upper = 50,\n control = DEoptim.control(NP = 50))\n\n## The below examples shows how the call to DEoptim can be\n## parallelized.\n## Note that if your objective function requires packages to be\n## loaded or has arguments supplied via \\code{...}, these should be\n## specified using the \\code{packages} and \\code{parVar} arguments\n## in control. \n\nGenrose <- function(x) {\n ## One generalization of the Rosenbrock banana valley function (n parameters)\n n <- length(x)\n ## make it take some time ... \n Sys.sleep(.001) \n 1.0 + sum (100 * (x[-n]^2 - x[-1])^2 + (x[-1] - 1)^2)\n}\n\n# get some run-time on simple problems\nmaxIt <- 250 \nn <- 5\n\noneCore <- system.time( DEoptim(fn=Genrose, lower=rep(-25, n), upper=rep(25, n),\n control=list(NP=10*n, itermax=maxIt)))\n\nwithParallel <- system.time( DEoptim(fn=Genrose, lower=rep(-25, n), upper=rep(25, n),\n control=list(NP=10*n, itermax=maxIt, parallelType=1)))\n\n## Compare timings \n(oneCore)\n(withParallel)", "meta": {"hexsha": "e3289c89add65181615a26910e9e77840ee30edc", "size": 2838, "ext": "r", "lang": "R", "max_stars_repo_path": "model/deoptim_tute.r", "max_stars_repo_name": "0xdomyz/r_collection", "max_stars_repo_head_hexsha": "29defad610c9b8603fff91370176201f72aaa856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-25T13:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T13:57:36.000Z", "max_issues_repo_path": "model/deoptim_tute.r", "max_issues_repo_name": "0xdomyz/r_collection", "max_issues_repo_head_hexsha": "29defad610c9b8603fff91370176201f72aaa856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/deoptim_tute.r", "max_forks_repo_name": "0xdomyz/r_collection", "max_forks_repo_head_hexsha": "29defad610c9b8603fff91370176201f72aaa856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.38, "max_line_length": 86, "alphanum_fraction": 0.6346018323, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7289671357295389}} {"text": "getTTestSampleSize =\nfunction(x,\n minDetectDiffPercent,\n sigLevel=0.05,\n power=0.8,\n type=\"two.sample\",\n alternative=\"two.sided\") {\n # Get the required sample size for t-test\n # minDetectDiffPercent: Percent increase or decrease from the base mean you want to detect\n # type <- c(\"two.sample\", \"one.sample\", \"paired\")\n # alternative <- c(\"two.sided\", \"less\", \"greater\")\n # Return: pwr.t.test object with n (sample size) filled\n # Note: pooled standard deviation is approximated by the SD of x\n require(pwr)\n powerAnalysis =\n pwr.t.test(\n d=mean(x) * (minDetectDiffPercent / 100) / sd(x),\n sig.level=sigLevel,\n power=power,\n type=type,\n alternative=alternative)\n return(powerAnalysis)\n}\n\ngetDetectableDiff <- \nfunction(x,\n sampleSize, \n sigLevel=0.05, \n power=0.8, \n type=\"two.sample\", \n alternative=\"two.sided\") {\n # Get the detectable difference in real scale\n # sampleSize: Sample size in each group\n # type <- c(\"two.sample\", \"one.sample\", \"paired\")\n # alternative <- c(\"two.sided\", \"less\", \"greater\")\n # Return: pwr.t.test object with n (sample size) filled\n # Note: pooled standard deviation is approximated by the SD of x\n require(pwr)\n powerAnalysis =\n pwr.t.test(\n n=sampleSize,\n sig.level=sigLevel,\n power=power,\n type=type,\n alternative=alternative)\n detectableDiff <- powerAnalysis$d * sd(x)\n return(detectableDiff)\n}\n", "meta": {"hexsha": "7ee6142da4de8d6a20af4f4cbb722638cf7d35e0", "size": 1590, "ext": "r", "lang": "R", "max_stars_repo_path": "stats/power.r", "max_stars_repo_name": "daigotanaka/r-utils", "max_stars_repo_head_hexsha": "787b08973cd4e2d8c6f9de36baa994102cdda65b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-09-27T08:18:45.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-27T08:18:45.000Z", "max_issues_repo_path": "stats/power.r", "max_issues_repo_name": "daigotanaka/r-utils", "max_issues_repo_head_hexsha": "787b08973cd4e2d8c6f9de36baa994102cdda65b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stats/power.r", "max_forks_repo_name": "daigotanaka/r-utils", "max_forks_repo_head_hexsha": "787b08973cd4e2d8c6f9de36baa994102cdda65b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4489795918, "max_line_length": 94, "alphanum_fraction": 0.5968553459, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7288542408664167}} {"text": "# Example : 3.2A Chapter : 3.2 Page No: 139\r\n# Find the Matrix having the given special solutions\r\ns1<-c(-3,1,0,0)\r\ns2<-c(-2,0,-6,1)\r\nR<-diag(4)\r\nR<-R[-4,] \r\n#As 1st column is pivot column it is not needed to change\r\n#As 3rd column is next pivot column , row reduced echolon form has 1 in second row of third column\r\nR[,3]<-R[,2]\r\n#Two free columns are modified acording to special solutions\r\nR[,2]<-c(-1*s1[1],0,0)\r\nR[,4]<-c(-1*s2[1],-1*s2[3],0)\r\nprint(\"matrix having given special solutions\")\r\nprint(R)", "meta": {"hexsha": "a181d2dec0bbe8664a0ffb14b175c99559367cf2", "size": 510, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH3/EX3.2.a/Ex3_3.2A.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH3/EX3.2.a/Ex3_3.2A.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH3/EX3.2.a/Ex3_3.2A.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 36.4285714286, "max_line_length": 99, "alphanum_fraction": 0.6588235294, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7288318755392115}} {"text": "#!/usr/bin/Rscript\n# Copyright © 2016 Martin Ueding \n# Licensed under the MIT license.\n\norig_pdf = function(x) {\n 1 / sqrt(x * (1 - x)) / pi\n # The `return` is not needed, the return value is the last expression which\n # has been evaluated.\n}\n\nbin_count = 50\nsamples_count = 100000\n\n###############################################################################\n# Method (a): Inverse Function Method #\n###############################################################################\n\ninverse_cdf = function(u) {\n 1 - sin(1/2 * (pi - pi * u))^2\n}\n\n# Plot the original function.\nx_orig = seq(0, 1, length.out=200)\ny_orig = orig_pdf(x_orig)\nplot(x_orig, y_orig, type='l', main='Original PDF', xlab='x', ylab='y')\n\n# Plot the inverse function.\nu_inv_cdf = seq(0, 1, length.out=100)\nx_inv_cdf = inverse_cdf(u_inv_cdf)\nplot(u_inv_cdf, x_inv_cdf, type='l', main='Inverse CDF', xlab='u', ylab='x')\n\n# Sample from uniform, transform it and plot a histogram.\nstart = proc.time()\nu = runif(samples_count)\nx = inverse_cdf(u)\nend = proc.time()\nduration_inverse_cdf = end - start\nhist(x, breaks=bin_count, freq=FALSE, main='Sampling with Inverse Function Method')\nlines(x_orig, y_orig, col='red')\n\n###############################################################################\n# Method (b): Logistic Map #\n###############################################################################\n\nlogistic_map = function(x) {\n 4 * x * (1 - x)\n}\n\niterapply = function(start, func, length) {\n result = numeric(length)\n result[1] = start\n for (i in 2:length) {\n result[i] = func(result[i - 1])\n }\n return(result)\n}\n\nx = seq(0, 1, length.out=200)\ny = logistic_map(x)\nplot(x, y, type='l', main='Logistic Map', xlab='x', ylab='y')\n\nstart = proc.time()\niterations = iterapply(pi/4 - 0.1, logistic_map, samples_count)\nend = proc.time()\nduration_logistic = end - start\n\nplot(iterations[1:1000], main='Successive Applications of the Logistic Map')\nhist(iterations, breaks=bin_count, freq=FALSE, main='Sampling with Logistic Map')\nlines(x_orig, y_orig, col='red')\n\n###############################################################################\n# Method (c): Tent Function #\n###############################################################################\n\ntent = function(x) {\n result = numeric(length(x))\n idx1 = x <= 1/2\n idx2 = x > 1/2\n result[idx1] = 2 * x[idx1]\n result[idx2] = 2 * (1 - x[idx2])\n return(result)\n}\n\nx = seq(0, 1, length.out=200)\ny = tent(x)\nplot(x, y, type='l', main='Tent Function', xlab='x', ylab='y')\n\nstart = proc.time()\niterations = iterapply(pi/4 - 0.1, tent, samples_count)\nend = proc.time()\nduration_tent = end - start\n\nplot(iterations[1:1000], main='Successive Applications of the Tent Function')\nhist(iterations, breaks=bin_count, freq=FALSE, main='Sampling with Tent Function')\nlines(x_orig, y_orig, col='red')\n\ncat(\"Times; user, system, wall:\\n\")\ncat(\"Inverse cdf: \", duration_inverse_cdf, \"\\n\")\ncat(\"Logistic Map: \", duration_logistic, \"\\n\")\ncat(\"Tent: \", duration_tent, \"\\n\")\n", "meta": {"hexsha": "fe6aef0e52006cbadc1ae93e7043d2644cc23da7", "size": 3204, "ext": "r", "lang": "R", "max_stars_repo_path": "03/R/1-sampling.r", "max_stars_repo_name": "martin-ueding/exercides-2016", "max_stars_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03/R/1-sampling.r", "max_issues_repo_name": "martin-ueding/exercides-2016", "max_issues_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03/R/1-sampling.r", "max_forks_repo_name": "martin-ueding/exercides-2016", "max_forks_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7227722772, "max_line_length": 83, "alphanum_fraction": 0.5349563046, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7288155762396619}} {"text": "# introduce determinism\nset.seed(123)\n\n# global settings\nsampleSize <- 100\n\nrollingDiceSum <- function (n=10^3) {\n\trowSums(replicate(2, sample(6, n, replace=T)))\n}\n#plotIt <- function (what) {\n# # barplot(table(factor(what, level=1:12)), xlab=\"outcome\", ylab=\"abs. probability\")\n# barplot(table(what)/sampleSize, col=rgb(0, 0, 0.8, alpha=0.3), xlab=\"outcome\", ylab=\"rel. probability\")\n#}\n\nexperimentResults <- rollingDiceSum(sampleSize)\nbarplot(table(experimentResults)/sampleSize, col=rgb(0, 0, 0.8, alpha=0.3), xlab=\"outcome\", ylab=\"rel. probability\")\n\n\nexactProbabilities <- c(1:6, 5:1)/36 # via Skriptum, Beispiel in section 2.3\nbarplot(exactProbabilities, col=rgb(0.8, 0.8, 0, alpha=0.3), add=T, xaxt=\"n\", yaxt=\"n\")\n\n# w <- factor(w, level=c(1,2,3,4,5,6,7))\n\n", "meta": {"hexsha": "4ca599e30bee8ed0e983a6fe496227daaa453239", "size": 770, "ext": "r", "lang": "R", "max_stars_repo_path": "probability_theory_practicals/ex1/solution.r", "max_stars_repo_name": "prokls/math-lecture-notes", "max_stars_repo_head_hexsha": "d1a94e128d13ce4399a9cc55323b2f8e0d9494fd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-11-25T01:49:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T14:47:36.000Z", "max_issues_repo_path": "probability_theory_practicals/ex1/solution.r", "max_issues_repo_name": "prokls/math-lecture-notes", "max_issues_repo_head_hexsha": "d1a94e128d13ce4399a9cc55323b2f8e0d9494fd", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:56:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-02T09:32:40.000Z", "max_forks_repo_path": "probability_theory_practicals/ex1/solution.r", "max_forks_repo_name": "prokls/math-lecture-notes", "max_forks_repo_head_hexsha": "d1a94e128d13ce4399a9cc55323b2f8e0d9494fd", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-03-24T14:42:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-25T11:00:11.000Z", "avg_line_length": 32.0833333333, "max_line_length": 116, "alphanum_fraction": 0.6805194805, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7287588670150974}} {"text": "# Example : 1 Chapter : 2.7 Pageno : 108\n# Inverses and Transposes\nA<-matrix(c(1,6,0,1),ncol=2)\nAT<-t(A)\nA1<-solve(A)\nprint(\"The inverse and transpose of the matrix are \")\nprint(A1)\nprint(AT)\nprint(\"Transpose of A-1 is \")\nprint(t(A1))\nprint(\"Invere of A transpose is\")\nprint(solve(AT))", "meta": {"hexsha": "025c7589697363ab31e8dc8d331460fe1187d163", "size": 289, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.7.1/Ex2.7_1.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.7.1/Ex2.7_1.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.7.1/Ex2.7_1.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 24.0833333333, "max_line_length": 53, "alphanum_fraction": 0.678200692, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.7287567618396753}} {"text": "# ......................................................................................\n# .....................Cvičení 1 - Stručný úvod do R, Kombinatorika.....................\n# ..................Adéla Vrtková, Michal Béreš, Martina Litschmannová..................\n# ......................................................................................\n\n# Nezobrazuje-li se vám text korektně, nastavte File \\ Reopen with Encoding... na UTF-8\n# Pro zobrazení obsahu skriptu použijte CTRL+SHIFT+O\n# Pro spouštění příkazů v jednotlivých řádcích použijte CTRL+ENTER\n\n# Nejprve si projdeme některé základy Rka a naimplementujeme si některé kombinatorické\n# funkce.\n# \n# Krátký úvod do R ####\n\n\n# jednoduché početní operace\n2+4\n5/2\n\n# POZOR na závorky! Pro počítání se používají pouze kulaté! \n# Hranaté a složené mají v R jinou funkci!\n(((10+2)*(340-33))-2)/3\n\n# kombinační číslo, faktoriály\nchoose(10,2)\nfactorial(4)\n\n# datové typy -> numeric, character, logical, (complex)\n# funkcí class zjišťujeme typ objektu\na=2+3\nclass(a)\n\nb=\"pismenko\"\nclass(b)\n\nc=(1>3)\nclass(c)\n\nd=3+1i\nclass(d)\n\n# * datové struktury v R ####\n# \n# - vector (rozumíme sloupcový vektor)\n# - factor (speciální případ vektoru)\n# - matrix (matice s rozměry n x m)\n# - data.frame (datový rámec s rozměry n x p)\n# - list (seznam)\n\n\n# definování vektoru (sloupcový=column)\na = c(3,4,6,7)\na <- c(3,4,6,7)\na[2]\n\n# další možnosti\nrep(1,4) # vytvoří vektor se čtyřmi jedničkami\n\nseq(1,10,2) #posloupnost od 1 do 10 s krokem 2\n\n1:10 #posloupnost od 1 do 10 s krokem 1\n\nb=c(\"A\",\"B\",\"C\",\"D\")\nb\n\nclass(b)\n\n#předefinování objektu na jiný typ - např. as.vector, as.matrix, as.factor,...\nb=as.factor(b)\nb\n\n#práce s vektory - slučování podle sloupců/řádků\ncbind(a,b)\n\nrbind(a,b)\n\nc(a,b)\n\n## definování matice\nA=matrix(c(3,4,6,7,3,2),nrow=2,ncol=3)\nB=matrix(c(3,4,6,7,3,2),nrow=2,ncol=3,byrow=TRUE)\nC=matrix(c(3,4,6,7,3,2),nrow=3,ncol=2)\n\nB\n\nB[1,3]\n\nA[1,]\n\nA[,2:3]\n\n#diagonální matice\ndiag(4)\n\ndiag(4,2)\n\n## operace s maticemi - pozor na maticové násobení -> %*%\nA+B\n\nA-B\n\nA*B\n\nA%*%C\n\n# ......................................................................................\n# \n# Kombinatorika ####\n# \n# * Variace ####\n# \n# V(n,k) - variace bez opakování, první argument bude celkový počet entit, druhý\n# argument velikost výběru\n\n\n# funkce se vytváří příkazem fucntion, je to objekt jehož jméno je dáno až proměnnou \n# do které tento objekt přiřadím\nvariace = function(n,k) # zde zadávám počet parametrů a jejich jména\n{ # celé tělo funkce je uzavřeno mezi závorkami {...}\n citatel = factorial(n) # faktoriál v originálním Rku existuje tak jej použijeme\n jmenovatel = factorial(n-k)\n return(citatel/jmenovatel) # to co funkce vrátí se dává do příkazu return(...)\n}\n\n# V*(n,k) - variace s opakováním\n\n\nvariace_opak = function(n,k)\n{\n return(n^k)\n}\n\n# * Permutace ####\n# \n# P(n)=V(n,n) - permutace\n\n\npermutace = function(n)\n{\n return(variace(n,n))\n}\n\n# P*(n1,n2,n3,....,nk) - permutace s opakováním, vstup bude vektor s jednotlivými počty\n# unikátních entit\n\n\npermutace_opak = function(vec_n) # vec_n je vektro počtů hodnot př.: vec_n = c(2,2,2,4,3)\n{\n n = sum(vec_n) # spočteme kolik máme hodnot celkem\n res_temp=factorial(n) #jejich faktoriál = hodnota v čitateli\n # jednoduchý cyklus začíná příkazem for, pak v závorkách následuje název iterátoru \n # a z jakého seznamu bude brán\n for(pocet in vec_n) # pocet je iterátor a postupně bude nabývat hodnot z vektoru vec_n\n {\n # postupně dělíme faktoriálem každého počtu unikátních entit\n res_temp=res_temp/factorial(pocet) \n }\n return(res_temp)\n}\n\n# * Kombinace ####\n# \n# C(n,k) - kombinace\n\n\nkombinace = function(n,k)\n{\n return(choose(n,k)) # funkce for kombinace už existuje v Rku a jmenuje se choose\n}\n\n# C*(n,k) - kombinace s opakováním\n\n\nkombinace_opak = function(n,k)\n{\n return(choose(n+k-1,k)) # použijeme známý vzorec\n}\n\n# Úlohy na cvičení ####\n# \n# * Příklad 1. ####\n# \n# Které heslo je bezpečnější?\n# * Heslo o délce osm znaků složené pouze z číslic.\n# * Heslo o délce pět znaků složené pouze z písmen anglické abecedy.\n\n\n# heslo 1\nh1 = variace_opak(n = 10, k = 8)\n# heslo 2\nh2 = variace_opak(n = 26, k = 5)\nh1/h2\n\n# * Příklad 2. ####\n# \n# Jak dlouho by trvalo vyřešení problému obchodního cestujícího pro n = 10 měst hrubou\n# silou, jestliže vyhodnocení délky každé z možných cest trvá 1 µs?\n\n\nn = 10\npocet = permutace(n-1)/2\ncas = pocet/1000000\ncas\n\n# * Příklad 3. ####\n# \n# Jak rozdělit kořist mezi 2 loupežníky, aby dostali oba věci ve stejné hodnotě\n# (případně co nejbližší hodnotě). Tj. lze rozdělit N zadaných čísel do dvou skupin tak,\n# aby součet čísel v obou skupinách byl stejný?\n# \n# **Kolik možností by bylo třeba vyzkoušet, pokud bychom úlohu řešili hrubou silou?**\n\n\nN = 10\nL = 4\nvariace_opak(n = L, k = N)\n\n# * Příklad 4. ####\n# \n# Kolik anagramů slova \"AUTO\" můžeme vytvořit?\n# \n# Kolik anagramů slova \"AUTOMOBILKA\" můžeme vytvořit? Kolik z nich začína na \"K\"?\n\n\npermutace(4)\nvec = c(2,1,1,2,1,1,1,1,1)\nsum(vec)\npermutace_opak(vec)\n\nvec = c(2,1,1,2,1,1,1,1)\nsum(vec)\npermutace_opak(vec)\n\n# * Příklad 5. ####\n# \n# V obchodě mají 6 druhů barevných hrníčků. \n# - Kolika různými způsoby můžeme koupit 4 různě-barevné hrníčky?\n# - Kolika různými možnostmi můžeme nakoupit 5 hrníčků (pokud nám nevadí více od stejné\n# barvy)?\n# - Jak se situace změní, pokud budou mít od každého pouze 4 kusy (a nám nevadí více\n# stejné barvy)?\n\n\nkombinace(6,4)\nkombinace_opak(6,5)\nkombinace_opak(6,5) - 6\n\n# * Příklad 6. (sbírka kap. 1, př. 7,8) ####\n# \n# Z urny se třemi koulemi, dvěma červenými a jednou bílou, budou současně vybrány dvě\n# koule.\n# Student a učitel uzavřou sázku. Pokud budou obě koule stejné barvy, vyhraje student.\n# Pokud\n# budou mít koule různou barvu, vyhraje učitel. \n# - Je hra férová? Jaké jsou pravděpodobnosti výhry učitele a studenta?\n# - Jakou kouli je třeba přidat, aby hra byla férová?\n\n\nkombinace(3,2)\nkombinace(4,2)\n\n# * Příklad 7. ####\n# \n# V balíčku je 5 různých párů ponožek (levá a pravá ponožka je vždy stejná).\n# - Kolik různých dvojic ponožek lze vybrat?\n# - Kolika různými způsoby se mohu obout? (tj. záleží na tom co je na které noze) \n\n\nkombinace_opak(n = 5,k = 2)\nvariace_opak(n=5,k=2)\nkombinace_opak(n = 5,k = 2)*2 - 5\n\n# * Příklad 8. ####\n# \n# \n# Mám 12 závaží o hmotnostech 1,2,...,12 kg.\n# - Kolika způsoby je mohu rozdělit na 2 hromádky?\n# - Kolika způsoby je mohu rozdělit na 3 hromádky?\n# - Kolika způsoby je mohu rozdělit na 3 hromádky, má-li na všech být stejný počet\n# závaží?\n# - Kolika způsoby je mohu rozdělit na 3 hromádky o stejném počtu závaží, pokud hmotnost\n# žádné z nich nesmí překročit 40 kg? \n\n\nvariace_opak(2,12)\nvariace_opak(3,12)\n(variace_opak(3,12)-3)/permutace(3)+1\n(variace_opak(3,12)-(variace_opak(2,12)-2)*3-3)/permutace(3)\nkombinace(12,4)*kombinace(8,4)/permutace(3)\npermutace(12)/(permutace(4)*permutace(4)*permutace(4)*permutace(3))\nkombinace(12,4)*kombinace(8,4)/permutace(3)-kombinace(8,4)\n\n# * Příklad 9. ####\n# \n# Mám 20 semínek od každého ze tří druhů zeleniny (mrkev, ředkvička, celer). Bohužel se\n# pomíchala.\n# - Do truhlíku zasadím 5 náhodných semínek. Jaká je pravděpodobnost, že mezi nimi budou\n# alespoň tři ředkvičky?\n# - Do truhlíku zasadím 5 náhodných semínek. Jaká je pravděpodobnost, že mezi nimi bude\n# více mrkví než celerů? \n\n\n(kombinace(20,3)*kombinace(40,2)+kombinace(20,4)*kombinace(40,1)+\n kombinace(20,5))/kombinace(60,5)\n\n", "meta": {"hexsha": "f15efb748182cebbeb1232dbb1136ec39fcb2cee", "size": 7395, "ext": "r", "lang": "R", "max_stars_repo_path": "CV1/cv1.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CV1/cv1.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CV1/cv1.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1666666667, "max_line_length": 90, "alphanum_fraction": 0.6631507776, "num_tokens": 3323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122201074846, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7287294024420559}} {"text": "#' Two-sample t-test power calculation\n#' \n#' @param m1 Mean of a group 1 (e.g., the control-group)\n#' @param m2 Mean of a group 2 (e.g., the experimental-group)\n#' @param n1 Number of obs. in group 1 (e.g., the control-group)\n#' @param n2 Number of obs. in group 2 (e.g., the control-group)\n#' @param nratio Ratio of sample sizes, group 2 to group 1; default is nratio = 1, meaning equal group sizes\n#' @param sd Standard deviation of each group, i.e., sd = sd1 = sd2\n#' @param sd1 Standard deviation of a group 1 (e.g., the control group)\n#' @param sd2 Standard deviation of a group 2 (e.g., the experimental group)\n#' @param sig.level significance level; default is sig.level = 0.05\n#' @param power one minus the probability of type II error; default is power = 0.8\n#' @return Returns an object with all the study parameters\n#' @export\n#' @importFrom stats qnorm\n#' @examples\n#' twomeans(m1 = 12, m2 = 16, sd = 5)\ntwomeans <- function(m1 = NULL,\n m2 = NULL,\n n1 = NULL,\n n2 = NULL,\n nratio = NULL,\n sd = NULL,\n sd1 = NULL,\n sd2 = NULL,\n sig.level = 0.05,\n power = 0.80) {\n\n # Validate function\n .check.twomeans(m1,\n m2,\n n1,\n n2,\n nratio,\n sd,\n sd1,\n sd2,\n sig.level,\n power)\n\n # Specify ratio\n if(is.null(nratio)) {\n nratio = 1\n }\n\n # Plug in sd (and sd1/sd2)\n if(!is.null(sd)) {\n sd1 = sd\n sd2 = sd\n }\n\n beta = 1 - power\n\n n1 <- (sd1^2 + (sd2^2) / nratio) *\n (qnorm(1 - sig.level / 2) + qnorm(1 - beta))^2 / ((m1 - m2)^2)\n\n n2 <- nratio * n1\n\n # Round the n's\n n1 <- ceiling(n1)\n n2 <- ceiling(n2)\n\n METHOD = \"Two-sample t-test power calculation\"\n NOTE = paste(\"\",\n \"m1 and m2 are the means of group 1 and 2, respectively.\",\n \"n1 and n2 are the obs. of group 1 and 2, respectively.\",\n sep = \"\\r\\n\")\n\n structure(list(m1 = m1,\n m2 = m2,\n n1 = n1,\n n2 = n2,\n sig.level = sig.level,\n power = power,\n alternative = \"two.sided\",\n method = METHOD,\n note = NOTE), \n class = \"power.htest\")\n\n}\n\n.check.twomeans <- function(m1, m2, n1, n2, nratio, sd, sd1, sd2, sig.level, power) {\n\n # Non-negative standard deviation\n if(any(sd <= 0, sd1 <= 0, sd2 <= 0)) {\n stop(\"sd must be positive\")\n }\n\n # Non-negative observations\n if(any(n1 <= 0, n2 <= 0, nratio <= 0)) {\n stop(\"n1, n2, and nratio must be positive\")\n }\n\n # alpha and power must fall within the interval [0, 1]\n if(any(sig.level < 0, sig.level > 1, power < 0, power > 1)) {\n stop(\"sig.level and power must fall between 0 and 1\")\n }\n\n # Means can't be equal\n if(m1 == m2) {\n stop(\"m1 and m2 cannot be equal\")\n }\n\n # Can't specify sd and (sd1 and sd2)\n if(is.null(sd)) {\n if(any(is.null(sd1), is.null(sd2))) {\n stop(\"must specific either just sd or sd1 and sd2\")\n }\n } else {\n if(any(!is.null(sd1), !is.null(sd2))) {\n stop(\"must specific either just sd or sd1 and sd2\")\n }\n }\n}\n", "meta": {"hexsha": "38f9c362d8e1591358fd200a74a825058a46e09e", "size": 3618, "ext": "r", "lang": "R", "max_stars_repo_path": "R/twomeans.r", "max_stars_repo_name": "MaxGhenis/pwrcalc", "max_stars_repo_head_hexsha": "075416c38c03509f3b0f296d3ae907e5fa9a90f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-04-26T14:31:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T04:38:53.000Z", "max_issues_repo_path": "R/twomeans.r", "max_issues_repo_name": "MaxGhenis/pwrcalc", "max_issues_repo_head_hexsha": "075416c38c03509f3b0f296d3ae907e5fa9a90f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-04-27T01:48:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T22:40:33.000Z", "max_forks_repo_path": "R/twomeans.r", "max_forks_repo_name": "MaxGhenis/pwrcalc", "max_forks_repo_head_hexsha": "075416c38c03509f3b0f296d3ae907e5fa9a90f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-05-02T16:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T08:41:07.000Z", "avg_line_length": 31.4608695652, "max_line_length": 108, "alphanum_fraction": 0.4745715865, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7287189152013418}} {"text": "library(tidyverse)\nlibrary(dplyr)\n\nsetwd(\"/Users/naoki_atkins/Documents/Code/Classwork/dataScience/hw7\")\nload(\"myvec.RData\")\n\nacf(myvec, lag.max = 100)\n\n\nmy_ts <- ts(myvec, frequency = 50)\ndecomp <- decompose(my_ts)\n\nplot(decomp)\n\n\n# Question 3a.\n\ndtw <- function (A, B) {\n M <- nrow(A)\n N <- nrow(B)\n Cost <- matrix(0,M,N) # Initialize with zeros\n # compute cost and fill in the matrix\n for (i in 1:M) {\n for (j in 1:N) {\n Cost[i,j] <- as.numeric((A[i,1] - B[j,1])^2 + (A[i,2] - B[j,2])^2) # distance function\n }\n }\n C <- matrix(0,M,N) # Initialize with zeros\n C[1,1] <- Cost[1,1] # Initialize top left cell\n for (i in 2:M) { # Initialize first column\n C[i,1] <- C[i-1,1] + Cost[i,1]\n }\n for (j in 2:N) { # Initialize first row\n C[1,j] <- C[1,j-1] + Cost[1,j]\n }\n \n # Fill in everything besides the first column and first row\n # Evaluate 3 neighbors (above, left-above, left)\n # Pick the smallest\n # Add the smallest value to ...\n # Fill in the matrix with that computed value\n for(i in 2:M) {\n for(j in 2:N) {\n C[i,j] <- min(C[i-1, j], C[i, j-1], C[i-1, j-1]) + Cost[i,j]\n }\n }\n return (C[M,N])\n}\n\n\n# Question 3b.\nA.x <- c(2, 0, 2, 4, 5)\nA.y <- c(2, 4, 6, 5, 2)\n\nA <- matrix(data = c(A.x, A.y), nrow = 5)\n\nB.x <- c(1, 0, 4, 5)\nB.y <- c(1, 6, 4, 1)\n\nB <- matrix(data = c(B.x, B.y), nrow = 4)\n\ndtw(A, B)\n\n# Question 4\n\ntsX <- read_csv(\"tsX.csv\")\nts2 <- read_csv(\"ts2.csv\")\nts3 <- read_csv(\"ts3.csv\")\nts4 <- read_csv(\"ts4.csv\")\nts5 <- read_csv(\"ts5.csv\")\n\n# 44116.78\ndtw(tsX, ts2)\n# 18583.75\ndtw(tsX, ts3)\n# 13293.01\ndtw(tsX, ts4)\n# 3192.354\ndtw(tsX, ts5)\n\n\n\ntsX %>%\n ggplot(aes(tsX$x, tsX$y)) + \n geom_path()\n\nts2 %>%\n ggplot(aes(ts2$x, ts2$y)) + \n geom_path()\n\nts3 %>%\n ggplot(aes(ts3$x, ts3$y)) + \n geom_path()\n\nts4 %>%\n ggplot(aes(ts4$x, ts4$y)) + \n geom_path()\n\nts5 %>%\n ggplot(aes(ts5$x, ts5$y)) + \n geom_path()\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "27be512c53a689d91ac2d416cf5e8882271c83ee", "size": 1884, "ext": "r", "lang": "R", "max_stars_repo_path": "dataScience/hw7/hw7.r", "max_stars_repo_name": "naokishami/Classwork", "max_stars_repo_head_hexsha": "ac59d640f15e88294804fdb518b6c84b10e0d2bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dataScience/hw7/hw7.r", "max_issues_repo_name": "naokishami/Classwork", "max_issues_repo_head_hexsha": "ac59d640f15e88294804fdb518b6c84b10e0d2bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dataScience/hw7/hw7.r", "max_forks_repo_name": "naokishami/Classwork", "max_forks_repo_head_hexsha": "ac59d640f15e88294804fdb518b6c84b10e0d2bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1272727273, "max_line_length": 92, "alphanum_fraction": 0.5642250531, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242132, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7285552641343024}} {"text": "# PSI function\n# Reference: P395, Credit risk analytics - Measurement technique, applications and examples\n# Rules of thumb\n# PSI < 0.10: no significant shift (green traffic light)\n# 0.10 ≤ PSI < 0.25: moderate shift (yellow traffic light)\n# PSI ≥ 0.25: significant shift (red traffic light)\nlibrary(tidyverse)\n\n# Hàm tính PSI cho từng biến\n\npsi <- function(actual, expected){\n \n tbl <- list(actual = actual, expected = expected) %>% \n # map(factor, levels = lbl, labels = lbl) %>% \n map(table) %>% \n map(prop.table) %>% \n map(as.data.frame, stringsAsFactors=FALSE) %>% \n reduce(full_join, by = \"Var1\") %>% \n mutate(sub_psi = (Freq.x-Freq.y)*(log(Freq.x)-log(Freq.y))) %>% \n mutate(psi = sum(sub_psi)) %>% \n select(Range = Var1, \n Trainning = Freq.y, \n Actual = Freq.x, \n psi) %>% \n mutate(Trainning = paste0(round(Trainning * 100, 1), \"%\"),\n Actual = paste0(round(Actual * 100, 1), \"%\"),\n psi = round(psi, 3),\n tag = case_when(psi < 0.1 ~ \"green\", \n psi < 0.25 ~ \"yellow\", \n TRUE ~ \"red\"))\n \n \n return(tbl)\n}\n\n# Hàm tính PSI cho cả bộ dữ liệu\npsi_df <- function(dat_train, dat_test, var_skip = NULL){\n same_name <- names(dat_test) %>%\n intersect(names(dat_train)) %>%\n setdiff(var_skip)\n \n sl <- function(x){\n psi(expected = dat_train[[x]], actual = dat_test[[x]]) %>% return()\n }\n \n same_name %>% \n set_names(same_name) %>% \n map_dfr(sl, .id = \"Variables\") %>% \n return()\n \n}\n", "meta": {"hexsha": "763b6fd83c2794e0dbbc22b6b23c0865a4a72544", "size": 1549, "ext": "r", "lang": "R", "max_stars_repo_path": "R/psi.r", "max_stars_repo_name": "nguyenngocbinh/scorecard.bml", "max_stars_repo_head_hexsha": "65c47e344ac6bd0e39c46e5be46c081ee1461796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/psi.r", "max_issues_repo_name": "nguyenngocbinh/scorecard.bml", "max_issues_repo_head_hexsha": "65c47e344ac6bd0e39c46e5be46c081ee1461796", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/psi.r", "max_forks_repo_name": "nguyenngocbinh/scorecard.bml", "max_forks_repo_head_hexsha": "65c47e344ac6bd0e39c46e5be46c081ee1461796", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7884615385, "max_line_length": 91, "alphanum_fraction": 0.5661717237, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.728533436713989}} {"text": "# Barometric formula\n# https://en.wikipedia.org/wiki/Barometric_formula\n# Ideal law: P = rho * R/M * T\n# See also:\n# * https://physics.stackexchange.com/questions/532903/air-pressure-dependence-on-temperature\n# * https://en.wikipedia.org/wiki/Density_of_air\n\ng0 <- 9.80665 # m/s2 -- gravitational acceleration\nR <- 8.3144598 # J/(mol·K) -- universal gas constant\nM <- 0.0289644 # kg/mol -- molar mass of Earth's air\nM_v <- 0.018016 # kg/mol -- molar mass of water vapor\n\n# Constants taken from Barometric formula\n# https://en.wikipedia.org/wiki/Barometric_formula\n# for altitude between 0 and 11 km.\n\nh_b <- 0 # m\nP_b <- 101325.00 # Pa\nT_b <- 288.15 # K\nL_b <- -0.0065 # K/m\nrho_b <- 1.2250 # kg/m3\n\n# This function computes the pressure in function of altitude.\n# LR stands for lapse rate: the drop in temperature in function of altitude is\n# here taken into consideration. For altitude between 0 and 11 km, the drop\n# in temperature is taken as a linear function: T = T_b + L_b*h.\n# See: https://en.wikipedia.org/wiki/Barometric_formula#Derivation\n# Other assumption here is that the air pressure is hydrostatic (i.e. \"fluid\" is not moving).\nP.lr <- function(h.meters) {\n base <- T_b / (T_b + L_b * (h.meters - h_b))\n exp <- g0 * M / (R * L_b)\n P_b * base^exp\n}\n\nP.lr(10)\n\n# PRESSURE\n# Here I define a few pressure conversion functions.\n\nP.cmH2O_to_Pa <- gwloggeR.data:::P.cmH2O_to_Pa\n\nP.Pa_to_cmH2O <- gwloggeR.data:::P.Pa_to_cmH2O\n\nP.Pa_to_cmH2O(P.lr(0))\nP.Pa_to_cmH2O(P.lr(100))\n\n# Conclusion here is that the drop in air pressure is expected to drop per 100 m:\nP.Pa_to_cmH2O(P.lr(0)) - P.Pa_to_cmH2O(P.lr(100))\n\ncurve(P.Pa_to_cmH2O(P.lr(x)), xlim = c(0, 11000), xlab = 'Altitude (m)', ylab = 'Air pressure (cmH2O)')\n\n# DENSITY\n# This is the same as P.lr, but for the density.\n# Not important I think.\n\n# rho.lr <- function(h.meters) {\n# base <- T_b / (T_b + L_b * (h.meters - h_b))\n# exp <- 1 + g0 * M / (R * L_b)\n# rho_b * base^exp\n# }\n#\n# rho.lr(0)\n# rho.lr(100)\n#\n# curve(rho.lr(x), xlim = c(0, 11000))\n\n# TEMPERATURE EFFECT\n\n# This is a very naive calculation of temperature effect based on the ideal law\n# because the density of air is assumed not to change in function of temperature.\nP.Pa_to_cmH2O(rho_b*R/M*(T_b + 1) - rho_b*R/M*T_b)\n\n## TEMPERATURE EFFECT ON DENSITY OF DRY AIR\n\n# Here we focus on the following:\n# https://en.wikipedia.org/wiki/Density_of_air\n\n# This function computes the density (rho) of air based on the assumption of\n# dry air.\nrho_da <- function(temp.K) {\n P_b*M/(R*temp.K)\n}\n\nrho_da(T_b)\nrho_da(15 + 273.15) # 15 °C\nrho_da(20 + 273.15)\n\n# Less naive calculation of temperature effect assuming dry air.\nP.Pa_to_cmH2O(rho_da(T_b + 1)*R/M*(T_b + 1) - rho_da(T_b)*R/M*T_b)\n\n## TEMPERATURE EFFECT ON DENSITY OF HUMID AIR\n\n# Saturation vapor pressure\n# See: https://en.wikipedia.org/wiki/Vapour_pressure_of_water\n# The Buck equation is the best one.\n\nP_sat.Pa <- function(temp.K, type = c('Buck', 'Tetens')) {\n type <- match.arg(type)\n temp.C <- temp.K - 273.15\n switch (type,\n 'Buck' = 0.61121*exp( (18.678 - temp.C/234.5)*(temp.C/(257.14 + temp.C)) ),\n 'Tetens' = 0.61078*exp(17.2*temp.C/(temp.C + 237.3))\n )\n}\n\nP_sat.Pa(T_b)\nP_sat.Pa(T_b, type = 'Tetens')\n\n# This function computes the density (rho) of air based on the assumption of\n# humid air.\n\nrho_ha <- function(temp.K, humidity.perc) {\n P_v <- humidity.perc/100 * P_sat.Pa(temp.K)\n P_d <- P_b - P_v\n\n (P_d*M + P_v*M_v)/(R*temp.K)\n}\n\nrho_da(T_b)\nrho_ha(T_b, 0)\nrho_ha(T_b, 100)\n\n# Less naive calculation of temperature effect assuming humid air.\nP.Pa_to_cmH2O(rho_ha(T_b + 1, 90)*R/M*(T_b + 1) - rho_ha(T_b, 90)*R/M*T_b)\n\n# HUMIDITY\n# The bulge during non-summer can not be explained by drop in air pressure density.\n# https://nl.wikipedia.org/wiki/Relatieve_luchtvochtigheid#Relatieve_luchtvochtigheid_en_klimaat\nP.Pa_to_cmH2O(rho_ha(T_b, 75)*R/M*T_b - rho_ha(T_b, 90)*R/M*T_b)\n", "meta": {"hexsha": "018713df9e32a656870c4ea40075919785b8e7b1", "size": 3892, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/drifts/analysis_07.r", "max_stars_repo_name": "DOV-Vlaanderen/groundwater-logger-validation", "max_stars_repo_head_hexsha": "db9bd59c1644bb298206e717a528b4974e3939d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-16T10:47:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T10:47:56.000Z", "max_issues_repo_path": "src/r/drifts/analysis_07.r", "max_issues_repo_name": "DOV-Vlaanderen/groundwater-logger-validation", "max_issues_repo_head_hexsha": "db9bd59c1644bb298206e717a528b4974e3939d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 61, "max_issues_repo_issues_event_min_datetime": "2019-05-17T21:14:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T13:47:40.000Z", "max_forks_repo_path": "src/r/drifts/analysis_07.r", "max_forks_repo_name": "DOV-Vlaanderen/groundwater-logger-validation", "max_forks_repo_head_hexsha": "db9bd59c1644bb298206e717a528b4974e3939d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-30T10:39:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T10:48:04.000Z", "avg_line_length": 29.9384615385, "max_line_length": 103, "alphanum_fraction": 0.6891058582, "num_tokens": 1337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7284521560886141}} {"text": "=begin\n # sample-geometry01.rb\n\n require 'algebra'\r\n R = MPolynomial(Rational)\r\n x,y,a1,a2,b1,b2,c1,c2 = R.vars('xya1a2b1b2c1c2')\r\n \r\n V = Vector(R, 2)\r\n X, A, B, C = V[x,y], V[a1,a2], V[b1,b2], V[c1,c2]\r\n \r\n D = (B + C) /2\r\n E = (C + A) /2\r\n F = (A + B) /2\r\n \r\n def line(p1, p2, p3)\r\n SquareMatrix.det([[1, *p1], [1, *p2], [1, *p3]])\r\n end\r\n \r\n l1 = line(X, A, D)\r\n l2 = line(X, B, E)\r\n l3 = line(X, C, F)\r\n s = line(A, B, C)\r\n \r\n g = Groebner.basis [l1, l2, l3, s-1] #s-1 means non degeneracy\r\n \r\n g.each_with_index do |f, i|\r\n p f\r\n end\r\n #x - 1/3a1 - 1/3b1 - 1/3c1\r\n #y - 1/3a2 - 1/3b2 - 1/3c2\r\n #a1b2 - a1c2 - a2b1 + a2c1 + b1c2 - b2c1 - 1\r\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "cc55451336edb84706cf6ca0cae402aebdbb8936", "size": 701, "ext": "rd", "lang": "R", "max_stars_repo_path": "work/consider/algebra-0.72/doc/sample-geometry01.rb.v.rd", "max_stars_repo_name": "rubyworks/stick", "max_stars_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-04-24T05:51:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-24T05:51:21.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-geometry01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "work/consider/algebra-0.72/doc/sample-geometry01.rb.v.rd", "max_forks_repo_name": "rubyworks/stick", "max_forks_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6176470588, "max_line_length": 65, "alphanum_fraction": 0.482168331, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.728293888162858}} {"text": "#autor: Joao Sollari Lopes\n#local: INE, Lisboa\n#Rversion: 3.6.1\n#criado: 02.07.2017\n#modificado: 06.12.2019\n\nlibrary(\"e1071\")\n\n##1. Linear SVM Classifier\n#[adapted from https://www.datacamp.com/community/tutorials/support-vector-machines-r]\nset.seed(12345)\nn1 <- 10\ny1 <- rnorm(n1,mean=0,sd=1)\nx1 <- rnorm(n1,mean=0,sd=1)\nn2 <- 10\ny2 <- rnorm(n2,mean=0,sd=1) + 1\nx2 <- rnorm(n2,mean=0,sd=1) + 1\n\ndat1 <- data.frame(stringsAsFactors=FALSE,\n y=c(y1,y2),\n x=c(x1,x2),\n grp=c(rep(\"blue\",n1),rep(\"red\",n2)))\n\nfnam <- \"../images/svm_1.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\npar(mar=c(3,2.5,1.5,0.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(dat1,plot(x,y,col=grp,pch=19))\ndev.off()\n\nmodfit <- svm(grp ~ .,\n dat1,\n scale=FALSE, #scaling stored for testing\n type=\"C-classification\", #SVM algorithm\n kernel=\"linear\", #kernel type\n cost=1.0, #C-constant (cost)\n tolerance=0.001) #convergence epsilon\n\n#beta_0 + beta_1*x + beta_2*y = 0\n#y = -(beta_1/beta_2)*x - (beta_0/beta_2)\nbeta_0 = -modfit$rho\nbeta_1 = t(modfit$coefs)%*%dat1$x[modfit$index]\nbeta_2 = t(modfit$coefs)%*%dat1$y[modfit$index]\n\ngrid1 <- expand.grid(\n x = seq(min(dat1$x),max(dat1$x),length=100),\n y = seq(min(dat1$y),max(dat1$y),length=100))\ngrid1$grp <- as.character(predict(modfit,grid1))\n\nfnam <- \"../images/svm_2.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\npar(mar=c(3,2.5,1.5,0.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(grid1,plot(x,y,col=grp,pch=19,cex=0.2))\nwith(dat1,points(x,y,col=grp,pch=19))\nabline(a=-beta_0/beta_2,b=-beta_1/beta_2)\ndev.off()\n\n##2. Non-linear SVM Classifier\nset.seed(12345)\nn1 <- 30\nrad1 <- sqrt(runif(n1,1,2))\nthe1 <- runif(n1,0,2*pi)\nx1 <- rad1*cos(the1)\ny1 <- rad1*sin(the1)\nn2 <- 30\nrad2 <- sqrt(runif(n2,0,1))\nthe2 <- runif(n2,0,2*pi)\nx2 <- rad2*cos(the2)\ny2 <- rad2*sin(the2)\n\ndat1 <- data.frame(stringsAsFactors=FALSE,\n x=c(x1,x2),\n y=c(y1,y2),\n grp=c(rep(\"blue\",n1),rep(\"red\",n2)))\n\nfnam <- \"../images/svm_3.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\npar(mar=c(3.0,3.0,1.5,1.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(dat1,plot(x,y,col=grp,pch=19))\ndev.off()\n\ndat1$z <- dat1$x^2 + dat1$y^2\n\nfnam <- \"../images/svm_4.tiff\"\ntiff(file=fnam,units=\"in\",width=8,height=4,res=300,compression=\"lzw\")\npar(mfcol=c(1,2),mar=c(3,2.5,1.5,0.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(dat1,plot(x,z,col=grp,pch=19))\nwith(dat1,plot(y,z,col=grp,pch=19))\ndev.off()\n\nfnam <- \"../images/svm_5.tiff\"\ntiff(file=fnam,units=\"in\",width=8,height=4,res=300,compression=\"lzw\")\npar(mfcol=c(1,2),mar=c(3,2.5,1.5,0.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(dat1,plot(x,z,col=grp,pch=19))\nabline(h=1)\nwith(dat1,plot(y,z,col=grp,pch=19))\nabline(h=1)\ndev.off()\n\nfnam <- \"../images/svm_6.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\npar(mar=c(3.0,3.0,1.5,1.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(dat1,plot(x,y,col=grp,pch=19))\nradius <- 1\ntheta <- seq(0,2*pi,length=200)\nlines(x=radius*cos(theta),y=radius*sin(theta))\ndev.off()\n\nmodfit <- svm(grp ~ x + y,\n dat1,\n scale=FALSE, #scaling stored for testing\n type=\"C-classification\", #SVM algorithm\n kernel=\"radial\", #kernel type\n gamma=0.5, #kernel gamma\n cost=1.0, #C-constant (cost)\n tolerance=0.001, #convergence epsilon\n epsilon=0.1) #loss-function epsilon\n\ngrid1 <- expand.grid(\n x = seq(min(dat1$x),max(dat1$x),length=100),\n y = seq(min(dat1$y),max(dat1$y),length=100))\ngrid1$grp <- as.character(predict(modfit,grid1))\n\nfnam <- \"../images/svm_7.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\npar(mar=c(3.0,3.0,1.5,1.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(grid1,plot(x,y,col=grp,pch=19,cex=0.2))\nwith(dat1,points(x,y,col=grp,pch=19))\nradius <- 1\ntheta <- seq(0,2*pi,length=200)\nlines(x=radius*cos(theta),y=radius*sin(theta))\ndev.off()\n\n##3. Linear SVM Regression\n\n## 2. Model Fitting\nset.seed(12345)\n\nreal_a1 <- 1.5\nreal_a2 <- 4\nx <- runif(n=30,min=0,max=10)\ny <- real_a1*x + real_a2 + rnorm(n=30,mean=0,sd=1)\ndat1 <- data.frame(x,y)\n\nfnam <- \"../images/svm_7.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\npar(mar=c(3,2.5,1.5,0.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(dat1,plot(x,y,pch=19))\ndev.off()\n\nmodfit <- svm(y ~ x,\n dat1,\n scale=FALSE, #scaling stored for testing\n type=\"eps-regression\", #SVM algorithm\n kernel=\"linear\", #kernel type\n tolerance=0.001, #convergence epsilon\n epsilon=0.5) #loss-function epsilon\n\n#y = beta_1*x + beta_0\nbeta_0 = -modfit$rho\nbeta_1 = t(modfit$coefs)%*%dat1$x[modfit$index]\n\nfnam <- \"../images/svm_8.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\npar(mar=c(3,2.5,1.5,0.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(dat1,plot(x,y,pch=19))\nabline(a=beta_0,b=beta_1,col=\"blue\")\nabline(a=beta_0 - 0.5,b=beta_1,lty=2,col=\"blue\")\nabline(a=beta_0 + 0.5,b=beta_1,lty=2,col=\"blue\")\ndev.off()\n\nlmfit <- lm(y ~ x,data=dat1)\na1 <- lmfit$coef[1]\na2 <- lmfit$coef[2]\n\nfnam <- \"../images/svm_9.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\npar(mar=c(3,2.5,1.5,0.5),mgp=c(1.7,0.7,0),cex=0.8)\nwith(dat1,plot(x,y,pch=19))\nabline(a=a1,b=a2,lwd=2,col=\"red\")\nabline(a=beta_0,b=beta_1,col=\"blue\")\nabline(a=beta_0 - 0.5,b=beta_1,lty=2,col=\"blue\")\nabline(a=beta_0 + 0.5,b=beta_1,lty=2,col=\"blue\")\ndev.off()\n", "meta": {"hexsha": "f50f707a7d1c8fae89c96c38a6657273554d0f59", "size": 5640, "ext": "r", "lang": "R", "max_stars_repo_path": "bin/pic_svm.r", "max_stars_repo_name": "jsollari/DAA2019", "max_stars_repo_head_hexsha": "6b4e0764f6570bef4652a73a773f3b9ee8af92da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/pic_svm.r", "max_issues_repo_name": "jsollari/DAA2019", "max_issues_repo_head_hexsha": "6b4e0764f6570bef4652a73a773f3b9ee8af92da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/pic_svm.r", "max_forks_repo_name": "jsollari/DAA2019", "max_forks_repo_head_hexsha": "6b4e0764f6570bef4652a73a773f3b9ee8af92da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-17T11:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T11:11:10.000Z", "avg_line_length": 30.652173913, "max_line_length": 86, "alphanum_fraction": 0.615248227, "num_tokens": 2309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7282548574954695}} {"text": "#------------------#\n# Forecasting\n#------------------#\nrm(list=ls(all.names=TRUE))\n#------------------#\nlibrary(dplyr)\nlibrary(tidyr)\ninstall.packages(\"skimr\")\nlibrary(skimr)\nlibrary(stats)\nlibrary(MASS)\nlibrary(ggplot2)\n#------------------#\n#-------------------------#\n# Load data\n#-------------------------#\ndm <- readr::read_csv(\"demand_data.txt\")\n\n# Add time trend\ndm <- dm %>%\n mutate(t = row_number()) %>%\n as_tibble()\n\n# Descriptives\nsummary(dm)\nskim(dm)\nhead(dm, 5)\n\n#-------------------------#\n# Visualize\n#-------------------------#\nhist(dm$demand)\n\ndm %>%\n ggplot(aes(x = demand)) +\n geom_histogram()\n\ndm %>%\n ggplot(aes(x = t, y = demand)) +\n geom_line()\n#-------------------------#\n# Setting\n#-------------------------#\n#The price is $4, the unit cost is $0.80, and the salvage value is $0. \nprice <- 4\ncost <- 0.8\nsalvage <- 0\n\n# What we know\nsl<-(price - cost) / (price - salvage) # target service level\noptimal_order_quantity <- as.integer(quantile(dm$demand, sl))\n\n# Splitting the sample\ndm1 <- dm[1:100,]\ndm2 <- dm[101:300,] # forecast, calculate forecasting_error\ndm3 <- dm[301:500,]\n\n# Make table for summary\nres_table <- data.frame(\n method = c(\"wo prediction\",\n \"moving average\",\n \"simple_exp_wo_tuning\", \"simple_exp_w_tuning\",\n \"holt_wo_tuning\", \"holt_w_tuning\"),\n AvgProf = rep(0, 6)\n)\n\ndm3 %>%\n ggplot(aes(x = demand)) +\n geom_histogram()\n\n#-------------------------#\n# Find the optimal quantity using simulation with the full data\n# (we can save time by using optimization methods)\n#-------------------------#\n\n# Prepare grid\nstocking <- c(min(dm$demand):max(dm$demand))\n\n# Calculate\nprofit <- matrix(0, nrow = nrow(dm), ncol = length(stocking))\nfor (i in 1:length(stocking)) { # loop for each stocking level\n q <- stocking[i]\n \n for (j in 1:nrow(dm)) { # loop for each realized demand\n profit[j,i] <- price * min(q, dm$demand[j]) + salvage * max(q - dm$demand[j], 0) - cost * q\n }\n}\n# make summary table\nsummary_table <- data.frame(\n stocking = stocking,\n AvgProf = apply(profit, 2, mean), # column means\n StdProf = apply(profit, 2, sd) # column sd\n)\nsummary_table %>%\n as_tibble() %>%\n arrange(desc(AvgProf)) %>%\n head(1)\n\n# This is going to be the (approx.) same as the following value\nquantile(dm$demand, 0.80)\n\noptimal_profit <- max(summary_table$AvgProf)\noptimal_profit\n\noptimal_stocking <- summary_table %>%\n as_tibble() %>%\n arrange(desc(AvgProf)) %>%\n head(1) %>%\n dplyr::select(stocking)\noptimal_stocking\n\n# Again, this value is going to be the (approx.) same as the following calculation\nmean(price * pmin(optimal_order_quantity, dm$demand) - cost * optimal_order_quantity)\n\n# Value of an oracle\n(price - cost) * mean(dm$demand) - optimal_profit\n\n# Safety Stock\nsafety_stock <- optimal_stocking - mean(dm$demand)\nprint(safety_stock)\n\n#-------------------------#\n# Find the optimal quantity using simulation only for df3\n# (we can save time by using optimization methods)\n#-------------------------#\n# Prepare grid\nstocking <- c(min(dm3$demand):max(dm3$demand))\n# Calculate\nprofit <- matrix(0, nrow = nrow(dm3), ncol = length(stocking))\nfor (i in 1:length(stocking)) { # loop for each stocking level\n q <- stocking[i]\n \n for (j in 1:nrow(dm3)) { # loop for each realized demand\n profit[j,i] <- price * min(q, dm3$demand[j]) + salvage * max(q - dm3$demand[j], 0) - cost * q\n }\n}\n# make summary table\nsummary_table <- data.frame(\n stocking = stocking,\n AvgProf = apply(profit, 2, mean), # column means\n StdProf = apply(profit, 2, sd) # column sd\n)\nsummary_table %>%\n as_tibble() %>%\n arrange(desc(AvgProf)) %>%\n head(1)\n\n# This is going to be the (approx.) same as the following value\nquantile(dm3$demand, 0.80)\n\noptimal_profit <- max(summary_table$AvgProf)\noptimal_profit\n\noptimal_stocking <- summary_table %>%\n as_tibble() %>%\n arrange(desc(AvgProf)) %>%\n head(1) %>%\n dplyr::select(stocking) %>%\n as.numeric()\n\n# Again, this value is going to be the (approx.) same as the following calculation\nres_table$AvgProf[1] <- mean(price * pmin(optimal_stocking, dm3$demand) - cost * optimal_stocking)\n\n# Value of an oracle\n(price - cost) * mean(dm3$demand) - optimal_profit\n\n# Safety Stock\nsafety_stock <- optimal_stocking - mean(dm3$demand)\nprint(safety_stock)\n\n#---------------------------------------------------------------------------#\n# Forecasting\n#---------------------------------------------------------------------------#\n# forecast for 301 --> use moving average, e.g., (D[300]+D[299]+D[298]+D[297])/4\n# then, at day 301, what should be the stocking level?\n# it would be: forecast + safety stock.\n# then, what is the safety stock?\n# Need to forecast forecasting errors:\n# Forecast forecast error distribution using the forecast error from day 101 to 300\n# Now, knowing the forecast error distribution --> Take the 80th percentile of the forecast error distribution.\n# then: stocking = forecast + 80th_percentile of forecast_error\n\n#-------------------------#\n# method 1. moving average\n#-------------------------#\n# Forecast demand of df2 using df1\nforecast <- c()\nfor (i in 1:nrow(dm2)) {\n # forecast by the last four days\n last_four_values <- c(dm$demand[(100+i-1)-3], dm$demand[(100+i-1)-2], dm$demand[(100+i-1)-1], dm$demand[(100+i-1)-0])\n forecast[i] <- mean(last_four_values)\n}\n\n# calculate stocking values using predicted forecast error in df2\nforecasting_error <- dm2$demand - forecast\nhist(forecasting_error)\n\nsafety_stock <- quantile(forecasting_error, 0.80)\nstocking <- forecast + safety_stock\n\n# for the remaining days 301-- 500: repeat the process\n# Note that in this case, forecast changes, but safety stock remains the same\n# For the third split sample: we would like to calculate the average daily profit, if we use the moving average forecasting method\nforecast_301_500 <- c()\nfor (i in 1:nrow(dm3)) {\n # forecast by the last four days\n last_four_values <- c(dm$demand[(300+i-1)-3], dm$demand[(300+i-1)-2], dm$demand[(300+i-1)-1], dm$demand[(300+i-1)-0])\n forecast_301_500[i] <- mean(last_four_values)\n}\n\nstocking_301_500 <- forecast_301_500 + safety_stock # we use safety_stock obtained from df2\n\n# Average profit\nres_table$AvgProf[2] <- mean(price * pmin(stocking_301_500, dm3$demand) + salvage * pmax(stocking_301_500 - dm3$demand, 0) - cost * stocking_301_500)\n\n# Oracle\n(price - cost) * mean(dm3$demand)\n\n#-------------------------#\n# method 2. simple exponential smoothing\n# It starts from week 101\n#-------------------------#\n# start from arbitrary number\nalpha = 0.2\n\nforecast_101_300 <- c()\nfor (i in 1:(300-101+1)) {\n if (i == 1){\n forecast_101_300[1] <- mean(dm1$demand)\n } else {\n # update the forecast with alpha\n forecast_101_300[i] <- alpha * dm$demand[100+i-1] + (1 - alpha) * forecast_101_300[i-1]\n }\n}\n\nforecast_error_simple_expo_smooth <- dm2$demand - forecast_101_300\nhist(forecast_error_simple_expo_smooth)\n\nsafety_stock <- quantile(forecast_error_simple_expo_smooth, 0.80)\nstocking <- forecast_101_300 + safety_stock\n\n# for the remaining days 301-- 500: repeat the process\n# Note that in this case, forecast changes, but safety stock remains the same\nforecast_301_500 <- c()\nfor (i in 1:(300-101+1)) {\n if (i == 1){\n forecast_301_500[1] <- mean(dm$demand[1:300])\n } else {\n # update the forecast with alpha\n forecast_301_500[i] <- alpha * dm$demand[300+i-1] + (1 - alpha) * forecast_301_500[i-1]\n }\n}\n\nstocking_301_500 <- forecast_301_500 + safety_stock # we use safety_stock obtained from df2\n\n# Average profit\nres_table$AvgProf[3] <- mean(price * pmin(stocking_301_500, dm3$demand) + salvage * pmax(stocking_301_500 - dm3$demand, 0) - cost * stocking_301_500)\n\n## finding optimal alpha\nmse_simple_exponential_smoothing <- function(alpha, actual_demand) {\n forecast_101_300 <- c()\n for (i in 1:(300-101+1)) {\n if (i == 1){\n forecast_101_300[1] <- mean(dm1$demand)\n } else {\n # update the forecast with alpha\n forecast_101_300[i] <- alpha * dm$demand[100+i-1] + (1 - alpha) * forecast_101_300[i-1]\n }\n }\n \n mse <- sum((actual_demand - forecast_101_300)^2) / length(actual_demand)\n return(mse)\n}\n\nres <- optim(0.2, mse_simple_exponential_smoothing, method = \"L-BFGS-B\",\n actual_demand = dm2$demand,\n lower = c(0),\n upper = c(1))\n## Note: bisection might be more appropriate here (https://urldefense.com/v3/__https://rpubs.com/aaronsc32/bisection-method-r__;!!Mih3wA!WKo4McW-7-dzrHSo51O5DuRNZsZC4YkYFqeXfDfe2Jlu5bLOewZdY1wOa_2w8g$ )\n## There are many ways/solvers to do this, but I just sticked with the very basic.\n\n# use the tuned values\nalpha <- res$par\n\nforecast_101_300_with_optim_alpha <- c()\nfor (i in 1:(300-101+1)) {\n if (i == 1){\n forecast_101_300_with_optim_alpha[1] <- mean(dm1$demand)\n } else {\n # update the forecast with alpha\n forecast_101_300_with_optim_alpha[i] <- alpha * dm$demand[100+i-1] + (1 - alpha) * forecast_101_300_with_optim_alpha[i-1]\n }\n}\n\nforecast_error_simple_expo_smooth <- dm2$demand - forecast_101_300_with_optim_alpha\nhist(forecast_error_simple_expo_smooth)\n\nsafety_stock <- quantile(forecast_error_simple_expo_smooth, 0.80)\nstocking <- forecast_101_300_with_optim_alpha + safety_stock\n\n# for the remaining days 301-- 500: repeat the process\n# Note that in this case, forecast changes, but safety stock remains the same\nforecast_301_500 <- c()\nfor (i in 1:(500-301+1)) {\n if (i == 1){\n forecast_301_500[1] <- forecast_101_300[200]\n } else {\n # update the forecast with alpha\n forecast_301_500[i] <- alpha * dm$demand[300+i-1] + (1 - alpha) * forecast_301_500[i-1]\n }\n}\n\nstocking_301_500 <- forecast_301_500 + safety_stock # we use safety_stock obtained from df2\n\n# Average profit\nres_table$AvgProf[4] <- mean(price * pmin(stocking_301_500, dm3$demand) + salvage * pmax(stocking_301_500 - dm3$demand, 0) - cost * stocking_301_500)\n\n# Another Objective Function (Maximizing Average profit to find tuning parameters)\n#101_300: Average_profit\n## finding optimal alpha\nAveProf_simple_exponential_smoothing <- function(alpha, df, price, salvage, cost) {\n forecast_101_300 <- c()\n for (i in 1:(300-101+1)) {\n if (i == 1){\n forecast_101_300[1] <- mean(dm$demand[1:100])\n } else {\n # update the forecast with alpha\n forecast_101_300[i] <- alpha * dm$demand[100+i-1] + (1 - alpha) * forecast_101_300[i-1]\n }\n }\n \n forecast_error_simple_expo_smooth <- dm$demand[101:300] - forecast_101_300\n \n safety_stock <- quantile(forecast_error_simple_expo_smooth, 0.80)\n stocking_101_300 <- forecast_101_300 + safety_stock\n \n # Average profit\n AvgProf <- mean(price * pmin(stocking_101_300, dm$demand[101:300]) + salvage * pmax(stocking_101_300 - dm$demand[101:300], 0) - cost * stocking_101_300)\n \n print(-AvgProf)\n return(-AvgProf) # don't forget to put negative sign as we want to maximize.\n}\n\nres <- optim(0.5, AveProf_simple_exponential_smoothing, method = \"L-BFGS-B\",\n df = df,\n lower = c(0),\n upper = c(1),\n price = price,\n salvage = salvage,\n cost = cost)\n\nres$par\n#0.01822693\n\n#-------------------------#\n# method 3. Trend-Corrected Exponential Smoothing (Holt’s Model)\n#-------------------------#\n#Step 1. Use the data from Week1 to Week300 to estimate \n#the slope “a” in time (t) and the intercept “b” from the linear regression model.\n\n#Dt = at + b\nmodel <- lm(dm$demand[1:300] ~ dm$t[1:300])\na <- coefficients(model)[2]\nb <- coefficients(model)[1]\n\n\n#Step 2. Use L0=b and T0=a from the above linear regression. \n#Use alpha=0.2 and beta=0.2. Estimate the forecast from Week1 to Week 500.\n\n#Ft+1 = Lt + Tt\n#L2 = aD2 + (1-a)(L1+T1)\n#t2 = b(L2 - L1)+(1-b)T1\n\nalpha <- 0.2\nbeta <- 0.2\nlevel <- b\ntrend <- a\n\nforecast_1_500 <- c()\nfor (i in 1:500) {\n forecast_1_500[i] <- trend + level\n # update the forecast with alpha and beta\n level <- alpha * dm$demand[i] + (1 - alpha) * forecast_1_500[i]\n trend <- beta * (level - (forecast_1_500[i] - trend)) + (1 - beta) * trend\n}\n\n#Step 3. What is the stocking quantity at Week301?\nforecast_error_holt <- dm$demand[101:300] - forecast_1_500[101:300]\nhist(forecast_error_holt)\nsafety_stock <- quantile(forecast_error_holt, 0.80)\n\nstocking_301_500 <- forecast_1_500[301:500] + safety_stock # I use safety_stock obtained from df2\n\nstocking_301_500[1] #stocking quantity at Week301 is 3735.754\n\n#Step 4. What is the weekly average profit from Week301 to Week500? \n\nres_table$AvgProf[5] <- mean(price * pmin(stocking_301_500, dm3$demand) + salvage * pmax(stocking_301_500 - dm3$demand, 0) - cost * stocking_301_500)\n\n#Do you see an improvement over simple Exponential Smoothing?\n#No\n#5. Use the data from Week1 to Week300 to find an “optimal” alpha and beta values.\n\n## finding optimal alpha & beta using MSE method\na <- coefficients(model)[2]\nb <- coefficients(model)[1]\n\n\nmse_holt <- function(p, actual_demand) {\n alpha <- p[1]\n beta <- p[2]\n level <- b\n trend <- a\n \n forecast_1_500 <- c()\n for (i in 1:500) {\n forecast_1_500[i] <- trend + level\n # update the forecast with alpha and beta\n level <- alpha * dm$demand[i] + (1 - alpha) * forecast_1_500[i]\n trend <- beta * (level - (forecast_1_500[i] - trend)) + (1 - beta) * trend\n }\n mse <- sum((actual_demand - forecast_1_500[101:300])^2) / length(actual_demand)\n return(mse)\n}\n\nres <- optim(c(0.2, 0.2), mse_holt, method = \"L-BFGS-B\",\n actual_demand = dm$demand[101:300],\n lower = c(0, 0),\n upper = c(10, 10))\nprint(\"Optimal alpha and beta using MSE method:\")\nprint(res$par)\n\n# Another Objective Function (Maximizing Average profit to find tuning parameters)\n#101_300: Average_profit\n## finding optimal alpha and beta\nAveProf_holt_smoothing <- function(p, price, salvage, cost) {\n alpha <- p[1]\n #alpha <- 0.025133018\n beta <- p[2]\n level <- b\n trend <- a\n forecast_1_500 <- c()\n for (i in 1:500) {\n forecast_1_500[i] <- trend + level\n # update the forecast with alpha and beta\n level <- alpha * dm$demand[i] + (1 - alpha) * forecast_1_500[i]\n trend <- beta * (level - (forecast_1_500[i] - trend)) + (1 - beta) * trend\n }\n \n #forecast_error_holt_smooth <- dm$demand[101:300] - forecast_1_500[101:300]\n forecast_error_holt_smooth <- dm$demand[1:300] - forecast_1_500[1:300]\n \n safety_stock <- quantile(forecast_error_holt_smooth, 0.80)\n \n stocking_101_300 <- forecast_1_500[101:300] + safety_stock\n # Average profit\n AvgProf <- mean(price * pmin(stocking_101_300, dm$demand[101:300]) + salvage * pmax(stocking_101_300 - dm$demand[101:300], 0) - cost * stocking_101_300)\n \n print(-AvgProf)\n return(-AvgProf) # don't forget to put negative sign as we want to maximize.\n}\n\nres <- optim(c(0.5,0.5), AveProf_holt_smoothing, method = \"L-BFGS-B\",\n lower = c(0,0),\n upper = c(10, 10),\n price = price,\n salvage = salvage,\n cost = cost)\nprint(\"Optimal alpha and beta by maximizing average profit:\")\nres$par\n\n\n#6. use the tuned values\nalpha <- res$par[1]\nbeta <- res$par[2]\n\nlevel <- b\ntrend <- a\n\nforecast_1_500_with_optim_alpha <- c()\nfor (i in 1:500) {\n forecast_1_500_with_optim_alpha[i] <- trend + level\n # update the forecast with alpha and beta\n level <- alpha * dm$demand[i] + (1 - alpha) * forecast_1_500_with_optim_alpha[i]\n trend <- beta * (level - (forecast_1_500_with_optim_alpha[i] - trend)) + (1 - beta) * trend\n}\n\nforecast_error_holt_smooth <- dm2$demand - forecast_1_500_with_optim_alpha[101:300]\nhist(forecast_error_holt_smooth)\n\nsafety_stock <- quantile(forecast_error_holt_smooth, 0.80)\nstocking_301_500 <- forecast_1_500_with_optim_alpha[301:500] + safety_stock # we use safety_stock obtained from df2\n\n\n# Average profit\nres_table$AvgProf[6] <- mean(price * pmin(stocking_301_500, dm3$demand) + salvage * pmax(stocking_301_500 - dm3$demand, 0) - cost * stocking_301_500)\n\n\n", "meta": {"hexsha": "2eadf114ada9daa42127b7fb9b982d0b2759f86b", "size": 15846, "ext": "r", "lang": "R", "max_stars_repo_path": "demand_forecast.r", "max_stars_repo_name": "hollylessthan/SupplyChain-Demand-Forecasting-by-Three-Forecasting-Methods", "max_stars_repo_head_hexsha": "45d3bab6dc26dd977acd7bf8cacee45e806211f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demand_forecast.r", "max_issues_repo_name": "hollylessthan/SupplyChain-Demand-Forecasting-by-Three-Forecasting-Methods", "max_issues_repo_head_hexsha": "45d3bab6dc26dd977acd7bf8cacee45e806211f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demand_forecast.r", "max_forks_repo_name": "hollylessthan/SupplyChain-Demand-Forecasting-by-Three-Forecasting-Methods", "max_forks_repo_head_hexsha": "45d3bab6dc26dd977acd7bf8cacee45e806211f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.755511022, "max_line_length": 202, "alphanum_fraction": 0.6611132147, "num_tokens": 4825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7282548508592434}} {"text": "normAbinom <- function() { # normAbinom.r\r\n x <- seq(5, 50, by=5)\r\n p.binom <- pbinom(x, 50, 0.5)\r\n p.norm <- pnorm(x, 25, sqrt(12.5))\r\n diff <- p.binom-p.norm\r\n list(p.binom = round(p.binom,4), p.norm = round(p.norm,4), diff = round(diff,4))\r\n } # end function\r\n\r\nnormAbinom()\r\n", "meta": {"hexsha": "27dc239d61a7340fd1e3002d680d6bc575b7dca7", "size": 285, "ext": "r", "lang": "R", "max_stars_repo_path": "R.2019.2/advanced.R/Rcode/Chap2/normAbinom.r", "max_stars_repo_name": "tolkien/misc", "max_stars_repo_head_hexsha": "84651346a3a0053b6a2af31db26c227a34da33c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R.2019.2/advanced.R/Rcode/Chap2/normAbinom.r", "max_issues_repo_name": "tolkien/misc", "max_issues_repo_head_hexsha": "84651346a3a0053b6a2af31db26c227a34da33c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R.2019.2/advanced.R/Rcode/Chap2/normAbinom.r", "max_forks_repo_name": "tolkien/misc", "max_forks_repo_head_hexsha": "84651346a3a0053b6a2af31db26c227a34da33c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5, "max_line_length": 83, "alphanum_fraction": 0.5754385965, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7282548375867903}} {"text": "##### 医学統計勉強会18第2回基本統計量 R code #####\n\nx <- c(0.684, 1.406, -0.663, -0.124, 0.849, -0.888, -0.492, -0.044, -0.188, 0.536, 2.063, -1.379, 0.920, 0.453, 1.239)\n\n## 数量的なデータの要約 ##\n\nsum(x)\t\t\t# x の要素の和\nlength(x)\t\t# x の長さ\nmean(x)\t\t\t# x の平均\nmedian(x)\t\t# x の中央値\nquantile(x)\t\t# x の四分位点.Five numbers summary\nquantile(x, 0.2)\t# x の20%パーセント点\nsummary(x)\t\t\t# Five numbers summary + 平均\n\nvar(x)\t\t\t# x の分散\nsd(x)\t\t\t# x の標準偏差\nsqrt(x)\t\t\t# x の平方根\nsqrt(var(x))\t# x の分散の平方根 = x の標準偏差\nIQR(x)\t\t\t# x の四分位点間距離\nquantile(x, 0.75) - quantile(x, 0.25)\t# 四分位点間距離の定義の確認\n\n## 視覚的なデータの要約 ##\n\nx <- rnorm(100)\t# ランダムなサンプルの生成\n\nhist(x)\t\t\t# ヒストグラム(頻度)\nhist(x, freq=F)\t# ヒストグラム(相対頻度)\n\nboxplot(x)\t\t# ボックスプロット\n\n# ヒストグラムとボックスプロット #\n\n# 二峰型 #\nx1 <- rnorm(100, mean=0)\nx2 <- rnorm(100, mean=4)\nx <- c(x1, x2)\nhist(x)\nboxplot(x)\n\n# 裾の重い分布 #\ny1 <- rnorm(100, sd=1)\ny2 <- rnorm(100, sd=4)\ny <- c(y1, y2)\nhist(y)\nboxplot(y)", "meta": {"hexsha": "55a3c61493ca0616a77f306611de35576efe28c0", "size": 869, "ext": "r", "lang": "R", "max_stars_repo_path": "MedicalStatisticsClass/2019/2/code.r", "max_stars_repo_name": "shumez/stat", "max_stars_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MedicalStatisticsClass/2019/2/code.r", "max_issues_repo_name": "shumez/stat", "max_issues_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MedicalStatisticsClass/2019/2/code.r", "max_forks_repo_name": "shumez/stat", "max_forks_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3111111111, "max_line_length": 118, "alphanum_fraction": 0.5926352129, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7280694069258703}} {"text": "### Code skeleton for Series 5, Exercise 1\n\n## Read in dataset\ndiabetes <-\n read.table(\"http://stat.ethz.ch/Teaching/Datasets/diabetes2.dat\",\n header = TRUE)\nreg <- diabetes[, c(\"Age\", \"C.Peptide\")]\nnames(reg) <- c(\"x\", \"y\")\n\n## Sort values\nreg <- reg[sort.list(reg$x), ]\n\n###################################################\n### TASK a)\n###################################################\n\n### Utility function for LOO cross-validation:\n\n##' Calculates the LOO CV score for given data and regression prediction function\n##'\n##' @param reg.data: regression data; data.frame with columns 'x', 'y'\n##' @param reg.fcn: regr.prediction function; arguments:\n##' reg.x: regression x-values\n##' reg.y: regression y-values\n##' x: x-value(s) of evaluation point(s)\n##' value: prediction at point(s) x\n##' @return LOOCV score\nloocv <- function(reg.data, reg.fcn)\n{\n ## Help function to calculate leave-one-out regression values\n loo.reg.value <- function(i, reg.data, reg.fcn)\n return(reg.fcn(reg.data$x[-i], reg.data$y[-i], reg.data$x[i]))\n\n ## Calculate LOO regression values using the help function above\n n <- nrow(reg.data)\n loo.values <- sapply(seq(1:n), loo.reg.value, reg.data, reg.fcn)\n\n ## Calculate and return MSE\n return(mean((loo.values - reg.data$y)^2))\n}\n\n\n### Regression prediction function for NW kernel:\nreg.fcn.nw <- function(reg.x, reg.y, x)\n ksmooth(reg.x, reg.y, x.points = x, kernel = \"normal\", bandwidth = 4.0)$y\n \n### Calculation of LOO CV-score for NW kernel estimator:\n(cv.nw <- loocv(reg, reg.fcn.nw))\nprint(cv.nw)\n\n### Hat matrix \"S.nw\":\nn <- nrow(reg)\nId <- diag(n)\nS.nw <- matrix(0, n, n)\nfor (j in 1:n) {\n tmp <- rep(0, n)\n tmp[j] <- 1\n S.nw[, j] <- reg.fcn.nw(reg$x, tmp, reg$x)\n}\n \n### Degrees of freedom (cf. Formula (3.6) in the lecture notes:\n(df.nw <- sum(diag(S.nw)))\nprint(df.nw)\n\n###################################################\n### TASKS b) to e)\n###################################################\n\n### Proceed similarly as in task a); you can reuse the utility function\n### loocv from task a)\n\n### b) have a look at ?predict.loess to define your regression function reg.fcn.lp\nreg.fcn.lp <- function(reg.x, reg.y, x){\n loess.fit <- loess(reg.y ~ reg.x, enp.target = df.nw, surface = \"direct\")\n return(predict(loess.fit, data.frame(reg.x = x)))\n}\n\n(cv.lp <- loocv(reg, reg.fcn.lp))\nprint(cv.lp)\n\n### c) have a look at ?predict.smooth.spline to define your regression function reg.fcn.ss\n\nest.ss <- smooth.spline(reg$x, reg$y, cv = TRUE, df = df.nw)\nprint((est.ss$cv.crit))\n\nreg.fcn.ss <- function(reg.x, reg.y, x){\n ss.fit <- smooth.spline(reg.x, reg.y, spar = est.ss$spar)\n return(predict(ss.fit, x)$y)\n}\n\n(cv.ss <- loocv(reg, reg.fcn.ss))\nprint(cv.ss)\n\n### d)\n\ncv.ss_int <- smooth.spline(reg$x, reg$y, cv = TRUE)$cv.crit\nprint(cv.ss_int)\n\n### e)\n\nreg.fcn.cn <- function(reg.x, reg.y, x){\n return(mean(reg.y))\n}\n\n(cv.cn <- loocv(reg, reg.fcn.cn))\nprint(cv.cn)", "meta": {"hexsha": "36ac3351b0c4e6120ce57b5a9725a8535b8cb276", "size": 3014, "ext": "r", "lang": "R", "max_stars_repo_path": "Computational_Statistics/Exercices/5_1.r", "max_stars_repo_name": "DanDoge/course_ethz", "max_stars_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Computational_Statistics/Exercices/5_1.r", "max_issues_repo_name": "DanDoge/course_ethz", "max_issues_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computational_Statistics/Exercices/5_1.r", "max_forks_repo_name": "DanDoge/course_ethz", "max_forks_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4339622642, "max_line_length": 90, "alphanum_fraction": 0.5809555408, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7278818450991433}} {"text": "# 4/14\n#\n# K means analysis on Star data ---------------------------\n\n#install.packages('foreign')\nlibrary(foreign) # to read the data we need function read.arff() from library foreign.\n\n#install.packages('dplyr')\nlibrary(dplyr) #' dplyr package provides some utility funcions for sorting data\n\nstars <- read.arff(file = 'AstronomyTrainingData.txt')\n#Filter stars for complete entries.\ncomplete_stars <- stars %>% filter(complete.cases(.)) \nstar_names <- levels(stars$class)\n\n# identify the 25 levels of star: (Column 87 holds the names.)\nlevels(stars$class)\nbarplot(summary(stars$class), horiz = TRUE, las = 1, cex.names = 0.5)\n\n# We could specify that there are 25 centers, and kmeans will attempt to \n# locate 25 good centers, but it may be terrible!\ncenters <- 25\n\nstar_km <- kmeans(complete_stars[c(-1,-dim(complete_stars)[2])], centers, iter.max = 20, nstart = 1)\nfound_centers <- star_km$centers\n\n# There are 25 centers, one for each cluster. The center contains 85 means representing each variable.\n# Cluster membership is identified by a a number.\n# View(star_km$cluster)\n\n#Numbers of stars per cluster\ntable(factor(star_km$cluster))\nplot(table(factor(star_km$cluster)),xlab = \"Cluster Number\", ylab = \"Stars per Cluster\")\n\n\n\n\n# I can make one of these by: \n# 1) Sorting the data by star type\n# 2) taking the mean for each star type, for each variable.\n\n# with dplyr: group COMPLETE stars by class, then summarise with the mean across all variables.\n#sum_stars <- complete_stars %>% group_by(class) %>% summarise_each(funs(mean))\n\n# with dplyr: group each star by class, then summarise all the variables with mean(x, rm.na)\nsum_stars <- stars %>% group_by(class) %>% summarise_each(funs(mean(., na.rm=TRUE)))\n\n#star_km$size\n#star_km$centers\n#star_km$tot.withinss\n#table(factor(star_km$cluster), factor(unlist(star_names)))\n\n#full_star_km <- kmeans(complete_stars[c(-1,-dim(complete_stars)[2])], centers = sum_stars, \n # iter.max = 20, nstart = 1)\n\n# Setting our own centers ---------------------------\n# We had to switch to \"Lloyd\" method, as \"Hartigan-Wong\" cannot handle size 0 clusters.\nfull_star_km <- kmeans(as.matrix(complete_stars[,c(-1,-87)]), \n centers = as.matrix(sum_stars[,c(-1,-2)]), iter.max = 20,\n algorithm = \"Lloyd\")\n\n# Result of clustering with 25 random clusters\nplot(table(star_km$cluster))\ntable(star_km$cluster)\n# Result of clustering with 25 nonrandom clusters drawn from training.\ntable(full_star_km$cluster) \nplot(table(full_star_km$cluster))\nplot(table(stars$class))\nbarplot(summary(stars$class), horiz = TRUE, las = 1, cex.names = 0.5)\n\n\n\n#algorithm = c(\"Hartigan-Wong\", \"Lloyd\", \"Forgy\",\"MacQueen\"), trace=FALSE)\nView(as.matrix(sum_stars[1:10,c(-1,-2)]))\n\n\nis.data.frame(complete_stars)\nView(sum_stars)\n?kmeans\n\nView(sum_stars[,c(-1,-2,-87)])\ndim(sum_stars[,c(-1,-2)])\ndim(stars[,c(-1,-87)])\n\n\n# An example of setting the centers ---------------------------\n# Available here: http://stats.stackexchange.com/questions/72606/k-means-clustering-after-first-iteration\n\n# Set the RNG seed to ensure reproducibility\nset.seed(12345)\n\n# Let's create 3 visually distinct clusters\nn <- c(1000, 500, 850)\n# Jeff: X var defined here for 3 clusters\nclassifier.1 <- c(rnorm(n[1], 10, 0.9), \n rnorm(n[2], 25, 2),\n rnorm(n[3], 35, 2))\n# Jeff: Y var defined here for 3 clusters.\nclassifier.2 <- c(rnorm(n[1], 5, 1),\n rnorm(n[2], 10, 0.4),\n rnorm(n[3], 2, .9))\n\ncol = c(\"blue\", \"darkgreen\", \"darkred\")\n# Run k-means with 3 clusters and random initial centroids \n# to check the clusters are correctly recognized\nkm <- kmeans(cbind(classifier.1, classifier.2), 3)\n# Plot the data, colored by cluster\nplot(classifier.1, classifier.2, pch=20, col=col[km$cluster])\n\n# Mark the final centroids\npoints(km$centers, pch=20, cex=2, col=\"orange\")\n\n# Now impose some obviously \"wrong\" starting centroids\nstart.x <- c(10, 25, 3000)\nstart.y <- c(10, 10, -10000)\nkm.2 <- kmeans(cbind(classifier.1, classifier.2), \n centers=cbind(start.x, start.y))\n\n# Jeff: How will this preform if we give it the right stuff?\nstart.x <- c(10, 25, 35)\n# It still finds it even if we give pretty bad y values!\nstart.y <- c(0, 1, 3)\nkm.2 <- kmeans(cbind(classifier.1, classifier.2), \n centers=cbind(start.x, start.y))\nplot(classifier.1, classifier.2, pch=20, col=col[km.2$cluster])\npoints(km.2$centers, pch=20, cex=2, col=\"orange\")\n\nView(cbind(start.x, start.y))\n?kmeans\n\n# Top 30 Vars. ---------------------------\n\n#Select the top n variables from PCA to use.\nn <- 20\nn_star_names <- as.character( pca_out[1:n,1] )\n#View(stars[as.character( pca_out[1:n,1] ) ])\n\n\n#Sort out the complete stars.\ncomplete_stars <- stars %>% filter(complete.cases(.)) \n\n# Create a sorted list of training stars, by type.\nsum_stars <- stars %>% group_by(class) %>% summarise_each(funs(mean(., na.rm=TRUE)))\n\n#\n\n\ntop_var_star_km <- kmeans(as.matrix(complete_stars[,n_star_names]), \n centers = as.matrix(sum_stars[,n_star_names]), iter.max = 200,\n algorithm = \"Lloyd\")\n\n#View(top_var_star_km$cluster)\n# Result of clustering using the best n variables, with means of clusters drawn from training.\n#table(top_var_star_km$cluster) \nplot(table(top_var_star_km$cluster))\nplot(table(stars$class))\n\n\nbarplot(table(top_var_star_km$cluster))\nbarplot(table(stars$class), las = 1, cex.names = 0.5, )\nbarplot(table(complete_stars$class), las = 1, cex.names = 0.5, )\n\n\nbarplot(cbind(table(top_var_star_km$cluster), table(stars$class)), las = 1, cex.names = 0.5, beside = T, )\n#barplot(summary(stars$class), horiz = TRUE, las = 1, cex.names = 0.5)\n\nresults <- as.data.frame( cbind(names = star_names, predicted = table(top_var_star_km$cluster), actual = table(stars$class)))\nView(results)\nbarplot(as.numeric(results$actual), horiz = T, las = 1, names.arg = results$names, cex.names= 0.5, main = \"Actual\")\nbarplot(as.numeric(results$predicted), horiz = T, las = 1, names.arg = results$names, cex.names= 0.5, main = \"Predicted\")\nbarplot(summary(stars$class), horiz = TRUE, las = 1, cex.names = 0.5, main = \"Training Stars\")\nbarplot(summary(complete_stars$class), horiz = TRUE, las = 1, cex.names = 0.5, main = \"Complete Stars\")\n\n\n\n\n\n# Working with the whole data ---------------------------\n# The location of this file will vary for you. I didn't upload it to github, since it is so large.\n# I suppose we could upload it if we want.\n\nall_stars <- read.arff(file = 'Z:/ST599/Project 1/data/AstronomyTestData.txt')\n\n\n\n\n\n\n\n\n\n# Multicolinearity Analysis ---------------------------\n\n#Is there multicolinearity?\n\n# install.packages('faraway')\nlibrary(faraway)\n#Calculate the variance inflation factors (a measure of multicolinearity)\n# (VIFS are a ratio of eigenvalues to the smallest eigenvalue)\ncomplete_stars_noname <- complete_stars[c(-1,-dim(complete_stars)[2])]\nvifs <- (vif(complete_stars_noname))\nvifs\nplot(vifs)\n#identify(vifs)\nidentify(vifs, labels = names(vifs), atpen = T)\nidentify(vifs, labels = names(vifs))\nidentify(vifs)\n# Colinearity Suspects in order:: \n# \"eclpoly_p_pulse\", \"eclpoly_p_pulse_initial\", \"std\" \"stetson_j\", \"amplitude\"\n\n\nView(complete_stars)\nsorted_vifcolumns <- arrange(complete_stars_noname[,c(1,18,19,83,84)],amplitude)\nView(complete_stars_noname[,c(1,18,19,83,84)])\n\ne <- eigen(t(as.matrix(complete_stars_noname))%*%as.matrix(complete_stars_noname))\nsignif(e$values,3)\n# There is at least one enormous colinearity. \n# It was at least 2.0e20 before correction.\nvar_names <- names(complete_stars)\nsort(var_names)\n\n\n# Correcting for variance inflation:\n# Remove ID, Remove Name\nstar_low_vif <- complete_stars[c(-1,-dim(complete_stars)[2])]\nstar_low_vif <- star_low_vif[c(-18,-19)]\n\ne <- eigen(t(as.matrix(star_low_vif))%*%as.matrix(star_low_vif))\nsignif(e$values,3)\n\nlow_vif <- (vif(star_low_vif))\nplot(low_vif)\nidentify(low_vif)\nView(star_low_vif[,c(1,81,82)])\n\n\n\n\n\n\n# Sharm's Example ---------------------------\n\n#cancerData<-read.table(file=\"14cancer.xtrain\",sep=\"\")\n# namesCancer<-read.table(file=\"namesCancer.txt\",sep=\"\",header=\"FALSE\")\n#namesCancer<-read.table(file=\"namesCancer.txt\")\n#myLabels<-c('breast','prostate','lung','collorectal','lymphoma','bladder','melanoma','uterus','leukemia','renal','pancreas','ovary','meso','cns')\n#names(cancerData)<-c(namesCancer)\n\n\n#dim(cancerData)\n#myLabels<-c('breast','prostate','lung','collorectal','lymphoma','bladder','melanoma','uterus','leukemia','renal','pancreas','ovary','meso','cns')\n\n#digit = read.table('Digit_recog_train.txt')\n#digit_no = digit[,1]\n#digit_pix = digit[,-1]\n#digit_no3 = digit_no[digit_no == 3]\n#digit_pix3 = digit_pix[digit_no == 3,]\n\n#sel = sample(c(0,1), length(digit_no), replace = T, prob = c(4/5,1/5))\n#digit_pix = digit_pix[sel == 1,]\n#digit_no = digit_no[sel==1]\n\n# Example, part 2\n\n#numCenters<-5\n#kmeansCancer<-kmeans(t(cancerData), numCenters, iter.max = 20, nstart = 1)\n\n#kmeansCancer$size\n#kmeansCancer$centers\n#kmeansCancer$tot.withinss\n#table(factor(kmeansCancer$cluster), factor(unlist(namesCancer)))\n#myLabels\n\n#numCenters = 10\n#kmeansDigit = kmeans(digit_pix, numCenters, iter.max = 20, nstart = 1)\n#pamDigit = pam(digit_pix, k = numCenters, metric = 'Euclidean')\n\n#kmeansDigit$size\n#kmeansDigit$centers\n#kmeansDigit$tot.withinss\n#table(factor(kmeansDigit$cluster), factor(digit_no))\n#pamDigit$medoids\n#pamDigit$objective\n#table(factor(pamDigit$clustering), factor(digit_no))\n\n# ---------------------------", "meta": {"hexsha": "0fac4fef52d88afd64664eebc5989cb4e3651039", "size": 9524, "ext": "r", "lang": "R", "max_stars_repo_path": "kmeans.r", "max_stars_repo_name": "mintzj/ST599-1", "max_stars_repo_head_hexsha": "5512ee29558bceefc6bcdf6176ff68c2ca79db56", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kmeans.r", "max_issues_repo_name": "mintzj/ST599-1", "max_issues_repo_head_hexsha": "5512ee29558bceefc6bcdf6176ff68c2ca79db56", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kmeans.r", "max_forks_repo_name": "mintzj/ST599-1", "max_forks_repo_head_hexsha": "5512ee29558bceefc6bcdf6176ff68c2ca79db56", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1846689895, "max_line_length": 146, "alphanum_fraction": 0.6863712726, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7277228848255156}} {"text": "library(drat)\nlibrary(dde)\nlibrary(odin)\n\n\ndrat::add(\"mrc-ide\")\n\nsir_generator <- odin::odin({\n ## Core equations for transitions between compartments:\n update(S) <- S - n_SI\n update(I) <- I + n_SI - n_IR\n update(R) <- R + n_IR\n\n ## Individual probabilities of transition:\n p_SI <- 1 - exp(-beta * I / N) # S to I\n p_IR <- 1 - exp(-gamma) # I to R\n\n ## Draws from binomial distributions for numbers changing between\n ## compartments:\n n_SI <- rbinom(S, p_SI)\n n_IR <- rbinom(I, p_IR)\n\n ## Total population size\n N <- S + I + R\n\n ## Initial states:\n initial(S) <- S_ini\n initial(I) <- I_ini\n initial(R) <- 0\n\n ## User defined parameters - default in parentheses:\n S_ini <- user(1000)\n I_ini <- user(1)\n beta <- user(0.2)\n gamma <- user(0.1)\n \n}, verbose = FALSE)\n\nsir <- sir_generator(I_ini = 10)\nsir\n\nset.seed(1)\nsir_col <- c(\"#8c8cd9\", \"#cc0044\", \"#999966\")\n\nres <- sir$run(0:100)\npar(mar = c(4.1, 5.1, 0.5, 0.5), las = 1)\nmatplot(res[, 1], res[, -1], xlab = \"Time\", ylab = \"Number of individuals\",\n type = \"l\", col = sir_col, lty = 1)\nlegend(\"topright\", lwd = 1, col = sir_col, legend = c(\"S\", \"I\", \"R\"), bty = \"n\")\n\nres_200 <- sir$run(0:100, replicate = 200)\nres_200 <- sir$transform_variables(res_200)\nres_200 <- cbind.data.frame(t = res_200[[1]], res_200[-1])\n\ncol <- rep(sir_col, each = 200)\n \npar(mar = c(4.1, 5.1, 0.5, 0.5), las = 1)\nmatplot(res_200[, 1], res_200[, -1], xlab = \"Time\", ylab = \"Number of individuals\",\n type = \"l\", col = col, lty = 1)\nlegend(\"topright\", lwd = 1, col = sir_col, legend = c(\"S\", \"I\", \"R\"), bty = \"n\")\n\n## x: instance of odin model\n## t: time steps\n## n: number of replicates\nrun_model <- function(x, t = 0:100, n = 1, ...) {\n res <- x$run(t, replicate = n, ...)\n res <- x$transform_variables(res)\n res <- cbind.data.frame(t = res[[1]], res[-1])\n attr(res, \"n_compartments\") <- length(x$names) - 1\n attr(res, \"n_replicates\") <- n\n attr(res, \"compartments\") <- x$names[-1]\n class(res) <- c(\"pretty_odin\", class(res))\n res\n}\n\nsir_pal <- colorRampPalette(sir_col)\n\nplot.pretty_odin <- function(x, pal = sir_pal, ...) {\n ## handle colors\n n_compartments <- attr(x, \"n_compartments\")\n n_replicates <- attr(x, \"n_replicates\")\n col_leg <- pal(n_compartments)\n alpha <- max(10 / n_replicates, 0.05)\n col <- rep(col_leg, each = n_replicates)\n\n ## make plot\n par(mar = c(4.1, 5.1, 0.5, 0.5), las = 1)\n matplot(x[, 1], x[, -1], xlab = \"Time\", ylab = \"Number of individuals\",\n type = \"l\", col = col, lty = 1, ...)\n legend(\"topright\", lwd = 1, col = col_leg, bty = \"n\",\n legend = attr(x, \"compartments\"))\n}\n\n# Run\nx <- run_model(sir, t = 0:100, n = 500)\nplot(x)\n", "meta": {"hexsha": "87fbc158d17a06f7f175e0186b99b934151defd5", "size": 2717, "ext": "r", "lang": "R", "max_stars_repo_path": "models/simple_stochastic_models/discrete_t_sir/ssir_odin.r", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_stochastic_models/discrete_t_sir/ssir_odin.r", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_stochastic_models/discrete_t_sir/ssir_odin.r", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 28.0103092784, "max_line_length": 83, "alphanum_fraction": 0.5811556864, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7275631052657894}} {"text": "################################################################\r\n### Code for replication study:\r\n### \"A New Approach to Estimating the Production Function for Housing\"\r\n### by Dennis Epple, Brett Gordon, and Holger Sieg, forthcoming AER.\r\n###\r\n### This code is used to estimate the production function.\r\n###\r\n###\r\n################################################################\r\n\r\n## ----Load-Libraries------\r\nlibrary(MASS)\r\nlibrary(splines)\r\n## library(odesolve) - This function is no longer maintained by CRAN\r\nlibrary(deSolve)\r\nlibrary(lokern)\r\nsource(\"./Notes/Gradient_Descent_001.R\")\r\n\r\n\r\n## ----read-the-data----\r\ngetwd()\r\n# Just pland, v, and lotarea\r\n#data = read.csv(\"./Data/Pittsburgh_post1995.txt\", header=TRUE)\r\ndata = read.csv(\"Pittsburgh_post1995.txt\", header=TRUE)\r\nN = dim(data)[1]\r\n\r\nv = data$v\r\npland = data$pland\r\nlotarea = data$lotarea\r\nmuni = data$muni\r\ntcog = data$tcog\r\n\r\nsorted = sort(v,index.return=TRUE, method=\"quick\")\r\npland = pland[sorted$ix]\r\nlotarea = lotarea[sorted$ix]\r\nmuni = muni[sorted$ix]\r\ntcog = tcog[sorted$ix]\r\nv = sorted$x\r\n\r\nv.full = v\r\npland.full = pland\r\n\r\n#Calculate 1 and 99 percentile for v\r\npercentile <- quantile(data$v, probs = c(0.01,0.99))\r\n\r\n# The 99 percentile = 144.4683 and 1 percentile = 0.923818\r\ngoodv = (((v.full < percentile[2])*(v > percentile[1])) == 1)\r\nv = v.full[goodv]\r\npland = pland.full[goodv]\r\nlotarea = lotarea[goodv]\r\nmuni = muni[goodv]\r\n\r\nN = length(v)\r\nlogpland = log(pland)\r\nlogv = log(v)\r\nv2 = v^2\r\nv3 = v^3\r\nv4 = v^4\r\n\r\nv.sd = sqrt(var(v))\r\nlogv.sd = sqrt(var(logv))\r\n\r\nremove(data)\r\n\r\nplot(logv, logpland, main=\"Value per Unit Land vs. Land Value per Unit Land\\nBaltimore City Residential Properties\",\r\n xlab=\"log(v)\", ylab=\"log(pland)\") #,xlim=c(-2,5), ylim=c(-3,3.5))\r\n\r\n\r\n## ----- Estimate-the-regressions ------\r\n\r\n### Basic regressions\r\n\r\nlm.loglin = lm(logpland ~ logv)\r\nlm.lin = lm(pland ~ v - 1)\r\nlm.quad = lm(pland ~ v + v2 - 1)\r\nlm.cub = lm(pland ~ v + v2 + v3 - 1)\r\nlm.quart = lm(pland ~ v + v2 + v3 + v4 - 1)\r\n#Linear model using Gaussian Generalized Linear Model\r\nglm.lin = glm(pland ~ v - 1)\r\n\r\n#Log Linear model using Gaussian Generalized Linear Model\r\nglm.loglin = glm(logpland ~ logv)\r\n\r\n#Log Linear model with a different Gradient Descent Loss Function\r\n#thetaValues = gradientDescentLinearModel(logv, logpland, 0.1, 1000)\r\n\r\n## ---Create-Coefficient-Table\r\n\r\n# table<- data.frame(matrix(ncol=7,nrow = 6))\r\n# namesOfColumn <- c(\"Coefficients\",\"Log_Linear\",\"Linear\",\"Quadratic\",\"Cubic\",\r\n# \"Gaussian_Generalized_Linear_Model\",\r\n# \"Gaussian_Generalized_Log_Linear_Model\",\r\n# \"Gradient_Descent_Log_Linear_Model\")\r\n# colnames(table) <- namesOfColumn\r\n# table$Coefficients <- c(\"v\", \"v^2\", \"v^3\", \"constant\", \"log(v)\", \"N\")\r\n# table[4,2] <- round(lm.loglin$coefficients[1],2)\r\n# table[5,2] <- round(lm.loglin$coefficients[2],2)\r\n# table[1,3] <- round(lm.lin$coefficients[1],2)\r\n# table[1,4] <- round(lm.quad$coefficients[1],2)\r\n# table[2,4] <- round(lm.quad$coefficients[2],5)\r\n# table[1,5] <- round(lm.cub$coefficients[1],2)\r\n# table[2,5] <- round(lm.cub$coefficients[2],5)\r\n# table[3,5] <- round(lm.cub$coefficients[3],2)\r\n# table[1,6] <- round(glm.lin$coefficients[1],2)\r\n# table[4,7] <- round(glm.loglin$coefficients[1],2)\r\n# table[5,7] <- round(glm.loglin$coefficients[2],2)\r\n# #table[4,8] <- round(thetaValues[1],2)\r\n# #table[5,8] <- round(thetaValues[2],2)\r\n# table[6,2:7] <- as.numeric(N)\r\n# View(table)\r\n\r\nstargazer(lm.loglin, lm.lin, lm.quad, lm.cub, glm.lin, glm.loglin, summary=FALSE, out = \"file.out\", type = \"text\")\r\n?stargazer\r\n# colnames(table) = gsub(\"_\", \" \", colnames(table))\r\n# table[is.na(table)]<- \" \"\r\n\r\n# table %>%\r\n# stargazer(type ='text', summary = FALSE,\r\n# digits =2,\r\n# title = \"Table 1 - Descriptive statistics of Residential data\")\r\n\r\n\r\n### Non-parametric estimation of r(v)\r\n\r\ngkern.deriv = glkerns(v, pland, deriv=1,n.out=300, hetero=TRUE,bandwidth=v.sd*1.1)\r\ngkern = glkerns(v, pland, deriv=0,n.out=500, hetero=TRUE,bandwidth=v.sd*1.1)\r\ngkern.interp = interpSpline(gkern$x.out,gkern$est,na.action=na.omit,bSpline=TRUE)\r\n\r\ngkern.log = glkerns(logv, logpland, deriv=0,n.out=300, hetero=TRUE)\r\ngkern.log.interp = interpSpline(gkern.log$x.out,gkern.log$est,na.action=na.omit,bSpline=TRUE)\r\ngkern.log.fitted = predict(gkern.log.interp, logv) ## ??\r\n\r\npar(mfrow=c(1,2))\r\nplot(gkern.deriv$x.out,gkern.deriv$est, type=\"l\")\r\nplot(gkern.log$x.out,gkern.log$est, type=\"l\", col=\"red\")\r\nplot(gkern$x.out,gkern$est, type=\"l\") ## ??\r\n\r\n### Plot the regressions\r\npar(mfrow=c(1,2))\r\nplot(logv, lm.loglin$fitted.values, type=\"l\",xlim=c(-2,5), ylim=c(-3,3.5))\r\nlines(logv, lm.loglin$fitted.values, col=\"red\")\r\nlines(logv, log(lm.lin$fitted.values), col=\"blue\")\r\nlines(logv, log(lm.quad$fitted.values), col=\"green\")\r\nlines(logv, log(lm.cub$fitted.values), col=\"orange\")\r\n\r\n#Plot to add line generated by Gaussian Generalized Linear Model\r\nlines(logv, glm.loglin$fitted.values, col = '#009E73')\r\n\r\n#Plot to add line using Log linear model with Gradient Descent Loss Function\r\n#abline(coef=thetaValues, col = '#F0E442')\r\n\r\n\r\n#Calculate the predicted values from using Log linear model with Gradient Descent Loss Function\r\n#predictedValuesGD <- calculatePredictionValues(logv, logpland, thetaValues[2], thetaValues[1])\r\n\r\n#Added two new model prediction\r\n#1) Gaussian Generalized Log Linear Model: Gaus.LLM\r\n#2) Gradient Descent Log Linear Model: GradDes.LLM\r\n\r\nregs = data.frame(\"Log-Linear\"=lm.loglin$fitted.values, \"Linear\"=log(lm.lin$fitted.values),\"Quadratic\"=log(lm.quad$fitted.values),\r\n \"Cubic\"=log(lm.cub$fitted.values), \"Log Kernel\"=gkern.log.fitted$y, 'Gaus.LLM'=glm.loglin$fitted.values)\r\n\r\nregs_table2 = data.frame(\"Log-Linear\" = summary(lm.loglin)$coeff)\r\n\r\nmatplot(cbind(logv,logv,logv,logv,logv,logv), regs, col=1:ncol(regs), lty=1:ncol(regs),lwd=c(2,2,2,2), type=\"l\",\r\n main=\"Fitted Regressions for r(v)\", xlab=\"v\", ylab=\"p_l\", xlim=c(-0.5,5), ylim=c(-2.2,3.5))\r\nlegend(3.9, 0.5, names(regs), col=1:ncol(regs), lty=1:ncol(regs), cex = 0.5 )\r\n\r\n\r\n\r\n## -----Derive-supply-functions-for-each-model-----\r\n\r\nvseq.n = 1000\r\nvseq = seq(1,100,length.out=vseq.n)\r\n\r\n### Calculate supply functions for quad and cubic cases\r\nr = lm.quad$coefficients\r\np.quad = (vseq^r[1])*exp(2*r[2]*(vseq-1))\r\ns.quad = vseq/p.quad\r\n\r\nr = lm.cub$coefficients\r\nc = 2*r[2] + 1.5*r[3]\r\np.cub = (vseq^r[1])*exp(2*r[2]*(vseq-1) + 1.5*r[3]*(vseq^2 - 1))\r\ns.cub = vseq/p.cub\r\n\r\n# Now create price grid given this upperbound\r\nlb = min(range(p.quad)[1],range(p.cub)[1])\r\nub = min(range(p.quad)[2],range(p.cub)[2])\r\npgrid = seq(lb,ub,length.out=vseq.n)\r\n\r\n\r\n### Calculate supply functions for linear and log-linear cases\r\n\r\nalpha = as.numeric(exp(lm.loglin$coefficients[1])*lm.loglin$coefficients[2])\r\nbeta = as.numeric(lm.loglin$coefficients[2] - 1)\r\n\r\n### Calculate supply function for GLM Log-linear case\r\n\r\nalpha_glm = as.numeric(exp(glm.loglin$coefficients[1])*glm.loglin$coefficients[2])\r\nbeta_glm = as.numeric(glm.loglin$coefficients[2] - 1)\r\n\r\n# Determine upper bound on p, since beta < 0 implies (c+log(p)) < 0\r\n### For log-linear model\r\nec = exp(-alpha/beta)\r\n\r\n### FOr GLM Log-linear model\r\nec_glm = exp(-alpha_glm/beta_glm)\r\n\r\n\r\n### Linear case\r\nk = lm.lin$coefficients[1]\r\ns.lin = pgrid^((1-k)/k)\r\n\r\n### Log-linear case\r\ns.loglin = (1/pgrid)*((1 + (beta/alpha)*log(pgrid))^(1/beta))\r\n\r\n### GLM Log-Linear case\r\nsglm.loglin = (1/pgrid)*((1 + (beta_glm/alpha_glm)*log(pgrid))^(1/beta_glm))\r\n\r\n### Solve ODE for kernel supply function\r\n\r\nrprime = interpSpline(gkern.deriv$x.out,gkern.deriv$est,na.action=na.omit,bSpline=TRUE)\r\n\r\n## calc.supply.deriv = function(t,y, params) list((y/t)*((1/(predict(rprime,y*t))$y)-1))\r\ncalc.supply.deriv = function(pgrid.kern,xstart, params) list((xstart/pgrid.kern)*((1/(predict(rprime,xstart*pgrid.kern))$x)-1))\r\n##dd = function(pgrid.kern,xstart, params) ## ??\r\n\r\n## list((xstart/pgrid.kern)*((1/(predict(rprime,xstart*pgrid.kern))$x)-1)) ## ??\r\n\r\nxstart = c(1)\r\npgrid.kern = c(1, seq(1.001,ub,length.out=vseq.n-1))\r\n\r\node.out = lsoda(xstart, pgrid.kern, calc.supply.deriv, parms=1, rtol=1e-5, atol=1e-7)\r\ns.kern = data.frame(s=ode.out[,2],p=ode.out[,1])\r\n\r\n### Plot all the supply functions\r\n\r\ns.funcs = data.frame(\"Log-Linear\"=s.loglin,\"Linear\"=s.lin,\"Quadratic\"=s.quad,\r\n \"Cubic\"=s.cub, \"Kernel\"=s.kern$s, \"GLM Log-Linear\" = sglm.loglin)\r\np.grids = cbind(pgrid,pgrid,p.quad,p.cub,s.kern$p,pgrid)\r\n\r\ns.lin.range = range(s.lin*pgrid)\r\ns.loglin.range = range(s.loglin*pgrid)\r\ns.quad.range = range(s.quad*p.quad)\r\ns.cub.range = range(s.cub*p.cub)\r\ns.kern.range = range(s.kern$s*s.kern$p)\r\nsglm.loglin.range = range(sglm.loglin*pgrid)\r\n\r\nmatplot(s.funcs,p.grids,col=1:ncol(s.funcs), lty=1:ncol(s.funcs),lwd=c(2,2,2,2), type=\"l\",\r\n main=\"Supply Functions\", xlab=\"Supply\", ylab=\"Price\",xlim=c(0,39))\r\nlegend(20, 1.5, names(s.funcs), col=1:ncol(s.funcs), lty=1:ncol(s.funcs))\r\n\r\n\r\n## ----Production-Function-Estimation------\r\n\r\nv.lin.hat = s.lin*pgrid\r\nv.loglin.hat = s.loglin*pgrid\r\nv.quad.hat = s.quad*p.quad\r\nv.cub.hat = s.cub*p.cub\r\nv.kernel = s.kern$p*s.kern$s\r\nv.glmloglin.hat = sglm.loglin*pgrid\r\n\r\nlm.lin.fitted = lm.lin$coefficients[1]*v.lin.hat\r\nlm.loglin.fitted = exp(lm.loglin$coefficients[1] + lm.loglin$coefficients[2]*log(v.loglin.hat))\r\nlm.quad.fitted = lm.quad$coefficients[1]*v.quad.hat + lm.quad$coefficients[2]*v.quad.hat^2\r\nlm.cub.fitted = lm.cub$coefficients[1]*v.cub.hat + lm.cub$coefficients[2]*v.cub.hat^2 + lm.cub$coefficients[3]*v.cub.hat^3\r\nkernel.fitted = predict(gkern.interp,v.kernel)$y\r\nglm.loglin.fitted = exp(glm.loglin$coefficients[1] + glm.loglin$coefficients[2]*log(v.glmloglin.hat))\r\n\r\n\r\nm.lin = v.lin.hat-lm.lin.fitted\r\nm.loglin = v.loglin.hat-lm.loglin.fitted\r\nm.quad = v.quad.hat-lm.quad.fitted\r\nm.cub = v.cub.hat-lm.cub.fitted\r\nm.kernel = v.kernel - kernel.fitted\r\nm.glmloglin = v.glmloglin.hat-glm.loglin.fitted\r\n\r\n##Normalize the production function for the kernel case\r\nm.kernel = m.kernel + (1-m.kernel[1])\r\n\r\nprod.funcs = data.frame(\"Log-Linear\"=s.loglin,\"Linear\"=s.lin,\"Quadratic\"=s.quad, \"Cubic\"=s.cub, \"Kernel\"=s.kern$s)\r\n\r\nm.grids = cbind(m.loglin, m.lin, m.quad, m.cub,m.kernel)\r\n\r\nmatplot(m.grids,prod.funcs, col=1:ncol(prod.funcs), lty=1:ncol(prod.funcs),lwd=c(2,2,2,2), type=\"l\",\r\n main=\"Production Functions\", xlab=\"m = (M/L)\", ylab=\"Output\", xlim=c(0,80), ylim=c(0,42))\r\nlegend(60, 12, names(prod.funcs), col=1:ncol(prod.funcs), lty=1:ncol(prod.funcs))\r\n\r\n\r\n## ----Calculate-supply-elasticities----\r\n\r\n## Missing definition of 'calc.elas' and 'fdiff' function. Added the defintion of 'calc.elas' and 'fdiff'\r\n\r\nfdiff <- function(x, fun, h=NULL, order=1, accur=4, ...) {\r\n macheps <- .Machine$double.eps\r\n\r\n if (order==1) {\r\n if(is.null(h)) h <- macheps^(1/3)* abs(x)\r\n ifelse (accur==2, w <- c(-1/2,1/2), w <- c(1/12,-2/3, 2/3,-1/12))\r\n ifelse (accur==2, xd <- x + h*c(-1,1), xd <- x + h*c(-2,-1,1,2))\r\n return(sum(w*fun(xd,...))/h)\r\n }\r\n else if (order==2) {\r\n if(is.null(h)) h <- macheps^(1/4)* abs(x)\r\n ifelse (accur==2, w <- c(1,-2,1), w <- c(-1/12,4/3,-5/2,4/3,-1/12))\r\n ifelse (accur==2, xd <- x + h*c(-1,0,1), xd <- x + h*c(-2,-1,0,1,2))\r\n return(sum(w*fun(xd,...))/h^2)\r\n }\r\n}\r\ncalc.elas = function(grid,sfunc,bspline=TRUE){\r\n require(splines)\r\n s.interp = interpSpline(grid,sfunc,na.action=na.omit,bSpline=bspline)\r\n s.elas = rep(NA,length(grid))\r\n for(i in 1:length(grid)){\r\n s.elas[i] = (fdiff(grid[i],function(x){(predict(s.interp,x))$y}))*(grid[i]/sfunc[i])\r\n }\r\n return(s.elas)\r\n}\r\n\r\n## Usual Code\r\nrequire(splines)\r\ns.loglin.elas = calc.elas(pgrid,s.loglin)\r\ns.lin.elas = calc.elas(pgrid,s.lin)\r\ns.quad.elas = calc.elas(pgrid,s.quad)\r\ns.cub.elas = calc.elas(pgrid,s.cub)\r\ns.kern.elas = calc.elas(s.kern$p,s.kern$s)\r\nsglm.loglin.elas = calc.elas(pgrid,sglm.loglin)\r\n\r\n\r\ns.elas = list(\"Linear\"=s.lin.elas, \"Log-linear\"=s.loglin.elas, \"Quad\"=s.quad.elas,\r\n \"Cubic\"=s.cub.elas, \"Kernel\"=s.kern.elas, \"GLM-Log-Linear\" = sglm.loglin.elas)\r\nsapply(s.elas,mean)\r\nsapply(s.elas,range)\r\nsapply(s.elas,sd)\r\n\r\n### Calculate demand elasticities\r\n\r\np.inv = function(v,s.interp){\r\n pstar = rep(NA,length(v))\r\n s.inv = function(p,v,sfunc){ ((predict(sfunc,p))$y*p - v) }\r\n for(i in 1:length(v)){\r\n pstar[i] = (uniroot(s.inv,c(0.0001,100),v=v[i],sfunc=s.interp))$root\r\n }\r\n return(pstar)\r\n}\r\n\r\ns.lin.interp = interpSpline(pgrid,s.lin,na.action=na.omit,bSpline=TRUE)\r\ns.loglin.interp = interpSpline(pgrid,s.loglin,na.action=na.omit,bSpline=TRUE)\r\ns.quad.interp = interpSpline(p.quad,s.quad,na.action=na.omit,bSpline=TRUE)\r\ns.cub.interp = interpSpline(p.cub,s.cub,na.action=na.omit,bSpline=TRUE)\r\ns.kern.interp = interpSpline(s.kern$p,s.kern$s,na.action=na.omit,bSpline=TRUE)\r\nsglm.loglin.interp = interpSpline(pgrid,sglm.loglin,na.action=na.omit,bSpline=TRUE)\r\n\r\np.lin.inv = p.inv(v,s.lin.interp)\r\np.loglin.inv = p.inv(v,s.loglin.interp)\r\np.quad.inv = p.inv(v,s.quad.interp)\r\np.cub.inv = p.inv(v,s.cub.interp)\r\np.kern.inv = p.inv(v,s.kern.interp)\r\np.glmloglin.inv = p.inv(v,sglm.loglin.interp)\r\n\r\nelas.lin = calc.average.elas(p.lin.inv,s.lin.interp)\r\nelas.loglin = calc.average.elas(p.loglin.inv,s.loglin.interp)\r\nelas.quad = calc.average.elas(p.quad.inv,s.quad.interp)\r\nelas.cub = calc.average.elas(p.cub.inv,s.cub.interp)\r\nelas.kern = calc.average.elas(p.kern.inv,s.kern.interp)\r\nelas.glmloglin = calc.average.elas(p.glmloglin.inv,sglm.loglin.interp)\r\n\r\n\r\np.loglin.inv.median = p.inv(median(v),s.loglin.interp)\r\nelas.loglin.median = calc.average.elas(p.loglin.inv.median,s.loglin.interp)\r\n\r\np.glmloglin.inv.median = p.inv(median(v),sglm.loglin.interp)\r\nelas.glmloglin.median = calc.average.elas(p.glmloglin.inv.median,sglm.loglin.interp)\r\n\r\n\r\n\r\n## ----Calculate-the-elasticity-of-substitution-for-land-vs-non-land-inputs-----\r\n\r\nn = 50\r\nL = lotarea\r\nm = v - exp(lm.loglin$coefficients[1] + lm.loglin$coefficients[2]*log(v))\r\nM = m*L\r\nLseq = seq(min(L),max(L),length.out=n)\r\nMseq = seq(min(M),max(M),length.out=n)\r\n\r\nn = 50\r\nL = lotarea\r\nm_glm = v - exp(glm.loglin$coefficients[1] + glm.loglin$coefficients[2]*log(v))\r\nM_glm = m_glm*L\r\nLseq_glm = seq(min(L),max(L),length.out=n)\r\nMseq_glm = seq(min(M_glm),max(M_glm),length.out=n)\r\n\r\n\r\n\r\n## ----Decclare-Functions----\r\n\r\npfunc.CD = function(k,Lseq,Mseq){\r\n Q = matrix(NA,nrow=length(Lseq),ncol=length(Mseq))\r\n A = 1/((1-k)^(1-k))\r\n for(i in 1:(length(Lseq))){ for(k in 1:(length(Mseq))){\r\n Q[i,k] = A*(Lseq[i]^k)*(Mseq[k]^(1-k))\r\n }}\r\n return(Q)\r\n}\r\n\r\nQ.CD = pfunc.CD(lm.lin$coefficients[1],Lseq,Mseq)\r\npersp(Lseq,Mseq,Q.CD,theta=-20,phi=45,xlim=c(500000,1200000),ylim=c(20000,300000))\r\n\r\npfunc.full = function(Lseq,Mseq,prod.interp){\r\n Q = matrix(NA,nrow=length(Lseq),ncol=length(Mseq))\r\n for(i in 1:(length(Lseq))){\r\n Q[i,] = pfunc.full2(Lseq[i],Mseq,prod.interp)\r\n }\r\n return(Q)\r\n}\r\n\r\npfunc.full2 = function(lval,mval,prod.interp){\r\n return(lval*(predict(prod.interp,mval/lval)$y))\r\n}\r\n\r\npfunc.full.L = function(lval, mval,prod.interp, ord = 1){\r\n temp = function(x,mval){ return(pfunc.full2(x,mval,prod.interp))}\r\n return(fdiff(lval, temp, h=NULL, order=ord, accur=4, mval))\r\n}\r\n\r\npfunc.full.M = function(mval,lval,prod.interp, ord = 1){\r\n temp = function(x,lval){ return( pfunc.full2(lval,x,prod.interp))}\r\n return(fdiff(mval, temp, h=NULL, order=ord, accur=4, lval))\r\n}\r\n\r\npfunc.full.LM = function(Lval, Mval, prod.interp){\r\n h = (.Machine$double.eps)^(1/3)*abs(min(Lval,Mval))\r\n\r\n f.xy = pfunc.full2(Lval+h, Mval+h, prod.interp)\r\n f.x_y = pfunc.full2(Lval+h, Mval-h, prod.interp)\r\n f._xy = pfunc.full2(Lval-h, Mval+h, prod.interp)\r\n f._x_y = pfunc.full2(Lval-h, Mval-h, prod.interp)\r\n\r\n return(((f.xy-f.x_y)-(f._xy-f._x_y))/(4*h^2))\r\n}\r\n\r\ncalc.elas.sub = function(Lseq, Mseq, prod.interp){\r\n n.L = length(Lseq)\r\n n.M = length(Mseq)\r\n Q.elas.sub = matrix(NA,nrow=n.L, ncol=n.M)\r\n for(i in 1:n.L){\r\n for(k in 1:n.M){\r\n F.L = pfunc.full.L(Lseq[i],Mseq[k],prod.interp, ord=1)\r\n F.M = pfunc.full.M(Mseq[k],Lseq[i],prod.interp, ord=1)\r\n F.LL = pfunc.full.L(Lseq[i],Mseq[k],prod.interp, ord=2)\r\n F.MM = pfunc.full.M(Mseq[k],Lseq[i],prod.interp, ord=2)\r\n F.LM = pfunc.full.LM(Lseq[i],Mseq[k],prod.interp)\r\n\r\n numer = F.L*F.M*(F.L*Lseq[i] + F.M*Mseq[k])\r\n denom = Lseq[i]*Mseq[k]*((2*F.L*F.M*F.LM) - ((F.L^2)*F.MM) - ((F.M^2)*F.LL))\r\n\r\n Q.elas.sub[i,k] = numer/denom\r\n }\r\n }\r\n return(Q.elas.sub)\r\n}\r\n\r\n# A function to compute highly accurate first- and second-order derivatives\r\n# From Fornberg and Sloan (Acta Numerica, 1994, p. 203-267; Table 1, page 213)\r\nfdiff <- function(x, fun, h=NULL, order=1, accur=4, ...) {\r\n macheps <- .Machine$double.eps\r\n\r\n if (order==1) {\r\n if(is.null(h)) h <- macheps^(1/3)* abs(x)\r\n ifelse (accur==2, w <- c(-1/2,1/2), w <- c(1/12,-2/3, 2/3,-1/12))\r\n ifelse (accur==2, xd <- x + h*c(-1,1), xd <- x + h*c(-2,-1,1,2))\r\n return(sum(w*fun(xd,...))/h)\r\n }\r\n else if (order==2) {\r\n if(is.null(h)) h <- macheps^(1/4)* abs(x)\r\n ifelse (accur==2, w <- c(1,-2,1), w <- c(-1/12,4/3,-5/2,4/3,-1/12))\r\n ifelse (accur==2, xd <- x + h*c(-1,0,1), xd <- x + h*c(-2,-1,0,1,2))\r\n return(sum(w*fun(xd,...))/h^2)\r\n }\r\n}\r\n\r\n# y is a data frame, x is a matrix\r\nplot.with.legend = function(x,y,col=1:ncol(x),lty=1:ncol(x),xlim=NULL,ylim=NULL,\r\n titles=names(y),lposx=(max(x)-max(x)/4),lposy=max(y)/3,main=\"\",xl=\"\",yl=\"\",...){\r\n matplot(x,as.matrix(y),col=col, lty=lty,lwd=c(2,2,2,2), type=\"l\",\r\n main=main,xlab=xl,ylab=yl,xlim=xlim,ylim=ylim, ...)\r\n legend(lposx,lposy, titles, col=col, lty=lty)\r\n}\r\n\r\n### Calculate the derivative of a function over a given range of values\r\ncalc.deriv = function(grid,fun,interp.obj=NULL,high.density=FALSE){\r\n require(splines)\r\n fun.interp = NULL\r\n if(! is.null(interp.obj)){\r\n fun.interp = interp.obj\r\n }\r\n else if(!high.density && length(grid)>200){\r\n interp.grid = rep(NA,200)\r\n interp.grid[1] = grid[1]\r\n interp.grid[200] = grid[200]\r\n interp.grid = sample(grid,198)\r\n fun.grid = fun[interp.grid]\r\n fun.interp = interpSpline(interp.grid,fun.grid,na.action=na.omit,bSpline=FALSE)\r\n }\r\n else{\r\n fun.interp = interpSpline(grid,fun,na.action=na.omit,bSpline=FALSE)\r\n }\r\n d = rep(NA,length(grid))\r\n for(i in 1:length(grid)){\r\n d[i] = fdiff(grid[i],function(x){(predict(fun.interp,x))$y})\r\n }\r\n return(list(x=grid,d=d))\r\n}\r\n\r\ncalc.elas = function(grid,sfunc,bspline=TRUE){\r\n require(splines)\r\n s.interp = interpSpline(grid,sfunc,na.action=na.omit,bSpline=bspline)\r\n s.elas = rep(NA,length(grid))\r\n for(i in 1:length(grid)){\r\n s.elas[i] = (fdiff(grid[i],function(x){(predict(s.interp,x))$y}))*(grid[i]/sfunc[i])\r\n }\r\n return(s.elas)\r\n}\r\n\r\n### pa - actual set of prices corresponding to the data\r\n### s - supply function\r\ncalc.average.elas = function(pa,s.interp,bspline=TRUE){\r\n require(splines)\r\n s.pred = predict(s.interp,pa)\r\n s.elas = rep(NA,length(pa))\r\n for(i in 1:length(pa)){\r\n s.elas[i] = (fdiff(pa[i],function(x){(predict(s.interp,x))$y}))*(pa[i]/s.pred$y[i])\r\n }\r\n return(s.elas)\r\n}\r\n## ----Simulate-supply-and-production-functions-to-calcalate-standard-errors-----\r\nrequire(splines)\r\nprod.lin.interp = interpSpline(m.lin,s.lin,na.action=na.omit,bSpline=TRUE)\r\nprod.loglin.interp = interpSpline(m.loglin,s.loglin,na.action=na.omit,bSpline=TRUE)\r\nprod.quad.interp = interpSpline(m.quad,s.quad,na.action=na.omit,bSpline=TRUE)\r\nprod.cub.interp = interpSpline(m.cub,s.cub,na.action=na.omit,bSpline=TRUE)\r\nprod.glmloglin.interp = interpSpline(m.glmloglin,sglm.loglin,na.action=na.omit,bSpline=TRUE)\r\n\r\nrequire(R.basic)\r\n\r\nQ = pfunc.full(Lseq, Mseq,prod.loglin.interp)\r\nQ.vec = as.vector(Q)\r\nL.vec = as.vector(rep(Lseq,n))\r\nM.vec = rep(NA, length(Q.vec))\r\nfor(i in 1:n){ for(k in 1:n){\r\n M.vec[(i-1)*n + k] = Mseq[i]\r\n}}\r\nplot3d(L.vec,M.vec,Q.vec)\r\n\r\nQ_glm = pfunc.full(Lseq_glm, Mseq_glm,prod.glmloglin.interp)\r\nQ.vec.glm = as.vector(Q_glm)\r\nL.vec.glm = as.vector(rep(Lseq_glm,n))\r\nM.vec.glm = rep(NA, length(Q.vec.glm))\r\nfor(i in 1:n){ for(k in 1:n){\r\n M.vec.glm[(i-1)*n + k] = Mseq_glm[i]\r\n}}\r\nplot3d(L.vec.glm,M.vec.glm,Q.vec.glm)\r\n\r\nQ.elas.loglin = calc.elas.sub(Lseq, Mseq, prod.loglin.interp)\r\nQ.elas.lin = calc.elas.sub(Lseq, Mseq, prod.lin.interp)\r\nQ.elas.quad = calc.elas.sub(Lseq, Mseq, prod.quad.interp)\r\nQ.elas.cub = calc.elas.sub(Lseq, Mseq, prod.cub.interp)\r\nQ.elas.glmloglin = calc.elas.sub(Lseq_glm, Mseq_glm, prod.glmloglin.interp)\r\n\r\n\r\nsup.loglin = function(grid,parms){\r\n alpha = as.numeric(exp(parms[1])*parms[2])\r\n beta = as.numeric(parms[2] - 1)\r\n return((1/grid)*((1 + (beta/alpha)*log(grid))^(1/beta)))\r\n}\r\n\r\nsup.glmloglin = function(grid,parms){\r\n alpha = as.numeric(exp(parms[1])*parms[2])\r\n beta = as.numeric(parms[2] - 1)\r\n return((1/grid)*((1 + (beta/alpha)*log(grid))^(1/beta)))\r\n}\r\n\r\n\r\nprod.loglin = function(q,s){\r\n v.hat = s.loglin*pgrid\r\n lm.loglin.fitted = exp(lm.loglin$coefficients[1] + lm.loglin$coefficients[2]*log(v.hat))\r\n m.loglin = v.hat-lm.loglin.fitted\r\n return(list(m=m.loglin,q=s))\r\n}\r\n\r\nprod.glmloglin = function(q,s){\r\n v.hat = sglm.loglin*pgrid\r\n glm.loglin.fitted = exp(glm.loglin$coefficients[1] + glm.loglin$coefficients[2]*log(v.hat))\r\n m.loglin = v.hat-glm.loglin.fitted\r\n return(list(m=m.loglin,q=s))\r\n}\r\n\r\n\r\nsim.sup.prod = function(mod,grid,sfunc,pfunc,nsim){\r\n r = mod$coefficients[,\"Estimate\"]\r\n sd = mod$coefficients[,\"Std. Error\"]\r\n r.sim = matrix(NA,nrow=nsim,ncol=length(r))\r\n for(i in 1:length(r)){\r\n r.sim[,i] = rnorm(nsim,mean=r[i],sd=sd[i])\r\n }\r\n\r\n s.sd = rep(NA,length(grid))\r\n s.mat = matrix(NA,nrow=length(grid),ncol=nsim)\r\n for(k in 1:length(grid)){\r\n for(i in 1:nsim){\r\n s.mat[k,i] = sfunc(grid[k],r.sim[i,])\r\n }\r\n s.sd[k] = sd(s.mat[k,])\r\n }\r\n\r\n p.sd = rep(NA,length(grid))\r\n p.mat = matrix(NA,nrow=length(grid),ncol=nsim)\r\n for(i in 1:nsim){\r\n ## Calculate the prod function for this supply function\r\n pfunc.temp = pfunc(grid,s.mat[,i])\r\n p.mat[,i] = pfunc.temp$q\r\n }\r\n for(k in 1:length(grid)) p.sd[k] = sd(p.mat[k,])\r\n\r\n return(list(s.sd=s.sd,p.sd=p.sd))\r\n}\r\n\r\nsim.funcs = sim.sup.prod(summary(lm.loglin),pgrid,sup.loglin,prod.loglin,100)\r\n\r\ns.loglin.ub = s.loglin + 2*sim.funcs$s.sd\r\ns.loglin.lb = s.loglin - 2*sim.funcs$s.sd\r\nprod.loglin.lb = s.loglin - 2*sim.funcs$p.sd\r\nprod.loglin.ub = s.loglin + 2*sim.funcs$p.sd\r\n\r\n# Supply and production plots\r\nplot(s.loglin,pgrid,type=\"l\",main=\"Loglin Supply Function with \\n 95% Confidence Band\",xlab=\"Supply\",ylab=\"Price\", xlim=c(0,40))\r\nlines(s.loglin.lb,pgrid,col=\"red\",lty=2)\r\nlines(s.loglin.ub,pgrid,col=\"red\",lty=2)\r\n\r\nplot(m.loglin,s.loglin, type=\"l\",main=\"Loglin Production Function with \\n 95% Confidence Band\",xlab=\"m\",ylab=\"q\", xlim=c(0,80))\r\nlines(m.loglin, prod.loglin.ub, col=\"red\",lty=2)\r\nlines(m.loglin, prod.loglin.lb, col=\"red\",lty=2)\r\n\r\n# Supply and production plots in log-log scale\r\nplot(log(s.loglin),log(pgrid),type=\"l\",main=\"Log-linear Supply Function with \\n 95% Confidence Band\",\r\n xlab=\"log(Supply)\",ylab=\"log(Price)\", xlim=c(0,log(40)), lwd=2)\r\nlines(log(s.loglin.lb),log(pgrid),col=\"black\",lty=2)\r\nlines(log(s.loglin.ub),log(pgrid),col=\"black\",lty=2)\r\n\r\nplot(log(m.loglin),log(s.loglin), type=\"l\",main=\"Log-linear Production Function with \\n 95% Confidence Band\",\r\n xlab=\"log(m)\",ylab=\"log(q)\", xlim=c(0,log(80)), lwd=2)\r\nlines(log(m.loglin), log(prod.loglin.ub), col=\"black\",lty=2)\r\nlines(log(m.loglin), log(prod.loglin.lb), col=\"black\",lty=2)\r\n\r\n# Supply and production plots in GLM log-log scale\r\nsim.glmfuncs = sim.sup.prod(summary(glm.loglin),pgrid,sup.glmloglin,prod.glmloglin,100)\r\n\r\ns.glmloglin.ub = sglm.loglin + 2*sim.glmfuncs$s.sd\r\ns.glmloglin.lb = sglm.loglin - 2*sim.glmfuncs$s.sd\r\nprod.glmloglin.lb = sglm.loglin - 2*sim.glmfuncs$p.sd\r\nprod.glmloglin.ub = sglm.loglin + 2*sim.glmfuncs$p.sd\r\n\r\n# Supply and production plots\r\nplot(sglm.loglin,pgrid,type=\"l\",main=\"GLM-Loglin Supply Function with \\n 95% Confidence Band\",xlab=\"Supply\",ylab=\"Price\", xlim=c(0,40))\r\nlines(s.glmloglin.lb,pgrid,col=\"red\",lty=2)\r\nlines(s.glmloglin.ub,pgrid,col=\"red\",lty=2)\r\n\r\nplot(m.glmloglin,sglm.loglin, type=\"l\",main=\"GLM-Loglin Production Function with \\n 95% Confidence Band\",xlab=\"m\",ylab=\"q\", xlim=c(0,80))\r\nlines(m.glmloglin, prod.glmloglin.ub, col=\"red\",lty=2)\r\nlines(m.glmloglin, prod.glmloglin.lb, col=\"red\",lty=2)\r\n\r\n# Supply and production plots in log-log scale\r\nplot(log(sglm.loglin),log(pgrid),type=\"l\",main=\"GLM-Log-linear Supply Function with \\n 95% Confidence Band\",\r\n xlab=\"log(Supply)\",ylab=\"log(Price)\", xlim=c(0,log(40)), lwd=2)\r\nlines(log(s.glmloglin.lb),log(pgrid),col=\"black\",lty=2)\r\nlines(log(s.glmloglin.ub),log(pgrid),col=\"black\",lty=2)\r\n\r\nplot(log(m.glmloglin),log(sglm.loglin), type=\"l\",main=\"GLM-Log-linear Production Function with \\n 95% Confidence Band\",\r\n xlab=\"log(m)\",ylab=\"log(q)\", xlim=c(0,log(80)), lwd=2)\r\nlines(log(m.glmloglin), log(prod.glmloglin.ub), col=\"black\",lty=2)\r\nlines(log(m.glmloglin), log(prod.glmloglin.lb), col=\"black\",lty=2)\r\n\r\n\r\n###########################################\r\n\r\n\r\n", "meta": {"hexsha": "37d3a8312442228a6e8417ee7d4880565b238e5c", "size": 25035, "ext": "r", "lang": "R", "max_stars_repo_path": "Notes/supply_004.r", "max_stars_repo_name": "ReplicationStudy/-ReplicationStudyToEstimatePFforHousingData598-", "max_stars_repo_head_hexsha": "d9d009254ef536d0ae37c8343f484067e36a609b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notes/supply_004.r", "max_issues_repo_name": "ReplicationStudy/-ReplicationStudyToEstimatePFforHousingData598-", "max_issues_repo_head_hexsha": "d9d009254ef536d0ae37c8343f484067e36a609b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/supply_004.r", "max_forks_repo_name": "ReplicationStudy/-ReplicationStudyToEstimatePFforHousingData598-", "max_forks_repo_head_hexsha": "d9d009254ef536d0ae37c8343f484067e36a609b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-02-28T21:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T20:08:08.000Z", "avg_line_length": 36.4410480349, "max_line_length": 138, "alphanum_fraction": 0.6439384861, "num_tokens": 8776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7275281767624262}} {"text": "#Copyright (c) 2016 Riccardo Francescato\n#insert a vector for eache experiment repetition\nRawData0 = c(130,34,20,\n\t\t\t150,136,25,\n\t\t\t138,174,96)\nRawData1 = c(155,40,70,\n\t\t\t188,122,70,\n\t\t\t110,120,104)\nRawData2 = c(74,80,82,\n\t\t\t159,106,58,\n\t\t\t168,150,82)\nRawData3 = c(180,75,58,\n\t\t\t126,115,45,\n\t\t\t160,139,60)\n\nRawData = c(RawData0,RawData1,RawData2,RawData3)\n\na = 3 # numer of treatments A (columns)\nb = 3 # numer of treatments B (rows)\nn = 4 # numer of repetitions\nN = a*b*n\nalpha = .05\nSRawData = RawData0+RawData1+RawData2+RawData3\nSRawMatrix = matrix(SRawData,ncol=a,byrow = TRUE)\nRawMatrix = matrix(RawData,ncol=a,byrow = TRUE)\n\n# ANOVA\nsum(SRawMatrix[1,])\n\nSSt <- sum(RawData^2) - sum(RawData)^2/N\nSSa = 0\nfor (i in 1:b){\n\tSSa=SSa+sum(SRawMatrix[i,])^2\n}\nSSa=(1/(b*n))*SSa-sum(RawData)^2/N\n\nSSb = 0\nfor (i in 1:a){\n\tSSb=SSb+sum(SRawMatrix[,i])^2\n}\nSSb=(1/(a*n))*SSb-sum(RawData)^2/N\n\nSSab = (1/n)*sum(SRawMatrix^2) - sum(RawData)^2/N - SSa - SSb\n\t\t\t\nSSe = SSt - SSab - SSa - SSb\n\nMSa\t= SSa/(a-1)\nMSb = SSb/(b-1)\nMSab = SSab/((a-1)*(b-1))\nMSe = SSe/(a*b*(n-1))\nF0a = MSa/MSe\nF0b = MSb/MSe\nF0ab = MSab/MSe\nFa = qf(alpha,df1=(a-1),df2=(a*b*(n-1)),lower.tail=F)\nFb = qf(alpha,df1=(b-1),df2=(a*b*(n-1)),lower.tail=F)\nFab = qf(alpha,df1=((a-1)*(b-1)),df2=(a*b*(n-1)),lower.tail=F)\ncat(paste0(\" Treatment A SS: \",SSa,\" Df: \", a-1 ,\" MS: \",MSa, \" F0a: \",F0a,\" Fa crit: \",Fa,\n\t\t\"\\n Treatment B SS: \",SSb,\" Df: \", b-1 ,\" MS: \",MSb,\" F0b: \",F0b,\" Fb crit: \",Fb,\n\t\t\"\\n Interaction AB SS: \",SSab,\" Df: \", (a-1)*(b-1) ,\" MS: \",MSab,\" F0ab: \",F0ab,\" Fab crit: \",Fab,\n\t\t\"\\n Error SS: \",SSe,\" Df: \",a*b*(n-1) ,\" MS: \",MSe,\n\t\t\"\\n Total SS: \",SSt,\" Df: \", (a*b*n)-1,\n\t\t\"\\n Fcrit: \", Fa))", "meta": {"hexsha": "81c5ac0457deabcb2e1c3f35e4b8a4c97f2c9f84", "size": 1677, "ext": "r", "lang": "R", "max_stars_repo_path": "ANOVA_factorial.r", "max_stars_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_stars_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ANOVA_factorial.r", "max_issues_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_issues_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ANOVA_factorial.r", "max_forks_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_forks_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0483870968, "max_line_length": 101, "alphanum_fraction": 0.5909361956, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.72743425859949}} {"text": "# Programming in `R`\n# Thanks to Sina Rasooli!\n\n# How to run script?!\n\n## Sum\n3 + 4\n\n## Subtract\n2 - 5\n\n## Multiply\n1.2 * 6.8\n\n## Divide\n(123 + 321) / 2\n\n## Exponentiation\n3^5\n\n## Modulo\n37%%9\n\n## Assign Variable\nx <- 42\nz <- \"salam\"\ny = 32\n23 -> x\n\n## Print\nx\ny\n\n## Arithmatic with Variables\nx + y\nx - y\nx * y\nx^y\nx / y\nx %% y\n\n## Arithmatic and Assignment\nz = x + y\nz\n\n## Variable Types\n### Numerics\nx = 1.2\nx = 3\n### Logical\ny = FALSE # `F` or `FALSE`\ny = T # `T` or `TRUE`\n### Character\nz = \"salam\"\n\n## Determine Class\nclass(x)\nclass(y)\nclass(z)\n\n## R Help\n?mean\nhelp(lm)\n??mean\nexample(\"median\")\n\n\n## Vectors\nx = vector()\nx\nx = c(1, 2, 3)\nx\ny = c(\"a\",\"b\",\"c\")\ny\nz = c(T,F,F)\nz\n\n## Vectors: What if Mixed?\nx = c(3,T)\nx\nclass(x)\ntypeof(x)\nx = c(4,\"a\")\nx\nx = c(5, F, \"b\")\nx\n\n## Attributes: name\nx_sleep = c(6.5, 7.5, 7, 8, 6)\nx_names = c(\"Saturday\", \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\")\nnames(x_sleep) = x_names\nx_sleep\nx_sleep[\"Monday\"] = 2\nx_sleep[\"Shanbe\"] = 4\nx_sleep\nx_sleep[1]\n\n## Vector Summation\nx = c(1,2,3)\ny = c(4,5,6)\nx+y\n\n## Vector Simple Functions\nx = c(1.2,3.4,5.6)\nsum(x)\nmean(x)\nmedian(x)\nsd(x)\n\n## Vector: Indexing\nx_sleep = c(6.5, 7.5, 7, 8, 6)\nx_names = c(\"Saturday\", \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\")\nx_sleep[2]\nx_sleep[-2]\nnames(x_sleep) = x_names\nx_sleep[\"Tuesday\"]\n\n## Vector Slicing\nx = 1:10\nx\nx_sleep[c(2,3,4)]\nx_sleep[\"Sunday\":\"Tuesday\"]\ny = c(4,3,1)\nx_sleep[y]\nx_sleep[c(\"Sunday\",\"Tuesday\")]\nx_sleep[c(T,T,T,F,T)]\nx_sleep\nx_sleep[-c(1,2)]\n\n\n## Vector Selection\n?sleep\nsleep\nx = sleep$extra\nx\nsleep$ID\nx_selection = x > 1.1\nx_selection\ny = x[ x_selection ]\ny\n\n## Matrices\nmatrix( data = 1:10, byrow = T, nrow = 5 )\n\n## Matrics: from Vectors\nx = c( 460.998, 314.4 )\ny = c( 290.475, 247.9 )\nz = c( 309.306, 165.8 )\nw = c( x, y, z )\nm = matrix( data = w, byrow = T, nrow = 3 )\n\n## Matrics: Attributes\nm\ncolnames(m) = c(\"A\",\"B\")\nrownames(m) = c(\"gozashte\", \"haal\",\"aayande\")\n\n## Matrices: Slicing\nm[2,]\nm[\"haal\",]\nm[\"gozashte\",1]\nm[c(\"aayande\",\"gozashte\"),\"A\"]\n\n## Matrices: simple Functions\nrowSums(m)\ncolSums(m)\ncolMeans(m)\nrowMeans(m)\n\n\n## Matrices: rbind, cbind\ncbind( m, rowSums(m) )\nrbind( m, colSums(m) )\n\n## Matrices: scalar arithmatics\nm + 1000\nm - 1000\nm * 2\nm / 5\nm %% 3\n\n## Matrices: multiply by vector\nm * c(10,100,1000)\nm * c(1, 0)\n\n## Matrices: Matrix Multiplications\nm %*% c(1,0)\nc(1,0,0) %*% m\nt(m) %*% m\nm %*% t(m)\n\n## Factors\nx = c(\"m\",\"f\",\"f\",\"m\",\"m\")\nx = factor(x)\nx\nclass(x)\n## Factors: Ordered\nx = c(\"a\",\"a\",\"c\",\"b\",\"c\",\"a\")\ny = factor( x, ordered = T, levels = c(\"c\",\"b\",\"a\") )\nx = c(1,2,3,2,3)\nx\nx = factor(x)\nx\n\n## Factors: Levels\nlevels(y) = c(\"A\",\"B\",\"C\")\ny\n\n## Factors: summary\nsummary(x)\nsummary(y)\n\n## Factors: comparison\ny[3] > y[1]\n\n## DataFrames: example\nclass(mtcars)\ntypeof(mtcars)\nhelp(\"mtcars\")\n\n## DataFrames: head\n?mtcars\nView(mtcars)\nhead(mtcars)\ntail(mtcars)\ndim(mtcars)\nnrow(mtcars)\nncol(mtcars)\n\n## DataFrames: str\nstr(mtcars)\n\n## DataFrames: summary\nsummary(mtcars)\n\n## DataFrames: constructor\nnames = c(\"Yashar\",\"Sina\",\"Hoda\",\"Maryam\")\nages = c(22,24,22,21)\nrow_ids = c(1,1,2,2)\nclass_df = data.frame(names, ages, row_ids)\nclass_df\n\n## DataFrames: slicing\nclass_df[1,1]\nclass_df[2,]\nclass_df[,3]\nclass_df[1:2,2:3]\nclass_df[,1]\nclass_df$names\nclass_df[,\"row_ids\"]\nclass_df$ages < 23\nclass_df[class_df$ages < 23 ,]\n\n\n\n## DataFrames: subset\nsubset( class_df, subset = ( ages < 23 ) )\n\n## DataFrames: order\na = c(3,1,4,5,2)\norder(a)\na[ order(a) ]\n\nclass_df[order(class_df$ages), ]\n\n## Lists: construction\na = 1:10\nb = matrix(1:10, byrow = T, nrow = 5)\nc = mtcars[1:10,]\nmy_list = list( a,b,c )\nmy_list\n\n## Lists: names\nmy_list = list( W = a, U = b, V = c )\nmy_list\n\nnames(my_list) = c(\"A\",\"B\",\"C\")\nmy_list\n\n## Lists: slicing\nmy_list$A\nmy_list[[3]]\n", "meta": {"hexsha": "30fa4ef55efcb4da0f58ca3d968f93ad1582b894", "size": 3732, "ext": "r", "lang": "R", "max_stars_repo_path": "statistics98/Programming.r", "max_stars_repo_name": "nimacgit/courses", "max_stars_repo_head_hexsha": "3474b9f854a4c3601e578101d95940c38c912a69", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "statistics98/Programming.r", "max_issues_repo_name": "nimacgit/courses", "max_issues_repo_head_hexsha": "3474b9f854a4c3601e578101d95940c38c912a69", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "statistics98/Programming.r", "max_forks_repo_name": "nimacgit/courses", "max_forks_repo_head_hexsha": "3474b9f854a4c3601e578101d95940c38c912a69", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.2340425532, "max_line_length": 67, "alphanum_fraction": 0.6066452304, "num_tokens": 1541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7273697064802582}} {"text": "r <- function(x, log = TRUE){\n xbar <- mean(x, na.rm = TRUE)\n ans <- n*(xbar - .5)\n if(!log) ans <- exp(ans)\n return(ans)\n}\n\ntheta0 <- 0\ntheta1 <- 1\nn <- 100\nalpha0 <- 0.05\ncprime <- qnorm(1-alpha0, sd = 1/sqrt(n))\ncprime\nlogc <- n*(cprime-.5)\n\nX0 <-rnorm(n, mean = theta0, sd = 1) \nX1 <-rnorm(n, mean = theta1, sd = 1) \n\n## Uma observação: este teste não é ruim:\ncat(\"Rejeita H0 para X0?\", r(X0) > logc, \"\\n\")\ncat(\"Rejeita H0 para X1?\", r(X1) > logc, \"\\n\")\n\n## Porém...\ntype_II_prob <- function(n){\n ans <- pnorm(q = qnorm(1-alpha0, sd = 1/sqrt(n)), mean = theta1, sd = 1/sqrt(n), lower.tail = TRUE)\n} \nns <- c(1, 25, 100)\ndata.frame(n = ns, beta = type_II_prob(ns), logc = exp(ns*(cprime-.5)))\n\ncurve(type_II_prob, 1, 100,\n xlab = \"Tamanho de amostra (n)\", ylab = expression(beta(delta)))\n", "meta": {"hexsha": "3c11db12a2077665d31b36d45c63819b971c4e30", "size": 807, "ext": "r", "lang": "R", "max_stars_repo_path": "code/exemplo_9.2.5_DeGroot.r", "max_stars_repo_name": "jlduim/Statistical_Inference_BSc", "max_stars_repo_head_hexsha": "6dfa2441c0b09bfe39a68367a242a81d76c41778", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2020-08-03T15:42:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T15:43:10.000Z", "max_issues_repo_path": "code/exemplo_9.2.5_DeGroot.r", "max_issues_repo_name": "jlduim/Statistical_Inference_BSc", "max_issues_repo_head_hexsha": "6dfa2441c0b09bfe39a68367a242a81d76c41778", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-08-16T23:02:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-07T14:34:43.000Z", "max_forks_repo_path": "code/exemplo_9.2.5_DeGroot.r", "max_forks_repo_name": "jlduim/Statistical_Inference_BSc", "max_forks_repo_head_hexsha": "6dfa2441c0b09bfe39a68367a242a81d76c41778", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-08-13T00:53:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:35:56.000Z", "avg_line_length": 25.21875, "max_line_length": 103, "alphanum_fraction": 0.5786864932, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7273530182552284}} {"text": "sample <- 50000\nX <- rexp(sample, 0.2)\nx <- data.frame(X = seq(1, sample , 1), Y = sort(X))\nplot(x,xlab=\"Position\",ylab=\"values\",main=\"Scatter_Plot for Exp distribution\")\n##\n\n\nlist <- split(X,seq(1,500,1))\n##\n\npdata1 <- rep(0, 100);\npdata2 <- rep(0, 100);\npdata3 <- rep(0, 100);\npdata4 <- rep(0, 100);\npdata5 <- rep(0, 100);\n\nfor(i in 1:100){\n val=round(X[i], 0);\n if(val <= 100){\n pdata1[val] = pdata1[val] + 1/ 100; \n }\n}\nfor(i in 101:200){\n val=round(X[i], 0);\n if(val <= 100){\n pdata2[val] = pdata2[val] + 1/ 100; \n }\n}\nfor(i in 201:300){\n val=round(X[i], 0);\n if(val <= 100){\n pdata3[val] = pdata3[val] + 1/ 100; \n }\n}\nfor(i in 301:400){\n val=round(X[i], 0);\n if(val <= 100){\n pdata4[val] = pdata4[val] + 1/ 100; \n }\n}\nfor(i in 401:500){\n val=round(X[i], 0);\n if(val <= 100){\n pdata5[val] = pdata5[val] + 1/ 100; \n }\n}\n\nxcols1 <- c(0:99)\nxcols2 <- c(0:99)\nxcols3 <- c(0:99)\nxcols4 <- c(0:99)\nxcols5 <- c(0:99)\n\nstr(pdata1)\nstr(xcols1)\n\nplot(xcols1, pdata1, \"l\", xlab=\"list1\", ylab=\"f(X)\", main=\"pdf\")\n\nstr(pdata2)\nstr(xcols2)\n\nplot(xcols2, pdata2, \"l\", xlab=\"list2\", ylab=\"f(X)\", main=\"pdf\")\n\nstr(pdata3)\nstr(xcols3)\n\nplot(xcols3, pdata3, \"l\", xlab=\"list3\", ylab=\"f(X)\", main=\"pdf\")\n\nstr(pdata4)\nstr(xcols4)\n\nplot(xcols4, pdata4, \"l\", xlab=\"list4\", ylab=\"f(X)\", main=\"pdf\")\n\nstr(pdata5)\nstr(xcols5)\n\nplot(xcols5, pdata5, \"l\", xlab=\"list5\", ylab=\"f(X)\", main=\"pdf\")\n\ncdata1 <- rep(0, 100)\n\ncdata1[1] <- pdata1[1]\n\nfor(i in 2:100){\n cdata1[i] = cdata1[i-1] + pdata1[i]\n}\n\nplot(xcols1, cdata1, \"o\", col=\"blue\", xlab=\"list1\", ylab=\"F(X)\", main=\"cdf\")\n\ncdata2 <- rep(0, 100)\n\ncdata2[1] <- pdata2[1]\n\nfor(i in 2:100){\n cdata2[i] = cdata2[i-1] + pdata2[i]\n}\n\nplot(xcols2, cdata2, \"o\", col=\"red\", xlab=\"list2\", ylab=\"F(X)\", main=\"cdf\")\n\ncdata3 <- rep(0, 100)\n\ncdata3[1] <- pdata3[1]\n\nfor(i in 2:100){\n cdata3[i] = cdata3[i-1] + pdata3[i]\n}\n\nplot(xcols3, cdata3, \"o\", col=\"green\", xlab=\"list3\", ylab=\"F(X)\", main=\"cdf\")\n\ncdata4 <- rep(0, 100)\n\ncdata4[1] <- pdata4[1]\n\nfor(i in 2:100){\n cdata4[i] = cdata4[i-1] + pdata4[i]\n}\n\nplot(xcols4, cdata4, \"o\", col=\"yellow\", xlab=\"list4\", ylab=\"F(X)\", main=\"cdf\")\n\ncdata5 <- rep(0, 100)\n\ncdata5[1] <- pdata5[1]\n\nfor(i in 2:100){\n cdata5[i] = cdata5[i-1] + pdata5[i]\n}\n\nplot(xcols5, cdata5, \"o\", col=\"grey\", xlab=\"list5\", ylab=\"F(X)\", main=\"cdf\")\n\nmn <- rep(0,500)\nstd <- rep(0,500)\n\ni=1\nfor(i in 1:500)\n{\n mn[i] <- mean(list[[i]])\n std[i] <- sd(list[[i]])\n}\nprint (mn[1])\nprint (mn[2])\nprint (mn[3])\nprint (mn[4])\nprint (mn[5])\nprint (std[1])\nprint (std[2])\nprint (std[3])\nprint (std[4])\nprint (std[5])\n##\n\npdata_m <- rep(0, 10);\n\nfor(i in 1:500){\n val1=round(mn[i], 0);\n if(val1 <= 10){\n pdata_m[val1] = pdata_m[val1] + 1/ 500; \n }\n}\n\nxcols_m <- c(1:10)\n\nstr(pdata_m)\nstr(xcols_m)\n\nplot(xcols_m, pdata_m, \"l\", xlab=\"mean\", ylab=\"f(X)\", main=\"pdf of means\")\n\ncdata_m <- rep(0, 10)\n\ncdata_m[1] <- pdata_m[1]\n\nfor(i in 2:10){\n cdata_m[i] = cdata_m[i-1] + pdata_m[i]\n}\n\nplot(xcols_m, cdata_m, \"o\", col=\"pink\", xlab=\"mean\", ylab=\"F(X)\", main=\"cdf of means\")\ntab <- table(round(mn))\nstr(tab)\nplot(tab, \"h\", xlab=\"Value\", ylab=\"Frequency\")\n##\n\nmnf <- rep(0, 1)\nstdf <- rep(0, 1)\nmnf <- mean(mn)\nstdf <- sd(mn)\n\nprint(mnf)\nprint(stdf)\n\n\n\n\n\n", "meta": {"hexsha": "9f5dcf1f9397f3a45f95c977495df2fd509dbff6", "size": 3213, "ext": "r", "lang": "R", "max_stars_repo_path": "160011.r", "max_stars_repo_name": "abhay-sr/251ass", "max_stars_repo_head_hexsha": "644429a990063a6604eae11781d61ac8aba1bafe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "160011.r", "max_issues_repo_name": "abhay-sr/251ass", "max_issues_repo_head_hexsha": "644429a990063a6604eae11781d61ac8aba1bafe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "160011.r", "max_forks_repo_name": "abhay-sr/251ass", "max_forks_repo_head_hexsha": "644429a990063a6604eae11781d61ac8aba1bafe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.734375, "max_line_length": 86, "alphanum_fraction": 0.568627451, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7273451138449002}} {"text": "##### 医学統計勉強会18第7回生存時間解析 R code #####\n\nlibrary(survival)\n\nx <- c(2, 4, 4, 5, 7, 8, 10)\t\t# 生存時間\ncens0 <- c(1, 1, 1, 1, 1, 1, 1)\t\t# censoring status: 打ち切り状態(0:打ち切り無し,1:打ち切り有り)\n\nSurv(x, cens0)\n\nfit0 <- survfit(Surv(x, cens0) ~ 1)\t# 生存関数のKaplan-Meier推定量を求める\n\nplot(fit0)\t\t\t\t\t\t# Kaplan-Meier curveの描画(信頼区間有り)\nplot(fit0, conf.int=FALSE, xlab=\"time\", ylab=\"Survival Function\")\t\t# Kaplan-Meier curveの描画(信頼区間有なし)\n\n\n\ncens1 <- c(1, 1, 1, 1, 0, 1, 0)\t\t# 7日目(5番目)と10日目(7番目)に打ち切り\n\nSurv(x, cens1)\n\nfit1 <- survfit(Surv(x, cens1) ~ 1)\t# 生存関数のKaplan-Meier推定量を求める\nplot(fit1, conf.int=FALSE, xlab=\"time\", ylab=\"Survival Function\")\n\n\n\n### 白血病患者に対する寛解期間の臨床比較試験 ###\n\nlibrary(MASS)\n\ndata(gehan)\n\nfit.gehan <- survfit(Surv(time, cens) ~ treat, data=gehan)\nplot(fit.gehan, mark.time=TRUE, col=c(\"blue\", \"red\"))\nlegend(25,1,legend=c(\"6-MP\", \"control\"), col=c(\"blue\", \"red\"), lty=1, bty=\"n\")\n\nsurvdiff(Surv(time, cens) ~ treat, data=gehan)\t\t# log-rank検定\n\nsurvdiff(Surv(time, cens) ~ treat, data=gehan, rho=1)\t\t# the Peto & Peto modification of the Gehan-Wilcoxon test\n\n\n\n### NCCTG Lung Cancer Data ###\nfit.lung <- survfit(Surv(time, status) ~ pat.karno, data=lung)\nplot(fit.lung, col=rainbow(8), main=\"NCCTG Lung Cancer Data\")\nlabel <- names(table(lung$pat.karno))\nlegend(800, 1, legend=label, lty=rep(1,8), col=rainbow(8), bty=\"n\")\n\nsurvdiff(Surv(time, status) ~ pat.karno, data=lung)\nsurvdiff(Surv(time, status) ~ pat.karno + strata(inst), data=lung)\n\n\n\n### Cox proportional hazard model: 白血病患者に対する寛解期間の臨床比較試験 ###\n\nfit.ph <- coxph(Surv(time, cens) ~ treat, data=gehan)\nsummary(fit.ph)\n\n### complementary log-log plot: Gehanの白血病データ ###\n\nplot(fit.gehan, fun=\"cloglog\", ylab=\"Log(-Log(survival))\", xlab=\"time\", lty=1:2)\nlegend(2, 0.6, c(\"control\", \"6-MP\"), lty=1:2)\n\n### Cox比例ハザードモデルにおける比例ハザード性の仮定についての、Schoenfeld residualによる検定 ###\ncox.zph(fit.ph)\n\n\n\n### 一般化加法モデルによる非線形モデル: 在郷軍人の肺がんデータ ###\n\nfit <- coxph(Surv(time, status) ~ trt + karno + age, data=veteran)\n\ncox.zph(fit)\t\t# karno, ageのp値は小さく比例ハザード性の破綻が示唆される\n\nlibrary(mgcv)\nfit.gam <- gam(time ~ trt + s(karno) + s(age), family=cox.ph(), weights=status, data=veteran)\nsummary(fit.gam)\nplot(fit.gam)\n", "meta": {"hexsha": "06ca0b3e78976add62f427a44f0c21ab5568d43e", "size": 2120, "ext": "r", "lang": "R", "max_stars_repo_path": "MedicalStatisticsClass/2019/7/code.r", "max_stars_repo_name": "shumez/stat", "max_stars_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MedicalStatisticsClass/2019/7/code.r", "max_issues_repo_name": "shumez/stat", "max_issues_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MedicalStatisticsClass/2019/7/code.r", "max_forks_repo_name": "shumez/stat", "max_forks_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1794871795, "max_line_length": 112, "alphanum_fraction": 0.6735849057, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7272913456827524}} {"text": "#!/usr/bin/Rscript\n\nrequire(deSolve)\n\n## ==============================================================================\n## Numerical solution of the SIR epidemiological model, a\n## system of ordinary differential equations with state variables\n## # susceptible (X), # infected (Y) # resistant (Z)\n## ==============================================================================\n\nparameters <- c(beta = 0.01,\n gamma = 0.01,\n m = 0.1)\n\nstate <- c(X = 100, Y = 1, Z = 0)\n\n## the ODE system\n\nlorenz <- function(t, state, parameters) {\n with(as.list(c(state, parameters)),{\n\n# rate of change\n\n dX <- -beta*X*Y + gamma*Z\n dY <- beta * X * Y - m*Y \n dZ <- m*Y - gamma * Z\n\n# return the rate of change\n\n list(c(dX, dY, dZ))\n\n })\n\n}\n\ntimes <- seq(0, 100, by = 0.01)\n\nout <- ode(y = state, times = times, func = lorenz, parms = parameters)\n\nhead(out)\n\npar(oma = c(0, 0, 3, 0))\nmatplot(out[,\"time\"],out[,2:4], xlab = \"Time (days)\", type=\"l\", ylab = \"Numbers\",col=\"black\")\nlegend(\"topright\", inset=0, legend=c(\"X (susceptible)\", \"Y (infected)\", \"Z (immune)\"), lty=1:3, col=\"black\", bty = \"n\", horiz=FALSE)\nmtext(outer = TRUE, side = 3, \"SIR Model\", cex = 1.5)\n", "meta": {"hexsha": "23dadde4af04ca7c2855e26bde20bb06e4dbf272", "size": 1217, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_sir_one_plot.r", "max_stars_repo_name": "siglun/etudes", "max_stars_repo_head_hexsha": "d78a76d9e6a58192041483b3ac90e9d2f5eb84fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simple_sir_one_plot.r", "max_issues_repo_name": "siglun/etudes", "max_issues_repo_head_hexsha": "d78a76d9e6a58192041483b3ac90e9d2f5eb84fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simple_sir_one_plot.r", "max_forks_repo_name": "siglun/etudes", "max_forks_repo_head_hexsha": "d78a76d9e6a58192041483b3ac90e9d2f5eb84fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4565217391, "max_line_length": 135, "alphanum_fraction": 0.4921939195, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813551535005, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.7271678469318379}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Goodness of Fit - Exercise 06\n\nrm(list = ls())\n\nobserved <- c(442, 38, 514, 6)\n\n(k <- length(observed))\n# 4\n\n(n <- sum(observed))\n# 1000\n\nEspectedProbabilities <- function(p) {\n c(0.5 * p, 0.5 * (1 - p), 0.5 * p ^ 2 + p * (1 - p), 0.5 * (1 - p) ^ 2)\n}\n\nLogLikelihood <- function(p, y) {\n sum(y * log(EspectedProbabilities(p)))\n}\n\nNegativeLogLikelihood <- function(...) {\n - LogLikelihood(...)\n}\n\nopt <- optim(0.5, NegativeLogLikelihood, y = observed, hessian = TRUE,\n lower = 10e-4, upper = 1 - 10e-4, method = 'L-BFGS-B')\n\n(p.hat <- opt$par)\n# 0.912941500560347\n\nexpected <- EspectedProbabilities(p.hat) * n\n\n(Q <- sum((observed - expected) ^ 2 / expected))\n# 3.08815842598583\n\n(pvalue <- 1 - pchisq(Q, 2))\n# 0.213508376478253\n", "meta": {"hexsha": "627e5be831eecf8a7f16f9492745c6a269e17943", "size": 808, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/goodness-of-fit/exercise-06.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/goodness-of-fit/exercise-06.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/goodness-of-fit/exercise-06.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7179487179, "max_line_length": 73, "alphanum_fraction": 0.6064356436, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644806, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7271492620563357}} {"text": "\r\n\r\n# Goal: \"Dummy variables\" in regression.\r\n\r\n# Suppose you have this data:\r\npeople = data.frame(\r\n age = c(21,62,54,49,52,38),\r\n education = c(\"college\", \"school\", \"none\", \"school\", \"college\", \"none\"),\r\n education.code = c( 2, 1, 0, 1, 2, 0 )\r\n )\r\n# Here people$education is a string categorical variable and\r\n# people$education.code is the same thing, with a numerical coding system.\r\npeople\r\n\r\n# Note the structure of the dataset --\r\nstr(people)\r\n# The strings supplied for `education' have been treated (correctly) as\r\n# a factor, but education.code is being treated as an integer and not as\r\n# a factor.\r\n\r\n\r\n# We want to do a dummy variable regression. Normally you would have:\r\n# 1 Chosen college as the omitted category\r\n# 2 Made a dummy for \"none\" named educationnone\r\n# 3 Made a dummy for \"school\" named educationschool\r\n# 4 Ran a regression like lm(age ~ educationnone + educationschool, people)\r\n# But this is R. Things are cool:\r\nlm(age ~ education, people)\r\n\r\n# ! :-)\r\n# When you feed him an explanatory variable like education, he does all\r\n# these steps automatically. (He chose college as the omitted category).\r\n\r\n# If you use an integer coding, then the obvious thing goes wrong --\r\nlm(age ~ education.code, people)\r\n# because he's thinking that education.code is an integer explanatory\r\n# variable. So you need to:\r\n\r\nlm(age ~ factor(education.code), people)\r\n# (he choose a different omitted category)\r\n\r\n# Alternatively, fix up the dataset --\r\npeople$education.code <- factor(people$education.code)\r\nlm(age ~ education.code, people)\r\n\r\n#\r\n# Bottom line:\r\n# Once the dataset has categorical variables correctly represented as factors, i.e. as\r\nstr(people)\r\n# doing OLS in R induces automatic generation of dummy variables while leaving one out:\r\nlm(age ~ education, people)\r\nlm(age ~ education.code, people)\r\n\r\n# But what if you want the X matrix?\r\nm <- lm(age ~ education, people)\r\nmodel.matrix(m)\r\n# This is the design matrix that went into the regression m.\r\n\r\n", "meta": {"hexsha": "25004b59e8bcbba5b313847902fa29d8a690cf2c", "size": 2034, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o2.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o2.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o2.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4745762712, "max_line_length": 88, "alphanum_fraction": 0.6966568338, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7268252043239787}} {"text": "library(diffeqr)\ndiffeqr::diffeq_setup()\n\nf <- function (u, p, t) {\n # State variables\n # ---------------\n # u1: rabbits\n # u2: foxes\n du1 = p[1]*u[1] - p[2]*u[1]*u[2]\n du2 = -p[3]*u[2] + p[4]*p[2]*u[1]*u[2]\n \n return(c(du1, du2))\n}\n\nu0 = c(10, 5)\ntspan <- list(0.0, 18.0)\np = c(1.0, 0.1, 1.5, 0.75)\nsol = diffeqr::ode.solve(f, u0, tspan, p=p, saveat=0.01)\n\nudf = as.data.frame(sol$u)\nmatplot(sol$t, udf, type = \"l\", xlab = \"Time\", ylab = \"Population\")\nlegend(\"topright\", c(\"Rabbits\", \"Foxes\"), lty = c(1,2), col = c(1,2), box.lwd = 0)", "meta": {"hexsha": "355068d3b147f3410ed0c0be78d5f23931d6b8e4", "size": 559, "ext": "r", "lang": "R", "max_stars_repo_path": "R/test_diffeqr.r", "max_stars_repo_name": "camrepo/ode_solver", "max_stars_repo_head_hexsha": "facb6d026440db51b3052e7a6b88184d749b5be0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T10:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T17:29:25.000Z", "max_issues_repo_path": "R/test_diffeqr.r", "max_issues_repo_name": "camrepo/ode_solver", "max_issues_repo_head_hexsha": "facb6d026440db51b3052e7a6b88184d749b5be0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/test_diffeqr.r", "max_forks_repo_name": "camrepo/ode_solver", "max_forks_repo_head_hexsha": "facb6d026440db51b3052e7a6b88184d749b5be0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-15T02:33:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T02:33:12.000Z", "avg_line_length": 25.4090909091, "max_line_length": 82, "alphanum_fraction": 0.5169946333, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509316, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.7268096388731868}} {"text": "newton <- function(f, fprime, x0, tol_approx=1e-8, tol_consec=1e-8){\n # Solves a given equation for its roots using Newton's Method given its derivative\n # and an initial guess. Also takes in function value tolerance and consecutive value tolerance.\n #\n # Args:\n # f (function): equation to be solved\n # fprime (function): derivative of f\n # x0 (numeric): initial guess\n # tol_approx (numeric): tolerance from 0\n # tol_consec (numeric): tolerance from previous value\n # Returns:\n # numeric: root of f\n x1 <- x0\n x0 <- x0 - 1 # To enter loop\n while (abs(f(x1))>tol_approx || abs(x1-x0)>tol_consec){\n x0 <- x1\n x1 <- x1 - f(x0)/fprime(x0)\n }\n return(x1)\n}\n\nbisection <- function(f, a, b, tol_approx=1e-8, tol_consec=1e-8){\n # Solves a given equation for its roots using Bisection Method given an initial\n # interval. Also takes in function value tolerance and consecutive value tolerance.\n #\n # Args:\n # f (function): equation to be solved\n # a (numeric): left bound (function evaluation must be of opposite sign than b)\n # b (numeric): right bound (function evaluation must be of opposite sign than a)\n # tol_approx (numeric): tolerance from 0\n # tol_consec (numeric): tolerance from previous value\n # Returns:\n # numeric: root of f\n if (f(a)*f(b) > 0) stop('Initial bounds must evaluate to opposite sign.')\n xL <- a; xR <- b; xM <- NA\n while (abs(xR-xL) > tol_consec || max(abs(c(f(xL),f(xR)))) > tol_approx){\n xM <- .5 * (xL + xR)\n if(f(xL)*f(xM) < 0) xR <- xM else xL <- xM # If sign changes in [xL,xM], make xM the new right bound, otherwise left\n }\n return(xM)\n}\n\ncall_black_scholes <- function(S, K, T, sigma, r, q){\n # Returns the Black-Scholes value of a vanilla call option.\n d1 <- (log(S/K) + (r - q + 0.5*sigma*sigma)*T) / (sigma*sqrt(T))\n return(S*exp(-q*T)*pnorm(d1) - K*exp(-r*T)*pnorm(d1 - sigma*sqrt(T)))\n}\n\ncalculate_implied_vol <- function(S, K, T, r, q, price, solver='newton'){\n # Returns the Black-Scholes implied volatility.\n vega <- function(sigma){\n # Vega of a vanilla option in the Black-Scholes framework.\n # This is plugged into Newton's method as the first derivative.\n d1 <- (log(S/K) + (r - q + 0.5*sigma*sigma)*T) / (sigma*sqrt(T))\n return(S*exp(-q*T)*sqrt(T)*dnorm(d1))\n }\n\n if (solver == 'newton') {\n newton(function(sigma) call_black_scholes(S, K, T, sigma, r, q) - price, vega, x0=0.25)\n } else if (solver == 'bisection'){\n bisection(function(sigma) call_black_scholes(S, K, T, sigma, r, q) - price, a=1e-4, b=1.5)\n } else {\n uniroot(function(sigma) call_black_scholes(S, K, T, sigma, r, q) - price, interval=c(1e-4,1.5))\n }\n \n}\n\ncalculate_smile <- function(S, T, r, q, strikes, prices, plot_smile=FALSE, plot_title='', solver='newton'){\n # Calculates the implied volatility for a range of strikes.\n # Can plot the implied volatility smile.\n #\n # Args:\n # S (numeric): Spot price\n # T (numeric): Maturity\n # r (numeric): Risk-neutral return rate\n # q (numeric): Continuous dividend rate\n # strikes (array-like): A range of strike prices\n # prices (array-like): Prices for range of strikes\n # plot_smile (logical): Should the function plot the implied volatility smile\n # Returns:\n # (vector): The vector of implied volatilities for the range of strike prices\n \n implied_vols <- mapply(function(K,V) calculate_implied_vol(S, K, T, r, q, V, solver=solver), strikes, prices)\n if (plot_smile) plot(strikes, implied_vols, main=plot_title, xlab='K', ylab='Implied Volatility', type='l', col='blue', las=1)\n return(implied_vols)\n}\n", "meta": {"hexsha": "ca3c4adf952dd8044363a18d55b20f493407013d", "size": 3804, "ext": "r", "lang": "R", "max_stars_repo_path": "black_scholes.r", "max_stars_repo_name": "scotthounsell/exact-simulation", "max_stars_repo_head_hexsha": "71ea16268e07e23ef99ad5586844a843bb1cf48a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-21T18:46:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T18:46:57.000Z", "max_issues_repo_path": "black_scholes.r", "max_issues_repo_name": "scotthounsell/exact-simulation", "max_issues_repo_head_hexsha": "71ea16268e07e23ef99ad5586844a843bb1cf48a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "black_scholes.r", "max_forks_repo_name": "scotthounsell/exact-simulation", "max_forks_repo_head_hexsha": "71ea16268e07e23ef99ad5586844a843bb1cf48a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.724137931, "max_line_length": 130, "alphanum_fraction": 0.6222397476, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7268010104081691}} {"text": "cat(\"Likelihood functions; \");\n# Likelihood Function;\n# The parameters may have different numbers depend on the model we are\n# going to use;\n# par5 is (p,r1,lambda1,r2,lambda2) for mixed model and par2 is (r,lambda)\n# for simple model;\n# Construct likelihood kernel\n## Generation interval kernel\n# probability transfer from i to j, the interval is +-1day;\n# shifted gamma distribution: allow for negative serial intervals\nptij <- function(ti,tj,dt,tshft,a,b){\n pgamma(ti-tj+dt+tshft,shape=a,scale=b)-pgamma(ti-tj-dt+tshft,shape=a,scale=b)\n}\n\nlogit<-function(x){\n exp(x)/(1-exp(x))\n}\n\n# serial interval pdf;\nserintpdf <- function(x,tshft,r,lambda){\n dgamma(x+tshft,shape=r,scale=lambda)\n}\nunifpdf <- function(x,u1,u2){\n dunif(x,min=u1,max=u2)\n}\n\n#serial interval cdf;\nserintcdf <- function(x,tshft,r,lambda){\n pgamma(x+tshft,shape=r,scale=lambda)\n}\n\nmaxgenint <- function(par){ # only positive roots\n f <- function(x){1-serintcdf(exp(x),par[1],par[2],par[3])-10^-3}\n return(c(-par[1],exp(uniroot(f, c(-10^8,10^8))$root)))\n}\n\n## Likelihood: product over all terms\nppij <- function(i,j,par,data){\n ifelse(i!=j,ptnegij(data[i],data[j],1,par[1],par[2],par[3]),0)\n}\n\n# Generate table with probabilities for generation interval kernel\n# Maximum admissable generation interval: 99.9 percentile of interval\n# distribution\nprobtab <- function(par){\n j <- 0\n stop <- FALSE\n prvect <- c()\n while(stop!=TRUE){\n new <- ptij(j,0,1,par[1],par[2],par[3])\n prvect[j+1] <- new\n if(sum(prvect)>(0.999999*2) | j>100 | new==0) {stop <- TRUE}\n j <- j+1\n }\n return(c(prvect,0))\n}\n\n# Generate vector of time differences (time intervals) for all possible\n# contacts: \n# replace inadmissable ones with -2 (including self, this is the outer\n# Replace). See next line for reason why not -1.\n\ndiffs <- function(i,vec,rng){\n diff_t <- vec[i]-vec\n diff_t[which(diff_trng[2])] <- -2\n diff_t[i] <- -2\n return(diff_t)\n}\n\n# Probability of j infecting i\n# two parameters\nprobvec <- function(i,par,data,maxint){\n serintpdf(diffs(i,data,maxint),par[1],par[2],par[3])\n}\nprobunif <- function(i,par,data){\n unifpdf(data[i]-data,par[1],par[2])\n}\n\n# probij <- function(i,j,par,data){\n# c(probunif(i,c(0,tswuhan),timedata)[j==1], # for Wuhan, uniform distribution\n# probvec(i,par,data,maxgenint(par))[j>1])\n# }\n\nprobij <- function(i,j,par,data){\n probvec(i,par,data,maxgenint(par))[j]\n}\n\n# j can be vector, i can only be a number.\nprobijnp <- function(i,j,par,data){\n pvec<-probij(i,(1:length(data)),par,data)\n return(pvec[j]/(1-pvec[j])*prod(1-pvec))\n}\n", "meta": {"hexsha": "9ac8a7ba48c8ae23231ef384c42cb6fe0c7318d5", "size": 2567, "ext": "r", "lang": "R", "max_stars_repo_path": "R codes/v6.likelihood.r", "max_stars_repo_name": "Holin-Chen/COVID-19-Transmission-Dynamics-GA", "max_stars_repo_head_hexsha": "5663f81a5c82c53387c7ac6db56b4ab855b7cf72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T20:59:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T20:59:35.000Z", "max_issues_repo_path": "R codes/v6.likelihood.r", "max_issues_repo_name": "Holin-Chen/COVID-19-Transmission-Dynamics-GA", "max_issues_repo_head_hexsha": "5663f81a5c82c53387c7ac6db56b4ab855b7cf72", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R codes/v6.likelihood.r", "max_forks_repo_name": "Holin-Chen/COVID-19-Transmission-Dynamics-GA", "max_forks_repo_head_hexsha": "5663f81a5c82c53387c7ac6db56b4ab855b7cf72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6021505376, "max_line_length": 80, "alphanum_fraction": 0.6758862485, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7267767604840382}} {"text": "#Series temporais e analises preditivas - Fernando Amaral\r\nlibrary(forecast)\r\nlibrary(ggplot2)\r\n\r\nplot(Seatbelts)\r\nx1 = tslm(DriversKilled ~ trend, data=Seatbelts)\r\nx2 = tslm(DriversKilled ~ season, data=Seatbelts)\r\nx3 = tslm(DriversKilled ~ trend + season, data=Seatbelts)\r\n\r\nCV(x1)\r\nCV(x2)\r\nCV(x3)\r\n\r\n#fazendo previsao\r\nr1 = forecast(x1,h=12)\r\nr2 = forecast(x2,h=12)\r\nr3 = forecast(x3,h=12)\r\n\r\nautoplot(r1)\r\nautoplot(r2)\r\nautoplot(r3)\r\n\r\nplot(r1)\r\nlines(r2$mean, col=\"red\")\r\nlines(r3$mean, col=\"green\")\r\nlegend(\"topright\",legend=c(\"Tend\",\"Seas\",\"Tend + Seas\"), col = c(\"blue\",\"red\",\"green\"), lty=1:2, cex=0.8)", "meta": {"hexsha": "ac4af0aabf19d6d0dc3d3baeac5abb6dd46c7b94", "size": 611, "ext": "r", "lang": "R", "max_stars_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/8.3.Regressao Linear.r", "max_stars_repo_name": "tarsoqueiroz/Rlang", "max_stars_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/8.3.Regressao Linear.r", "max_issues_repo_name": "tarsoqueiroz/Rlang", "max_issues_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/8.3.Regressao Linear.r", "max_forks_repo_name": "tarsoqueiroz/Rlang", "max_forks_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5, "max_line_length": 105, "alphanum_fraction": 0.6792144026, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7266552786261892}} {"text": "# https://fivethirtyeight.com/features/can-you-solve-these-colorful-puzzles/\n# You play a game with four balls: One ball is red, one is blue, \n# one is green and one is yellow. They are placed in a box. You \n# draw a ball out of the box at random and note its color. Without \n# replacing the first ball, you draw a second ball and then paint \n# it to match the color of the first. Replace both balls, and repeat \n# the process. The game ends when all four balls have become the \n# same color. What is the expected number of turns to finish the game?\n\n# Libraries\nlibrary(ggplot2)\n\n# Input\nnum_colors <- 4\nnum_balls <- 4\nnum_trials <- 25000\n\n# Code\nrpl <- num_balls > num_colors\nnum_turns <- numeric(num_trials)\n\nfor (i in 1:num_trials) {\n a <- sample(1:num_colors, num_balls, replace = rpl)\n count <- 0\n while(!isTRUE(all.equal(min(a), max(a)))) {\n b <- sample(a, 2, replace = FALSE)\n c1 <- min(which(a == b[1]))\n c2 <- min(which(a == b[2]))\n a[c(c1, c2)] <- b[1]\n count <- count + 1\n }\n num_turns[i] <- count\n}\n\n# Output\nggplot(mapping = aes(num_turns)) + \n geom_histogram(binwidth = 1) +\n theme_bw() +\n labs(title = \"Riddler 4/28\", x = \"Num. of Turns\", y = \"Count\")\nmedian(num_turns)\nmean(num_turns)\n", "meta": {"hexsha": "5abc26039f4c9e10ea98c356bea0a1d74e31298a", "size": 1227, "ext": "r", "lang": "R", "max_stars_repo_path": "colorBalls.r", "max_stars_repo_name": "sgranitz/riddler", "max_stars_repo_head_hexsha": "e77df77289f3e3710626b1eeb506a7b0cdf4ecd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colorBalls.r", "max_issues_repo_name": "sgranitz/riddler", "max_issues_repo_head_hexsha": "e77df77289f3e3710626b1eeb506a7b0cdf4ecd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colorBalls.r", "max_forks_repo_name": "sgranitz/riddler", "max_forks_repo_head_hexsha": "e77df77289f3e3710626b1eeb506a7b0cdf4ecd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2142857143, "max_line_length": 76, "alphanum_fraction": 0.6691116544, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7266307348192548}} {"text": "#!/usr/bin/env Rscript\n\n##############################################################################\n## Functions\n\ninteger_partition = function(n) {\n part_nums = c()\n for (k in 1:n) {\n part_nums = c(part_nums, A(n=n, k=k))\n }\n return(part_nums)\n}\n\nA = function(n, k) {\n if ((k == 1) || (n == k)) {\n return(1)\n }\n if ((k > n) || (k < 1)) {\n return(0)\n }\n return(A(n=(n-1), k=(k-1)) + A(n=(n-k), k=k))\n}\n\nexpand_integer_vector = function(v) {\n expanded = c()\n for (i in 1:length(v)) {\n expanded = c(expanded, rep(i, v[i]))\n }\n return(expanded)\n}\n\nget_psi_prior = function(n) {\n integer_parts = integer_partition(n=n)\n return(1/(n * integer_parts))\n}\n\nparse_file_ext = function(path) {\n return(tail(strsplit(path, '\\\\.')[[1]], n=1))\n}\n\nplot_div_model_prior = function(n, output_path=\"partition_numbers.pdf\") {\n prior_probs = get_psi_prior(n=n)\n names(prior_probs) = c(1:n)\n partition_numbers = expand_integer_vector(integer_partition(n=n))\n plot_letters = LETTERS[1:2]\n format = 'pdf'\n ext = parse_file_ext(output_path)\n if ((tolower(ext) == 'eps') || (tolower(ext) == 'ps')) {\n format = 'eps'\n }\n\n if (format == 'eps') {\n postscript(output_path, onefile = F, paper=\"special\", horizontal=F, width=7.087, height=3)\n } else {\n pdf(output_path, width=7.087, height=3)\n }\n par(yaxs = \"i\", xaxs = \"i\")\n par(cex.axis=0.7)\n par(mgp = c(1.4,0.4,0)) # mgp adjusts space of axis labels\n # oma is space around all plots\n par(oma = c(0,0,0.3,0.2), mar = c(2.65,2.45,0.5,0.1))\n par(mfrow = c(1, 2))\n hist(partition_numbers,\n breaks= c(1:(n+1)),\n \t\tright=FALSE,\n \t\txlab=\"\",\n \t\tylab=bquote(\"# of divergence models\"),\n main=\"\",\n \t\t# xlim=c(0,22),\n \t\t# ylim=c(0,140),\n \t\txaxt=\"n\",\n \t\tcol=\"gray50\", border=\"gray50\")\n box()\n axis(1, at=seq(1.5, (n+.5), 1), labels=c(1:n), tick=F)\n axis(1, at=c(1:(n+1)), labels=F)\n #mtext(\"Number of divergence models\", WEST<-2, padj=0, cex=1, outer = T)\n mtext(plot_letters[[1]], side=3, adj=0, line=0, cex=0.75, font=2)\n \n par(mgp = c(1,0.4,0)) # mgp adjusts space of axis labels\n barplot(prior_probs, \n border=\"gray50\",\n space=0,\n # axis.lty=1,\n \t xaxt = \"n\",\n col=\"gray50\",\n \t\txlab=\"\",\n ylab=bquote(italic(p)(italic(M)[group(\"|\", bold(tau), \"|\")*\",\"*italic(i)])),\n ylim=c(0, max(prior_probs))\n )\n box()\n axis(1, at=seq(0.5, (n-.5), 1), labels=c(1:n), tick=F)\n axis(1, at=c(0:n), labels=F)\n mtext(plot_letters[[2]], side=3, adj=0, line=0, cex=0.75, font=2)\n\tmtext(bquote(\"# of divergence events, \" * group(\"|\", bold(tau), \"|\")), SOUTH<-1, padj=-0.7, cex=1.1, outer = T)\n dev.off()\n}\n\n##############################################################################\n## Main CLI\n\n## Option parsing\nsuppressPackageStartupMessages(library(\"optparse\"))\noption_list <- list(\n make_option(c(\"-n\", \"--num-elements\"), type=\"integer\", dest=\"n\", default=22,\n help=\"Number of elements (default: 22)\"),\n make_option(c(\"-o\", \"--output-path\"), type=\"character\",\n dest=\"output_path\", default=\"partition_numbers.pdf\",\n help=paste(\"Output path for plot file (default: \",\n \"'./partition_numbers.pdf'). If you want an EPS-\",\n \"formatted plot file, simply specify a path with \",\n \"an '.eps' or '.ps' extension. Otherwise, the \",\n \"plot file will be a PDF.\"))\n)\noptions <- parse_args(OptionParser(option_list=option_list))\n\nplot_div_model_prior(n = options$n,\n output_path = options$output_path)\n\n", "meta": {"hexsha": "fac3038d783174b2cde673c095b18674977c7a1d", "size": 3791, "ext": "r", "lang": "R", "max_stars_repo_path": "slides/bin/integer_partition_plot.r", "max_stars_repo_name": "joaks1/msbayes-experiments", "max_stars_repo_head_hexsha": "72fcf3c26f6d92bdcc39343372552f45d72d8f7f", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slides/bin/integer_partition_plot.r", "max_issues_repo_name": "joaks1/msbayes-experiments", "max_issues_repo_head_hexsha": "72fcf3c26f6d92bdcc39343372552f45d72d8f7f", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/bin/integer_partition_plot.r", "max_forks_repo_name": "joaks1/msbayes-experiments", "max_forks_repo_head_hexsha": "72fcf3c26f6d92bdcc39343372552f45d72d8f7f", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8571428571, "max_line_length": 112, "alphanum_fraction": 0.5183328937, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7266265142541543}} {"text": "\n# 调用R包\nlibrary(\"FactoMineR\");\nlibrary(\"factoextra\");\n\ndata(decathlon2)\nhead(decathlon2)\n\ndecathlon2.active <- decathlon2[1:23, 1:10]\nhead(decathlon2.active[, 1:6], 4)\n\n# 获得数据\nlibrary(\"FactoMineR\")\nlibrary(\"factoextra\")\ndata(decathlon2)\ndecathlon2.active <- decathlon2[1:23, 1:10]\n\n# PCA计算\nres.pca <- PCA(decathlon2.active, graph = FALSE)\n# 提取变量的分析结果\nvar <- get_pca_var(res.pca)\nvar\n\n# Coordinates of variables\nhead(var$coord, 4)\n# col.var设定线条颜色\nfviz_pca_var(res.pca, col.var = \"black\")\n\nhead(var$cos2)\nlibrary(\"corrplot\")\n# is.corr表示输入的矩阵不是相关系数矩阵\ncorrplot(var$cos2, is.corr=FALSE)\n\n# Total cos2 of variables on Dim.1 and Dim.2\n# 在第一第二主成分是显示结果(通过值的叠加显示)\nfviz_cos2(res.pca, choice = \"var\", axes = 1:2)\n\n# Color by cos2 values: quality on the factor map\nfviz_pca_var(res.pca, col.var = \"cos2\",\n gradient.cols = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"), \n repel = TRUE # Avoid text overlapping\n )\n\n# Change the transparency by cos2 values\nfviz_pca_var(res.pca, alpha.var = \"cos2\")\n\nhead(var$contrib, 4)\nlibrary(\"corrplot\")\ncorrplot(var$contrib, is.corr=FALSE) \n\n# Contributions of variables to PC1\n# 各变量对第一主成分的贡献\nfviz_contrib(res.pca, choice = \"var\", axes = 1, top = 10)\n# Contributions of variables to PC2\n# 各变量对第二主成分的贡献\nfviz_contrib(res.pca, choice = \"var\", axes = 2, top = 10)\n\nfviz_contrib(res.pca, choice = \"var\", axes = 1:2, top = 10)\n\nfviz_pca_var(res.pca, col.var = \"contrib\",\n gradient.cols = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\")\n )\n\n# Change the transparency by contrib values\nfviz_pca_var(res.pca, alpha.var = \"contrib\")\n\n# Create a random continuous variable of length 10\n# 生成随机数\nset.seed(123)\nmy.cont.var <- rnorm(10)\n# Color variables by the continuous variable\n# col.var设置颜色\n# gradient.cols设置颜色渐变范围\nfviz_pca_var(res.pca, col.var = my.cont.var,\n gradient.cols = c(\"blue\", \"yellow\", \"red\"),\n legend.title = \"Cont.Var\")\n\n# Create a grouping variable using kmeans\n# Create 3 groups of variables (centers = 3)\nset.seed(123)\n# 进行聚类\n# center聚类数量\nres.km <- kmeans(var$coord, centers = 3, nstart = 25)\n# 将向量编码为因子\ngrp <- as.factor(res.km$cluster)\n# Color variables by groups\nfviz_pca_var(res.pca, col.var = grp, \n palette = c(\"#0073C2FF\", \"#EFC000FF\", \"#868686FF\"),\n legend.title = \"Cluster\")\n\n#proba用于表征维度的显着性阈值,\nres.desc <- dimdesc(res.pca, axes = c(1,2), proba = 0.05)\n# Description of dimension 1 第一主成分\nres.desc$Dim.1\n\n# 第二主成分\nres.desc$Dim.2\n\nind <- get_pca_ind(res.pca)\nind\n\nfviz_pca_ind(res.pca)\n\n# Quality of individuals\nhead(ind$cos2)\n# repel=TRUE能够避免部分重合的点重叠\nfviz_pca_ind(res.pca, col.ind = \"cos2\", \n gradient.cols = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"),\n repel = TRUE # Avoid text overlapping (slow if many points)\n )\n\nfviz_pca_ind(res.pca, col.ind = \"cos2\", pointsize = \"cos2\",\n gradient.cols = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"),\n repel = TRUE # Avoid text overlapping (slow if many points)\n )\n\nfviz_cos2(res.pca, choice = \"ind\")\n\n# Total contribution on PC1 and PC2\nfviz_contrib(res.pca, choice = \"ind\", axes = 1:2)\n\nhead(iris, 3)\n\n# The variable Species (index = 5) is removed before PCA analysis\n# 第5列不进行PCA运算\niris.pca <- PCA(iris[,-5], graph = FALSE)\n\nfviz_pca_ind(iris.pca,\n # show points only (nbut not \"text\") 只显示点而不显示文本,默认都显示\n geom.ind = \"point\", \n # 设定分类种类\n col.ind = iris$Species,\n # 设定颜色\n palette = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"),\n # 添加椭圆 Concentration ellipses\n addEllipses = TRUE,\n legend.title = \"Groups\",\n )\n\nfviz_pca_ind(iris.pca,\n label = \"none\", # hide individual labels\n habillage = iris$Species, # color by groups\n addEllipses = TRUE, # Concentration ellipses\n palette = \"jco\"\n )\n\n# Variables on dimensions 2 and 3\nfviz_pca_var(res.pca, axes = c(2, 3))\n# Individuals on dimensions 2 and 3\nfviz_pca_ind(res.pca, axes = c(2, 3))\n\n# Show variable points and text labels\nfviz_pca_var(res.pca, geom.var = c(\"point\", \"text\"))\n\n# Show individuals text labels only\nfviz_pca_ind(res.pca, geom.ind = \"text\")\n\n# Change the size of arrows an labels\nfviz_pca_var(res.pca, arrowsize = 1, labelsize = 5, \n repel = TRUE)\n# Change points size, shape and fill color\n# Change labelsize\nfviz_pca_ind(res.pca, \n pointsize = 3, pointshape = 21, fill = \"lightblue\",\n labelsize = 5, repel = TRUE)\n\n# Add confidence ellipses\nfviz_pca_ind(iris.pca, geom.ind = \"point\", \n # 使用iris数据集\n col.ind = iris$Species, # color by groups\n palette = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"),\n addEllipses = TRUE, ellipse.type = \"confidence\",\n legend.title = \"Groups\"\n )\n# Convex hull\nfviz_pca_ind(iris.pca, geom.ind = \"point\",\n col.ind = iris$Species, # color by groups\n palette = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"),\n # 用凸包多边形代替椭圆\n addEllipses = TRUE, ellipse.type = \"convex\",\n legend.title = \"Groups\"\n )\n\n\nfviz_pca_var(res.pca, axes.linetype = \"dotted\")\n\nind.p <- fviz_pca_ind(iris.pca, geom = \"point\", col.ind = iris$Species)\nggpubr::ggpar(ind.p,\n title = \"Principal Component Analysis\",\n # 下标题\n subtitle = \"Iris data set\",\n # 说明\n caption = \"Source: factoextra\",\n # x,y轴标题\n xlab = \"PC1\", ylab = \"PC2\",\n # 标题名字位置\n legend.title = \"Species\", legend.position = \"top\",\n # 主题和配设\n ggtheme = theme_gray(), palette = \"jco\"\n )\n\nfviz_pca_biplot(res.pca, repel = TRUE,\n col.var = \"#2E9FDF\", # Variables color\n col.ind = \"#696969\" # Individuals color\n )\n\nfviz_pca_biplot(iris.pca, \n # 观测量颜色\n col.ind = iris$Species, palette = \"jco\", \n # 添加椭圆\n addEllipses = TRUE, label = \"var\",\n # 线条颜色\n col.var = \"black\", repel = TRUE,\n legend.title = \"Species\") \n\nfviz_pca_biplot(iris.pca, \n # Fill individuals by groups\n geom.ind = \"point\",\n # 点的形状\n pointshape = 21,\n # 点的大小\n pointsize = 2.5,\n # 按照组类特定形状\n fill.ind = iris$Species,\n col.ind = \"black\",\n # Color variable by groups\n # 颜色\n col.var = factor(c(\"sepal\", \"sepal\", \"petal\", \"petal\")),\n # 标题\n legend.title = list(fill = \"Species\", color = \"Clusters\"),\n repel = TRUE # Avoid label overplotting\n )+\n ggpubr::fill_palette(\"jco\")+ # Indiviual fill color\n ggpubr::color_palette(\"npg\") # Variable colors\n\nfviz_pca_biplot(iris.pca, \n # Individuals\n geom.ind = \"point\",\n fill.ind = iris$Species, col.ind = \"black\",\n pointshape = 21, pointsize = 2,\n palette = \"jco\",\n addEllipses = TRUE,\n # Variables\n alpha.var =\"contrib\", col.var = \"contrib\",\n gradient.cols = \"RdYlBu\",\n \n legend.title = list(fill = \"Species\", color = \"Contrib\",\n alpha = \"Contrib\")\n )\n\n# Visualize variable with cos2 >= 0.6\n# 可视化cos2>0.6\nfviz_pca_var(res.pca, select.var = list(cos2 = 0.6))\n\n# Select by names\n# 根据名字显示\nname <- list(name = c(\"Long.jump\", \"High.jump\", \"X100m\"))\nfviz_pca_var(res.pca, select.var = name)\n\n# 根据前五贡献\n# top 5 contributing individuals and variable\nfviz_pca_biplot(res.pca, select.ind = list(contrib = 5), \n select.var = list(contrib = 5),\n ggtheme = theme_minimal())\n", "meta": {"hexsha": "befa571acd100a63641b1c209b10995c68131f71", "size": 7919, "ext": "r", "lang": "R", "max_stars_repo_path": "PCA/Principal Component Methods in R.r", "max_stars_repo_name": "luohenyueji/R-Study-Notes", "max_stars_repo_head_hexsha": "e6021d86a15f46a981c09c5e2c1b6766c6470462", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-19T09:43:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T08:58:33.000Z", "max_issues_repo_path": "PCA/Principal Component Methods in R.r", "max_issues_repo_name": "qiuli-github/R-Study-Notes", "max_issues_repo_head_hexsha": "eb2fb7d06eabe45622f378ca2d07fd50ac2e21fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PCA/Principal Component Methods in R.r", "max_forks_repo_name": "qiuli-github/R-Study-Notes", "max_forks_repo_head_hexsha": "eb2fb7d06eabe45622f378ca2d07fd50ac2e21fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-06-03T07:02:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T06:07:55.000Z", "avg_line_length": 29.8830188679, "max_line_length": 74, "alphanum_fraction": 0.5717893673, "num_tokens": 2481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7265916130447991}} {"text": "# Derive statistics from confusion matrix\r\n# [ref] https://en.wikipedia.org/wiki/Confusion_matrix\r\ngenerateCM <- function(pred, ref){\r\n return(table(pred, ref))\r\n}\r\n\r\ncmToMetrics <- function(cm, positive=1){\r\n # Decode the matrix\r\n if(positive==0){\r\n TP <- cm[1,1]/sum(cm)\r\n TN <- cm[2,2]/sum(cm)\r\n FP <- cm[1,2]/sum(cm)\r\n FN <- cm[2,1]/sum(cm)\r\n } else {\r\n TP <- cm[2,2]/sum(cm)\r\n TN <- cm[1,1]/sum(cm)\r\n FP <- cm[2,1]/sum(cm)\r\n FN <- cm[1,2]/sum(cm)\r\n }\r\n # Derive Metrics\r\n sensitivity <- TP/(TP+FN)\r\n specificity <- TN/(FP+TN)\r\n prevalence <- TP+FN/(FN+TP+FP+TN)\r\n ppv <- TP/(TP+FP)\r\n npv <- TN/(TN+FN)\r\n fpr <- FP/(FP+TN)\r\n fnr <- FN/(FN+TP)\r\n fdr <- FP/(FP+TP)\r\n FOR <- FN/(TN+FN)\r\n accuracy <- (TP+TN)/(FN+TP+FP+TN)\r\n F1 <- 2*TP/(2*TP+FP+FN)\r\n MCC <- (TP*TN-FP*FN)/sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN))\r\n informedness <- sensitivity + specificity - 1\r\n markedness <- ppv + npv -1\r\n # Output\r\n output <- c(\"Accuracy\"=accuracy,\r\n \"True.Positive\"=TP,\r\n \"False.Negative\"=FN,\r\n \"False.Positive\"=FP,\r\n \"True.Negative\"=TN,\r\n \"Sensitivity\"=sensitivity, \r\n \"Specificity\"=specificity,\r\n \"Prevalence\"=prevalence, \r\n \"Positive.Predictive.Value\"=ppv,\r\n \"Negative.Predictive.Value\"=npv,\r\n \"False.Positive.Rate\"=fpr,\r\n \"False.Discovery.Rate\"=fdr,\r\n \"False.Negative.Rate\"=fnr,\r\n \"False.Omission.Rate\"=FOR,\r\n \"F1.Score\"=F1,\r\n \"Matthews.correlation.coefficient\"=MCC,\r\n \"Informedness\"=informedness,\r\n \"Markedness\"=markedness)\r\n return(output)\r\n}", "meta": {"hexsha": "73794398d3a40e13de783beef9327663190dbd4b", "size": 1701, "ext": "r", "lang": "R", "max_stars_repo_path": "utils/confusionMatrixToMetrics.r", "max_stars_repo_name": "tingsyo/qpetw", "max_stars_repo_head_hexsha": "e0f87a401649b367506370beeffaeffcc9484407", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/confusionMatrixToMetrics.r", "max_issues_repo_name": "tingsyo/qpetw", "max_issues_repo_head_hexsha": "e0f87a401649b367506370beeffaeffcc9484407", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/confusionMatrixToMetrics.r", "max_forks_repo_name": "tingsyo/qpetw", "max_forks_repo_head_hexsha": "e0f87a401649b367506370beeffaeffcc9484407", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9272727273, "max_line_length": 61, "alphanum_fraction": 0.5220458554, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098192, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7264109719363365}} {"text": "# Multinomial logistic regression simulation code\n# For K levels of the dependent variable, estimates K-1 sets of \n# coefficients for the independent variables.\n\n# Currently set up for 3 classes but can be extended to any number\n\n# Raymond Viviano\n# rayviviano@gmail.com\n# March 23, 2020\n\n# TODO: Encapsulate certain code sections into smaller functions\n# TODO: Bound coverage probability between 0 & 1\n\n# Easy access to mlogit models\nsuppressPackageStartupMessages(library(mlogit))\n\n# Set error reporting options\noptions(show.error.locations=TRUE)\noptions(error=recover)\n\n\n#' Coverage Probability, i.e., the probability that the confidence interval (ci)\n#' for a parameter will contain the true value\n#' Inputs:\n#' b - Estimate\n#' se - Standard Error of the Estimate\n#' true - True value of parameter for data-generating process\n#' cl - Confidence level\n#' dof - Degrees of Freedom\n#' Output:\n#' List containing coverage probability, vect\ncoverage.prob <- function(b, se, true, cl=.95, dof=Inf){\n # Compute quantile based on confidence level\n coverage.quantile <- cl + (1-cl)/2\n\n # Compute confidence interval upper and lower bounds\n ci.lower <- b - qt(coverage.quantile, df=dof)*se\n ci.upper <- b + qt(coverage.quantile, df=dof)*se\n\n # For each ci generated for each b/se pair, eval if true param is in ci\n ci.contain.true <- ifelse(true>=ci.lower & true<=ci.upper, 1, 0)\n\n # Calculate coverage probability\n cp <- mean(ci.contain.true)\n\n # Calculate Monte Carlo Error\n mc.err.lower <- cp - 1.96*sqrt((cp*(1-cp))/length(b))\n mc.err.upper <- cp + 1.96*sqrt((cp*(1-cp))/length(b))\n\n # Return coverage probability and error\n return(list(cp=cp, ci=cbind(mc.err.lower, mc.err.upper)))\n}\n\n\n#' Power to detect any effect at various alpha levels\n#' Takes a vector of p-values and calculates the proportion of modell where the \n#' p-val for the effect of interest was < .5, .01, and .001.\npower.detect.effect <- function(p.val.vec){\n less.than.05 <- ifelse(p.val.vec < .05, 1, 0)\n prop.05 <- sum(less.than.05)/length(less.than.05)\n\n less.than.01 <- ifelse(p.val.vec < .01, 1, 0)\n prop.01 <- sum(less.than.01)/length(less.than.01)\n\n less.than.001 <- ifelse(p.val.vec < .001, 1, 0)\n prop.001 <- sum(less.than.001)/length(less.than.001)\n\n cat(paste0('Power to detect effect at .05: ', prop.05, '\\n'))\n cat(paste0('Power to detect effect at .01: ', prop.01, '\\n'))\n cat(paste0('Power to detect effect at .001: ', prop.001, '\\n'))\n}\n\n\n# Ensure reproducible results\nset.seed(10000)\n\n# Set logistic regression parameters (Can be calculated as log(oddsRatio)) for\n# Classes A and B (against reference C).\n\n# Class a\nb0a <- .2 # Set Logistic Regression Intercept True Value\nb1a <- .5 # Set Logistic Regression Slope True Value \n\n# Class b\nb0b <- -.2\nb1b <- .75\n\n# Define sample size\nn <- 16000\n\n# Define number of simulations\nnsims <- 55\n\n# Define matrix to hold simulation data (estimates, std.errors, and pvals)\nsim.prms <- matrix(NA, nrow=nsims, ncol=12)\n\n# Loop through simulations\nfor(i in 1:nsims){\n # Participant/subject/case/index\n case = c(1:n)\n\n # Generate independant variable data, uniform random between -1 and 1\n x <- runif(n, -1, 1)\n\n # Compute probabilities of each class based on generated data\n prob.a <- exp(b0a +b1a*x) / (1 + exp(b0a + b1a*x) + exp(b0b + b1b*x))\n prob.b <- exp(b0b +b1b*x) / (1 + exp(b0a + b1a*x) + exp(b0b + b1b*x))\n prob.c <- 1 - prob.a - prob.b\n\n # Generate y data based on calculated probabilities\n y <- rep(NA, n)\n for (j in 1:n){\n y[j] <- sample(c(\"a\", \"b\", \"c\"), 1, replace = TRUE, \n prob = c(prob.a[j], prob.b[j], prob.c[j]))\n }\n\n # Prep data for mlogit package\n sim.data <- data.frame(case, x, y, stringsAsFactors=FALSE)\n\n # Convert data to long format for mlogit\n sim.data <- mlogit.data(sim.data, shape='wide', choice=\"y\", id.var='case')\n\n # Estimate logit model\n model <- mlogit(y ~ -1|x, data=sim.data, reflevel='c') \n\n # Get variance-covariance matrix\n var.covar <- vcov(model)\n\n # Put model paramters in simulation matrix\n sim.prms[i,1] <- model$coef[1] # Estimate for b0a\n sim.prms[i,2] <- model$coef[3] # Estimate for b1a\n sim.prms[i,3] <- model$coef[2] # Estimate for b0b\n sim.prms[i,4] <- model$coef[4] # Estimate for b1b\n sim.prms[i,5] <- sqrt(diag(var.covar)[1]) # b0a standard error\n sim.prms[i,6] <- sqrt(diag(var.covar)[3]) # b1a standard error\n sim.prms[i,7] <- sqrt(diag(var.covar)[2]) # b0b standard error\n sim.prms[i,8] <- sqrt(diag(var.covar)[4]) # b1b standard error\n sim.prms[i,9] <- summary(model)$CoefTable[,4][1] # b0a pvalue\n sim.prms[i,10] <- summary(model)$CoefTable[,4][3] # b1a pvalue\n sim.prms[i,11] <- summary(model)$CoefTable[,4][2] # b0b pvalue\n sim.prms[i,12] <- summary(model)$CoefTable[,4][4] # b1b pvalue\n}\n\n# Get Covarage probabilities for the parameters\nb0a.coverage <- coverage.prob(sim.prms[,1], sim.prms[,5], b0a, .95, n-length(coef(model)))\nb1a.coverage <- coverage.prob(sim.prms[,2], sim.prms[,6], b1a, .95, n-length(coef(model)))\nb0b.coverage <- coverage.prob(sim.prms[,3], sim.prms[,7], b0b, .95, n-length(coef(model)))\nb1b.coverage <- coverage.prob(sim.prms[,4], sim.prms[,8], b1b, .95, n-length(coef(model)))\n\n# Print intercept for class a coverage probability and 95% confidence interval\nprint(\"Coverage Probability for b0a\")\nprint(b0a.coverage)\n\n# Print coefficent on x for class a coverage probability and 95% confidence interval\nprint(\"Coverage Probability for b1a\")\nprint(b1a.coverage)\n\n# Print intercept for class b coverage probability and 95% confidence interval\nprint(\"Coverage Probability for b0b\")\nprint(b0b.coverage)\n\n# Print coefficent on x for class b coverage probability and 95% confidence interval\nprint(\"Coverage Probability for b1b\")\nprint(b1b.coverage)\n\ncat(\"Power to detect b0a\\n\")\npower.detect.effect(sim.prms[,9])\n\ncat(\"\\nPower to detect b1a\\n\")\npower.detect.effect(sim.prms[,10])\n\ncat(\"Power to detect b0b\\n\")\npower.detect.effect(sim.prms[,11])\n\ncat(\"\\nPower to detect b1b\\n\")\npower.detect.effect(sim.prms[,12])", "meta": {"hexsha": "8d7630bb57192aeef22dcf44324688d7e042db56", "size": 6255, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/multinomial-logit-simulations.r", "max_stars_repo_name": "rviviano/data-tools", "max_stars_repo_head_hexsha": "97ab15584d01ac81ffe4349e337ed2d76a042ece", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/multinomial-logit-simulations.r", "max_issues_repo_name": "rviviano/data-tools", "max_issues_repo_head_hexsha": "97ab15584d01ac81ffe4349e337ed2d76a042ece", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/multinomial-logit-simulations.r", "max_forks_repo_name": "rviviano/data-tools", "max_forks_repo_head_hexsha": "97ab15584d01ac81ffe4349e337ed2d76a042ece", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5397727273, "max_line_length": 90, "alphanum_fraction": 0.6604316547, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.726410969035609}} {"text": "set.seed(1)\n\n\n# case 1: t-oracles; case 2: normal oracles.\ncase = 1\n# energy function for the Gaussian mixture distribution\nif (case == 1) {\n mean1 = -4\n mean2 = 3\n f = function(x) return(-log(0.4 * dnorm(x, mean=mean1, sd=0.7) + 0.6 * dnorm(x, mean=mean2, sd=0.5)))\n noisy_f = function(x) return(f(x) + rt(1, df=5))\n} else {\n mean1 = -3\n mean2 = 2\n f = function(x) return(-log(0.4 * dnorm(x, mean=mean1, sd=0.7) + 0.6 * dnorm(x, mean=mean2, sd=0.5)))\n noisy_f = function(x) return(f(x) + rnorm(1, 0, 2))\n}\n# target Gaussian mixture distribution\ndensity = function(x) exp(-f(x))\n\n\n# Important hyperparameters\nlr = 0.03\nT_high = 10\nT_low = 1\n\n# Other hyperparameters\nx_low = 0\nx_high = 0\npart1 = 100\ngrad_std = 0.1\nthinning = 100\n\n# You can set a larger value to obtain more stable results.\ntotal = 100000\n\n################################################### SGLD ###################################################\nsamples_sgld = c()\nx_low = 0\nfor (i in 1:part1) {\n samples_part = c()\n for (j in 1:(total/part1)) {\n x_low = x_low - lr * (numDeriv::grad(f, x_low) + rnorm(1, 0, grad_std)) + sqrt(2 * lr * T_low) * rnorm(1, 0, 1)\n \n if (j %% (thinning) == 0) {samples_part = c(samples_part, x_low)}\n }\n print(i)\n samples_sgld = c(samples_sgld, samples_part)\n}\n\n\n\n################################################### Naive reSGLD ###################################################\nsamples_naive = c()\nx_low = 0\nx_high = 0\nfor (i in 1:part1) {\n samples_part = c()\n for (j in 1:(total/part1)) {\n x_low = x_low - lr * (numDeriv::grad(f, x_low) + rnorm(1, 0, grad_std)) + sqrt(2 * lr * T_low) * rnorm(1, 0, 1)\n x_high = x_high - lr * (numDeriv::grad(f, x_high) + rnorm(1, 0, grad_std)) + sqrt(2 * lr * T_high) * rnorm(1, 0, 1)\n \n integrand_corrected = min(1, exp((1 / T_high - 1 / T_low) * (noisy_f(x_high) - noisy_f(x_low))))\n \n if (runif(1) < integrand_corrected) {\n tmp = x_low\n x_low = x_high\n x_high = tmp\n }\n if (j %% thinning == 0) {samples_part = c(samples_part, x_low)}\n }\n print(i)\n samples_naive = c(samples_naive, samples_part)\n}\n\n\n################################################### reSGLD ###################################################\nsamples_ptsgld = c()\nhat_var = 10\ncounter = 1\nx_low = 0\nx_high = 0\nfor (i in 1:part1) {\n samples_part = c()\n for (j in 1:(total/part1)) {\n x_low = x_low - lr * (numDeriv::grad(f, x_low) + rnorm(1, 0, grad_std)) + sqrt(2 * lr * T_low) * rnorm(1, 0, 1)\n x_high = x_high - lr * (numDeriv::grad(f, x_high) + rnorm(1, 0, grad_std)) + sqrt(2 * lr * T_high) * rnorm(1, 0, 1)\n \n if (j %% 20 == 0) {\n loss_stat = c()\n for (jjj in 1:10) {\n loss_stat = c(loss_stat, noisy_f(x_low))\n }\n unbiased_var = var(loss_stat)\n hat_var = (1 - 1 / counter) * hat_var + (1 / counter) * unbiased_var\n counter = counter + 1\n }\n \n integrand_corrected = min(1, exp((1 / T_high - 1 / T_low) * (noisy_f(x_high) - noisy_f(x_low) - (1 / T_high - 1 / T_low) * hat_var)))\n \n if (runif(1) < integrand_corrected) {\n tmp = x_low\n x_low = x_high\n x_high = tmp\n }\n if (j %% thinning == 0) {samples_part = c(samples_part, x_low)}\n }\n print(i)\n samples_ptsgld = c(samples_ptsgld, samples_part)\n}\n\n\nreal_samples = c(rnorm(length(samples_ptsgld)*0.4, mean=mean1, sd=0.7), rnorm(length(samples_ptsgld)*0.6, mean=mean2, sd=0.5))\n\nwdata = data.frame(\n Type = factor(rep(c(\"Ground truth\", \"SGLD\", \"Naive reSGLD\", \"reSGLD\"), each=length(samples_ptsgld))),\n weight = c(real_samples, samples_sgld, samples_naive, samples_ptsgld)\n )\n\nlibrary(ggplot2)\n\np=ggplot(wdata, aes(x = weight)) +\n stat_density(aes(x=weight, colour=Type, linetype=Type), size=2, geom=\"line\", position=\"identity\") +\n scale_linetype_manual(values=c(\"solid\", \"dotdash\", \"longdash\", \"twodash\"))+\n scale_color_manual(values = c(\"#666666\", \"#7570B3\", \"#E7298A\", \"#1B9E77\")) +\n scale_x_continuous(name=\"X\") +\n scale_y_continuous(name=\"Density\") +\n theme(\n legend.position = c(0.3, 0.8), \n legend.title =element_blank(), \n legend.text = element_text(colour=\"grey15\", size=24),\n legend.key.size = unit(2,\"line\"),\n legend.key = element_blank(),\n legend.background=element_rect(fill=alpha('grey', 0.1)),\n axis.title=element_text(size=24),\n axis.text.y = element_text(size=24),\n axis.text.x = element_text(size=24)\n )\np\n\n\n\n\n\n\n\n", "meta": {"hexsha": "94d8a9f5a736efc37e5f498818bba3127656faee", "size": 4672, "ext": "r", "lang": "R", "max_stars_repo_path": "simulation/reSGLD_Gaussian_mixture.r", "max_stars_repo_name": "gaoliyao/Replica_Exchange_Stochastic_Gradient_MCMC", "max_stars_repo_head_hexsha": "609f803ca334b21820dc020c16ad8113363a03e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-06-30T01:14:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:03:17.000Z", "max_issues_repo_path": "simulation/reSGLD_Gaussian_mixture.r", "max_issues_repo_name": "gaoliyao/Replica_Exchange_Stochastic_Gradient_MCMC", "max_issues_repo_head_hexsha": "609f803ca334b21820dc020c16ad8113363a03e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation/reSGLD_Gaussian_mixture.r", "max_forks_repo_name": "gaoliyao/Replica_Exchange_Stochastic_Gradient_MCMC", "max_forks_repo_head_hexsha": "609f803ca334b21820dc020c16ad8113363a03e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-02T22:06:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T23:35:21.000Z", "avg_line_length": 31.7823129252, "max_line_length": 141, "alphanum_fraction": 0.537885274, "num_tokens": 1509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7262464683631967}} {"text": "# Fiecare student primește un i unic\ni <- 1\n\n# Exercițiul 1\n# Folosim repartiția hipergeometrică\np1 <- dhyper(x=1, m=2, n=i, k=2)\np2 <- dhyper(x=2, m=2, n=i, k=2)\n\nprint(\"P(X = 2):\")\nprint(p1 / (p1 + p2))\n\n# Exercițiul 2\n# Folosim repartiția binomială\nprint(\"P(X = i):\")\nprint(dbinom(i, size=100, prob=1/6))\n\n# Exercițiul 3\n# Folosim repartiția normală\nright <- 1\n\nprint(\"P(X < 1):\")\nprint(pnorm(right, mean=3, sd=sqrt(54)))\n\n# Statistică\nX <- c(1, 2, 3, i + 3)\nn <- 4\n\n# Exercițiul 4\nX_bar <- mean(X)\nsigma <- sqrt(3)\n\nalpha <- 0.01\n\ndx <- (sigma*qnorm(1 - alpha/2))/sqrt(n)\n\nc(X_bar - dx, X_bar + dx)\n\n# Exercițiul 5\ns = var(X)\n\naux <- (n - 1) * s\n\nleft <- aux/qchisq(alpha/2, df=n-1)\nright <- aux/qchisq(1-alpha/2, df=n-1)\n\n# Exercițiul 6\nC <- cbind(1, X, X^2)\ny <- c(1, 2, 3, 4)\n\n# beta = (C^T * C)^(-1) * C^T * y\nbeta <- solve(t(C)%*%C, t(C)%*%y)\n\nprint(t(beta)) # Afișare pe linie\n\n# Verificare cu lm\nX_sq <- X^2\n\nmodel <- lm(y ~ X + X_sq)\nprint(model$coefficients)\n\n", "meta": {"hexsha": "1b38bd481a1b4083b15e379cf560f9a7dd8829e8", "size": 973, "ext": "r", "lang": "R", "max_stars_repo_path": "ps/examen_ps.r", "max_stars_repo_name": "FloaterTS/teme-fmi", "max_stars_repo_head_hexsha": "624296d3b3341f1c18fb26768e361ce2e1faa68c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2020-03-17T10:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:40:30.000Z", "max_issues_repo_path": "ps/examen_ps.r", "max_issues_repo_name": "florinalexandrunecula/teme-fmi", "max_issues_repo_head_hexsha": "b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ps/examen_ps.r", "max_forks_repo_name": "florinalexandrunecula/teme-fmi", "max_forks_repo_head_hexsha": "b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2020-01-22T11:39:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T00:19:06.000Z", "avg_line_length": 15.9508196721, "max_line_length": 40, "alphanum_fraction": 0.5868448099, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.726147752623327}} {"text": "alpha=0.05\r\nq.alpha=qtukey(1-alpha,3,15)\r\nn=10\r\nsw2=10.28 # calculated in 14.10\r\nW=q.alpha*(sqrt(sw2/n))\r\nW\r\nsample_means=c(25.1,23.5,37.8)\r\n# by ordering sample mean from lowest to highest , we rank display panels by 2 1 3 \r\n# if diffrence between means > W then we declare them to be significantly different from each other", "meta": {"hexsha": "8101fe0a4fe034955cfb9e7067d7ec1827338d56", "size": 325, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH14/EX14.12/Ex14_12.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH14/EX14.12/Ex14_12.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH14/EX14.12/Ex14_12.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 36.1111111111, "max_line_length": 99, "alphanum_fraction": 0.7261538462, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7259479113576555}} {"text": "#===============================================================\n# Find k-Almost-primes\n# R implementation\n#===============================================================\n#---------------------------------------------------------------\n# Function for prime factorization from Rosetta Code\n#---------------------------------------------------------------\n\nfindfactors <- function(n) {\n d <- c()\n div <- 2; nxt <- 3; rest <- n\n while( rest != 1 ) {\n while( rest%%div == 0 ) {\n d <- c(d, div)\n rest <- floor(rest / div)\n }\n div <- nxt\n nxt <- nxt + 2\n }\n d\n}\n\n#---------------------------------------------------------------\n# Find k-Almost-primes\n#---------------------------------------------------------------\n\nalmost_primes <- function(n = 10, k = 5) {\n\n # Set up matrix for storing of the results\n\n res <- matrix(NA, nrow = k, ncol = n)\n rownames(res) <- paste(\"k = \", 1:k, sep = \"\")\n colnames(res) <- rep(\"\", n)\n\n # Loop over k\n\n for (i in 1:k) {\n\n tmp <- 1\n\n while (any(is.na(res[i, ]))) { # Keep looping if there are still missing entries in the result-matrix\n if (length(findfactors(tmp)) == i) { # Check number of factors\n res[i, which.max(is.na(res[i, ]))] <- tmp\n }\n tmp <- tmp + 1\n }\n }\n print(res)\n}\n", "meta": {"hexsha": "93c4426701990df09053c44c5f4764f5245e15e9", "size": 1278, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Almost-prime/R/almost-prime.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Almost-prime/R/almost-prime.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Almost-prime/R/almost-prime.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 25.56, "max_line_length": 105, "alphanum_fraction": 0.3748043818, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7258124621332269}} {"text": "#' @export\n#' @title correlationMatrix\n#' @description couldn't accurately describe\n#' @param \\code{X} \n#' @param \\code{dfr} degrees of freedom\n#' @param \\code{meth.} \n#' @return \\code{}\n#' @note X is the matrix of values with each column representing a single variable. The upper triangle of the resulting matrix is p-values and lower is cor test value\n#' @family statistical\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\ncorrelationMatrix <- function(X, dfr = nrow(X) - 2,meth.=c(\"pearson\", \"kendall\", \"spearman\")) {\n\t\t\t R <- round(cor(X,method=meth.),digits=4)\n\t\t\t\t above <- row(R) < col(R)\n\t\t\t\t r2 <- R[above]^2\n\t\t\t\t Fstat <- r2 * dfr / (1 - r2)\n\t\t\t\t R[above] <- 1 - pf(Fstat, 1, dfr)\n\t\t\t\t if( any(R[above]==0)) {\n\t\t\t\tR[above][which(R[above]==0)]<-0.0001\n\t \t\t }\n\t\t\t R\n\t\t\t}\n", "meta": {"hexsha": "2dc8dc5167b1bc6e4c1f657dc0a474223661c3bb", "size": 797, "ext": "r", "lang": "R", "max_stars_repo_path": "R/correlationMatrix.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/correlationMatrix.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/correlationMatrix.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.652173913, "max_line_length": 167, "alphanum_fraction": 0.6185696361, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7258124558608245}} {"text": "## LASSO BAYESIANO\nrm(list =ls())\n##load(\"hiv.rda\")\n##204 binary attributes and 704 observations\nlibrary(monomvn)\ndata(diabetes)\nattach(diabetes)\n## Ordinary Least Squares regression\nreg.ols <- regress(x, y)\n## Lasso regression\nreg.las <- regress(x, y, method=\"lasso\")\n## Bayesian Lasso regression. T: N�m de Muestras a Posteriori\n## thin: number of MCMC samples to skip before a sample is collected (via thinning)\nreg.blas <- blasso(x, y, T= 2000, thin = 50)\n## summarize the beta (regression coefficients) estimates\nplot(reg.blas, burnin=200)\npoints(drop(reg.las$b), col=2, pch=20)\npoints(drop(reg.ols$b), col=3, pch=18)\nlegend(\"topleft\", c(\"blasso-map\", \"lasso\", \"lsr\"), col=c(2,2,3), pch=c(21,20,18))\n## plot the size of different models visited\nplot(reg.blas, burnin=200, which=\"m\")\n## get the summary\ns <- summary(reg.blas, burnin=200)\ns$coef\n## Residual Variance\ns$s2\n## calculate the probability that each beta coef != zero\ns$bn0\n## A summary of the model order\ns$m\n## Lambda\ns$lambda2\n\n### BOOTSTRAP\npar(mfrow=c(1,1))\nlibrary(glmnet)\nrequire(boot)\n##X <- model.matrix(y~.,data=diabetes)\ncv.out=cv.glmnet(x,y,alpha=1)\nplot(cv.out)\nbestlam=cv.out$lambda.min\nbestlam\nfit1=glmnet(x,y)\ncoef(fit1,s=bestlam) # extract coefficients at a single value of lambda\n## Funci�n que extrae los coeficientes de LASSO dado el mejor lambda de VC\n## Muestra de bootstrap\nsample(1:10, size = 10, replace = T)\nset.seed(44)\nB <- 1000\nbetas <- matrix(0,B,11)\nlambdas <- rep(0, B)\nn.x <- nrow(x)\nfor (i in 1:B){\n mi.muestra <- sample(nrow(x), size = n.x, replace = T)\n x.b <- x[mi.muestra,]\n y.b <- y[mi.muestra]\n cv.out=cv.glmnet(x.b,y.b,alpha=1)\n fit1=glmnet(x.b,y.b,alpha=1)\n coefs <-coef(fit1,s=cv.out$lambda.min)\n betas[i,] <- coefs[,1]\n lambdas[i] <- cv.out$lambda.min\n}\nboxplot(betas)\nabline(h=0, col = \"green\", pch =20)\nmedia.betas <- apply(betas, 2, mean)\npoints(drop(media.betas), col=3, pch=18)\nsd.betas <- apply(betas, 2, sd)\nlimite.inferior <- apply(betas, 2, quantile, probs =0.025, na.rm = FALSE)\nlimite.superior <- apply(betas, 2, quantile, probs =0.975, na.rm = FALSE)\nintervalo.percentil = cbind(limite.inferior,limite.superior)\nrownames(intervalo.percentil) <- rownames(coefs)\nintervalo.percentil\nmean(lambdas)\n", "meta": {"hexsha": "a5207eeb5e036ae27091d133adfaed8dd7a3616a", "size": 2223, "ext": "r", "lang": "R", "max_stars_repo_path": "playground/bayesian_lasso.r", "max_stars_repo_name": "gonz4lex/data-science-projects", "max_stars_repo_head_hexsha": "7f83fdc5ead55ea620f7599f3359d4801adb99d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "playground/bayesian_lasso.r", "max_issues_repo_name": "gonz4lex/data-science-projects", "max_issues_repo_head_hexsha": "7f83fdc5ead55ea620f7599f3359d4801adb99d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "playground/bayesian_lasso.r", "max_forks_repo_name": "gonz4lex/data-science-projects", "max_forks_repo_head_hexsha": "7f83fdc5ead55ea620f7599f3359d4801adb99d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0405405405, "max_line_length": 83, "alphanum_fraction": 0.6968061179, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7257967789665396}} {"text": "model_snowaccumulation <- function (tsmax = 0.0,\n tmax = 0.0,\n trmax = 0.0,\n precip = 0.0){\n #'- Name: SnowAccumulation -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: snowfall accumulation calculation\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: It simulates the depth of snow cover and recalculate weather data\n #'- inputs:\n #' * name: tsmax\n #' ** description : maximum daily air temperature (tmax) below which all precipitation is assumed to be snow\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 1000\n #' ** unit : degC\n #' ** uri : \n #' * name: tmax\n #' ** description : current maximum air temperature\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : degC\n #' ** uri : \n #' * name: trmax\n #' ** description : tmax above which all precipitation is assumed to be rain\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : degC\n #' ** uri : \n #' * name: precip\n #' ** description : current precipitation\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : mmW\n #' ** uri : \n #'- outputs:\n #' * name: Snowaccu\n #' ** description : snowfall accumulation\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW/d\n #' ** uri : \n fs <- 0.0\n if (tmax < tsmax)\n {\n fs <- 1.0\n }\n if (tmax >= tsmax && tmax <= trmax)\n {\n fs <- (trmax - tmax) / (trmax - tsmax)\n }\n Snowaccu <- fs * precip\n return (list('Snowaccu' = Snowaccu))\n}", "meta": {"hexsha": "7d15eeebb5f1020d622a4c3d7752108de1eecf46", "size": 3319, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Snowaccumulation.r", "max_stars_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_stars_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/STICS_SNOW/Snowaccumulation.r", "max_issues_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_issues_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/STICS_SNOW/Snowaccumulation.r", "max_forks_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_forks_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4657534247, "max_line_length": 137, "alphanum_fraction": 0.3314251281, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418220680101, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7257364981837741}} {"text": "# Generates a new board - either a random one, sample blinker or gliders, or user specified.\ngen.board <- function(type=\"random\", nrow=3, ncol=3, seeds=NULL)\n{\n if(type==\"random\")\n {\n return(matrix(runif(nrow*ncol) > 0.5, nrow=nrow, ncol=ncol))\n } else if(type==\"blinker\")\n {\n seeds <- list(c(2,1),c(2,2),c(2,3))\n } else if(type==\"glider\")\n {\n seeds <- list(c(1,2),c(2,3),c(3,1), c(3,2), c(3,3))\n }\n board <- matrix(FALSE, nrow=nrow, ncol=ncol)\n for(k in seq_along(seeds))\n {\n board[seeds[[k]][1],seeds[[k]][2]] <- TRUE\n }\n board\n}\n\n# Returns the number of living neighbours to a location\ncount.neighbours <- function(x,i,j)\n{\n sum(x[max(1,i-1):min(nrow(x),i+1),max(1,j-1):min(ncol(x),j+1)]) - x[i,j]\n}\n\n# Implements the rulebase\ndetermine.new.state <- function(board, i, j)\n{\n N <- count.neighbours(board,i,j)\n (N == 3 || (N ==2 && board[i,j]))\n}\n\n# Generates the next interation of the board from the existing one\nevolve <- function(board)\n{\n newboard <- board\n for(i in seq_len(nrow(board)))\n {\n for(j in seq_len(ncol(board)))\n {\n newboard[i,j] <- determine.new.state(board,i,j)\n }\n }\n newboard\n}\n\n# Plays the game. By default, the board is shown in a plot window, though output to the console if possible.\ngame.of.life <- function(board, nsteps=50, timebetweensteps=0.25, graphicaloutput=TRUE)\n{\n if(!require(lattice)) stop(\"lattice package could not be loaded\")\n nr <- nrow(board)\n\n for(i in seq_len(nsteps))\n {\n if(graphicaloutput)\n {\n print(levelplot(t(board[nr:1,]), colorkey=FALSE))\n } else print(board)\n\n Sys.sleep(timebetweensteps)\n\n newboard <- evolve(board)\n\n if(all(newboard==board))\n {\n message(\"board is static\")\n break\n } else if(sum(newboard) < 1)\n {\n message(\"everything is dead\")\n break\n } else board <- newboard\n }\n invisible(board)\n}\n\n# Example usage\ngame.of.life(gen.board(\"blinker\"))\ngame.of.life(gen.board(\"glider\", 18, 20))\ngame.of.life(gen.board(, 50, 50))\n", "meta": {"hexsha": "ef10a58737dc489e7d9cf13bae2a398d8da23382", "size": 2085, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Conways-Game-of-Life/R/conways-game-of-life.r", "max_stars_repo_name": "mullikine/RosettaCodeData", "max_stars_repo_head_hexsha": "4f0027c6ce83daa36118ee8b67915a13cd23ab67", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Conways-Game-of-Life/R/conways-game-of-life.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Conways-Game-of-Life/R/conways-game-of-life.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 25.1204819277, "max_line_length": 109, "alphanum_fraction": 0.5966426859, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7255022372624644}} {"text": "\n## Stochastic GRADIENT DESCENT ALGORITHM\nstochastic_gd<-function(design_matrix,response,\n gradient_fn,cost_fn,threshold=0.01,\n max_pass=1,\n init_weights=matrix(rep(0,ncol(design_matrix)),ncol=1),\n learning_rate=0.1){\n theta<-init_weights\n alpha<-learning_rate\n n<-nrow(design_matrix)\n cost<-numeric()\n nrows<-nrow(X)\n for(k in 1:max_pass){\n index<-(1:nrows)[order(runif(nrows))]\n if(!is.null(cost_fn)){\n cost<-c(cost,cost_fn(response,design_matrix%*%theta))\n } \n if(tail(cost,n=1)=x,]$L)\n \n}\n\npl$cumL <- sapply(pl$r,cumPowerL) \n\nplot(log(cumL)~logr,data=pl)\n\npl1 <- pl[pl$logr<3,]\n\nlm1 <- lm(log(cumL)~logr,data=pl1) \n\nlm0 <- lm(log(cumL)~logr,data=pl) \n\nsummary(lm1)\n\ncoef(lm1)\n\nsummary(lm0)\n\n\nabline(lm1,col=\"red\")\n\nabline(lm0,col=\"blue\")\n\n# Exercise 4\n\npl2 <- pl[1:50,]\n\nlm2 <- lm(log(cumL)~logr,data=pl2) \n\nsummary(lm2)\n\ncoef(lm2)\n\nabline(lm2,col=\"green\")\n", "meta": {"hexsha": "6ca9af81b58f559c3e3f1a13282efa6f72dfd6b4", "size": 747, "ext": "r", "lang": "R", "max_stars_repo_path": "R/cursoR1.r", "max_stars_repo_name": "lsaravia/MultifractalsInR", "max_stars_repo_head_hexsha": "1dfe51dbd49f370551c45fd16fd37f4ce040b2ca", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-08-11T04:34:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-17T12:25:35.000Z", "max_issues_repo_path": "R/cursoR1.r", "max_issues_repo_name": "lsaravia/MultifractalsInR", "max_issues_repo_head_hexsha": "1dfe51dbd49f370551c45fd16fd37f4ce040b2ca", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/cursoR1.r", "max_forks_repo_name": "lsaravia/MultifractalsInR", "max_forks_repo_head_hexsha": "1dfe51dbd49f370551c45fd16fd37f4ce040b2ca", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-03-17T12:26:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-11T20:31:32.000Z", "avg_line_length": 10.8260869565, "max_line_length": 40, "alphanum_fraction": 0.5876840696, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7254188114130616}} {"text": "library(deSolve)\nlibrary(reshape2)\nlibrary(ggplot2)\n\n\nsir_ode <- function(times,init,parms){\n with(as.list(c(parms,init)), {\n # ODEs\n dS <- -beta*S*I\n dI <- beta*S*I-gamma*I\n dR <- gamma*I\n list(c(dS,dI,dR))\n })\n}\n\nparms <- c(beta=0.1,gamma=0.05)\ninit <- c(S=0.99,I=0.01,R=0) \ntimes <- seq(0,200,length.out=2001)\nsir_out <- lsoda(init,times,sir_ode,parms)\n\nsir_out_long <- melt(as.data.frame(sir_out),\"time\")\n\n# Plot\nggplot(sir_out_long, aes(x=time, y=value, colour=variable, group=variable)) +\n geom_line(lwd=2) + xlab(\"Time\") + ylab(\"Number\")\n", "meta": {"hexsha": "a671af6c8ed2a1d1400a9f61809494080fbc848f", "size": 553, "ext": "r", "lang": "R", "max_stars_repo_path": "models/simple_deterministic_models/sir/sir_desolve.r", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_deterministic_models/sir/sir_desolve.r", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_deterministic_models/sir/sir_desolve.r", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 21.2692307692, "max_line_length": 77, "alphanum_fraction": 0.6546112116, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7253710210451382}} {"text": "# bivariate skew-normal copula with parameters rho, ga1, ga2\r\n# such that determinant with these 3 correlation is positive definite\r\n# checks on cdf, pdf and conditional distributions\r\n\r\n# Rmat= [1 ga1 ga2; ga1 1 rho; ga2 rho 1 ] \r\n# is correlation matrix of (Z0,Z1,Z2)\r\n# the bivariate skew normal distribution is (Y1,Y2) = [Z1,Z2|Z0>0]\r\n# the conditional distribution is univariate extended skew-normal\r\n# with 4 parameters: xi=location, omega=scale, alpha=ga/sqrt(1-ga^2),\r\n# tau=(negative threshold) \r\n\r\n# these functions make use of functions in library(sn) and\r\n# library(CopulaModel)\r\n\r\n# param=c(rho,ga1,ga2), constraint is that\r\n# correlation matrix with these parameters should be positive definite\r\ndbskewn=function(y1,y2,param)\r\n{ rho=param[1]; ga1=param[2]; ga2=param[3]\r\n r2=1-rho^2\r\n #a1=ga1/sqrt(1-ga1^2)\r\n #a2=ga2/sqrt(1-ga2^2)\r\n s=1-ga1^2-ga2^2-rho^2+2*ga1*ga2*rho # should be positive\r\n s=sqrt(s/r2)\r\n be1=(ga1-rho*ga2)/r2\r\n be2=(ga2-rho*ga1)/r2\r\n bpdf=2*dbvn2(y1,y2,rho)*pnorm((be1*y1+be2*y2)/s)\r\n bpdf\r\n}\r\n\r\n#============================================================\r\n\r\n# compare\r\nlibrary(CopulaModel)\r\nlibrary(sn) \r\n\r\nrho=.7; ga1=.5; ga2=.1\r\nrho=.4; ga1=.4; ga2=-.1\r\nrho=.3; ga1=.4; ga2=-.3\r\na1=ga1/sqrt(1-ga1^2)\r\na2=ga2/sqrt(1-ga2^2)\r\nmypar=c(rho,ga1,ga2)\r\ny1=.5; y2=2.1\r\ny1=-.5; y2=-1.3\r\ny1=.5; y2=-1.3\r\nout2=dbskewn(y1,y2,mypar)\r\n\r\n# sn library\r\nrmat=matrix(c(1,rho,rho,1),2,2)\r\n#alpv=c(a1,a2) # this is not correct\r\ngav=c(ga1,ga2)\r\ntem=solve(rmat,gav)\r\nalpv=tem/sqrt(1-sum(gav*tem))\r\nout=dmsn(c(y1,y2),Omega=rmat,alpha=alpv)\r\ncat(out,out2,\"\\n\")\r\n# Ok matches\r\n# check some identities\r\ntem2=rmat%*%alpv\r\ngv=tem2/sqrt(1+sum(alpv*tem2))\r\nprint(c(gv))\r\nprint(gav)\r\nprint(1-sum(gav*tem))\r\nprint(1/(1+sum(alpv*tem2)))\r\n# Ok these match\r\n\r\n#============================================================\r\n\r\n# skew-normal copula from Azzalini-DallaValle's bivariate skew-normal\r\n# u,v = values or vectors in (0,1)\r\n# param = (rho,ga1,ga2), with -10\r\n\r\n# Output: bivariate skew-normal copula density\r\ndbskewncop=function(u,v,param)\r\n{ rho=param[1]; ga1=param[2]; ga2=param[3]\r\n r2=1-rho^2\r\n a1=ga1/sqrt(1-ga1^2)\r\n a2=ga2/sqrt(1-ga2^2)\r\n s=1-ga1^2-ga2^2-rho^2+2*ga1*ga2*rho # should be positive\r\n s=sqrt(s/r2)\r\n be1=(ga1-rho*ga2)/r2\r\n be2=(ga2-rho*ga1)/r2\r\n y1=qsn(u,0,1,alpha=a1)\r\n y2=qsn(v,0,1,alpha=a2)\r\n bpdf=2*dbvn2(y1,y2,rho)*pnorm((be1*y1+be2*y2)/s)\r\n denom=dsn(y1,alpha=a1)*dsn(y2,alpha=a2)\r\n cpdf=bpdf/denom\r\n cpdf\r\n}\r\n\r\n# Output: bivariate skew-normal copula cdf\r\npbskewncop=function(u,v,param)\r\n{ rho = param[1]; gav = param[2:3] \r\n rmat=matrix(c(1,rho,rho,1),2,2)\r\n tem=solve(rmat,gav)\r\n alpv=tem/sqrt(1-sum(gav*tem))\r\n ga1=gav[1]; ga2=gav[2]\r\n a1=ga1/sqrt(1-ga1^2)\r\n a2=ga2/sqrt(1-ga2^2)\r\n y1=qsn(u,alpha=a1); y2=qsn(v,alpha=a2)\r\n cdf=pmsn(c(y1,y2),Omega=rmat,alpha=alpv)\r\n cdf\r\n}\r\n\r\n# pcond21 = P(Veps*30) cat(\"*** ccdf roundoff???\\n\")\r\n ccdf2=pcond(u+eps,v,cpar)\r\n pdf=bpdf(u,v,cpar)\r\n #cat(u,v,ccdf,(ccdf2-ccdf)/eps,pdf,\"\\n\")\r\n tem=(ccdf2-ccdf)/eps\r\n cat(u,v,ccdf,tem,pdf,\"\\n\")\r\n if(abs(tem-pdf)>eps*30) cat(\"*** dcop roundoff???\\n\")\r\n }\r\n invisible(0)\r\n}\r\n\r\n\r\n# check of psn\\circ qsn is OK, \r\n# check of (psn(y+eps)-psn(y))/eps is OK\r\n\r\n#param=c(.7,.5,.5) \r\n#param=c(.7,.7,.1)\r\n#param=c(.5,.0,.1)\r\n#param=c(.1,.1,.1)\r\nparam=c(.2,.3,.1)\r\n\r\n# compare pcondbskewncop21 and pcondbskewncop12\r\na=c(.4,.5,.6)\r\nb=c(.1,.7,.8)\r\nfor(j in 1:3)\r\n{ out1=pcondbskewncop21(a[j],b[j],param)\r\n out2=pcondbskewncop12(a[j],b[j],param[c(1,3,2)])\r\n cat(out1,out2,\"\\n\")\r\n}\r\n# above two should be the same\r\n\r\n#u=.3\r\nu=.8\r\nvvec=seq(.4,.9,.1)\r\n\r\n#for(v in vvec) chkcopderiv(u,v,param,bcdf=pbskewncop,pcond=pcondbskewncop21,bpdf=dbskewncop,str=\"bskn\",eps=1.e-4)\r\n\r\nchkcopderiv(u,vvec,param,bcdf=pbskewncop,pcond=pcondbskewncop21,\r\n bpdf=dbskewncop)\r\n# OK\r\n\r\nchkcopderiv2(u,vvec,param,bcdf=pbskewncop,pcond=pcondbskewncop12,\r\n bpdf=dbskewncop)\r\n# OK\r\n\r\n\r\ncat(\"\\ncheck pcond and qcond as functional inverses\\n\")\r\nuvec=seq(.1,.6,.1)\r\nvvec=seq(.4,.9,.1)\r\n#par.pla=pla.b2cpar(.7)\r\n#chkcopcond(uvec,vvec,par.pla,pcondpla,qcondpla,\"pla\")\r\nchkcopcond(uvec,vvec,param,pcondbskewncop21,qcondbskewncop21,\"bskn\")\r\nchkcopcond(uvec,vvec,param,pcondbskewncop12,qcondbskewncop12,\"bskn\")\r\n# should above two be the same?\r\nchkcopcond(vvec,uvec,param,pcondbskewncop12,qcondbskewncop12,\"bskn\")\r\n\r\n# looks OK\r\n", "meta": {"hexsha": "d8b6264c7105dcbfb1b8b7dc8964530020130689", "size": 7472, "ext": "r", "lang": "R", "max_stars_repo_path": "bskewnormcop-original/bskewn-pqd.r", "max_stars_repo_name": "vincenzocoia/copsupp", "max_stars_repo_head_hexsha": "9b92e11670aff9a7b6ef8365fc2c9b3a8c904923", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-11-29T23:25:20.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-29T23:25:20.000Z", "max_issues_repo_path": "bskewnormcop-original/bskewn-pqd.r", "max_issues_repo_name": "vincenzocoia/copsupp", "max_issues_repo_head_hexsha": "9b92e11670aff9a7b6ef8365fc2c9b3a8c904923", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bskewnormcop-original/bskewn-pqd.r", "max_forks_repo_name": "vincenzocoia/copsupp", "max_forks_repo_head_hexsha": "9b92e11670aff9a7b6ef8365fc2c9b3a8c904923", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0739299611, "max_line_length": 115, "alphanum_fraction": 0.6319593148, "num_tokens": 3165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595115, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.725230808931563}} {"text": "view_list <- function(list) {\n\n for (item in 1:length(list)) {\n\n print(head(list[[item]]))\n\n }\n}\n\n\n#' row-wise centering\n#'\n#' center the col of matrix x\n#' @param x a matrix\n#'\n#' @keywords norm internal\ncenter_colmeans <- function(x) {\n xcenter <- colMeans(x)\n x - rep(xcenter, rep.int(nrow(x), ncol(x)))\n}\n\n#' The 2norm or Frobenius norm function\n#'\n#'\n#' @param x vector or matrix to calculate its 2norm or Frobenius norm\n#' @return 2norm or Frobenius norm\n#'\n#' @keywords norm internal\nnorm_2 <- function(x) sqrt(sum(x^2))\n\n\n\n#' Differencing matrix\n#'\n#' @param k number of coeficient to be diffed\n#' @param m order of differencing\n#'\n#' @keywords\n#'\ndiff_matrix <- function(k, m) {\n m_diff <- diag(k)\n while (m > 0) {\n m_diff <- diff(m_diff)\n m <- m - 1\n }\n if (is.vector(m_diff)) {\n m_diff <- t(m_diff)\n }\n return(m_diff)\n}\n\n\n\n#' P-spline basis\n#'\n#' Construct the $n \\times K$ spline matrix using quiv-distant knots\n#' $K = k_0 + m$\n#'\n#' @param x observations for the first covariate\n#' @param k0 number of internal knots\n#' @param m order of the basis splines\n#' @param x_range range of the spline basis,\n#' default to be NULL then use the c(max, min)\n#'\n#' @import splines\n#'\n#' @return $n \\times K$ spline matrix for the first covariate,\n#'\nspline_basis <- function(x, k0, m, x_range=NULL) {\n if (is.null(x_range)) {\n x_range <- c(max(x), min(x))\n }\n\n big <- x_range[1]; small <- x_range[2]\n h <- (big - small) / (k0 + 1)\n v_knots <- seq_len(k0) * h + small\n v_knots <- c(rep(small, m), v_knots, rep(big, m))\n out <- splines::splineDesign(v_knots, x, ord = m)\n return(out)\n}\n", "meta": {"hexsha": "afbf8b996560111e2f18bb5ca8ba90fa6012d9e5", "size": 1635, "ext": "r", "lang": "R", "max_stars_repo_path": "R/utils.r", "max_stars_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_stars_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/utils.r", "max_issues_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_issues_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/utils.r", "max_forks_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_forks_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1851851852, "max_line_length": 69, "alphanum_fraction": 0.6226299694, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7250454667708948}} {"text": "## This is free software and is offered with no warranty whatsoever.\n\n##utility function returns true if n-m is odd\n\n.odd <- function(n,m) {\n if (((n-m)%%2) == 0) {\n FALSE\n } else {\n TRUE\n }\n}\n\n\n##derivative (wrt r) of zernike polynomials\n## Iterative version of recurrence relation\n## given in Eqn. 13 of Mathworld Zernike article.\n\ndrzernike <- function(rho, n, m) {\n if ((n<0) || (m<0) || (n 0) {\n mtemp <- c(mtemp, rep(1:mmax, each=2))\n }\n mtemp <- rev(mtemp)\n n <- c(n, order-mtemp)\n m <- c(m, mtemp)\n t <- c(t, rep(c(\"c\", \"s\"), mmax), \"n\")\n }\n list(n=n, m=m, t=t)\n}\n\n## Augmented Fringe set\n\nzlist.fr <- makezlist(2,12)\n\n## list of ZP indexes in ISO/ANSI sequence\n\n#' Construct list of ZP indexes in ISO/ANSI sequence with sine terms first\n#'\n#' @param maxorder maximum radial and azimuthal order\n#' @return a named list with n=radial indexes, m=azimuthal, and t indicating\n#' trig function to apply\n#' @examples\n#' zlist.iso <- makezlist.iso(maxorder=6)\n#' zlist <- makezlist(0, 6)\nmakezlist.iso <- function(maxorder=12) {\n n <- numeric(0)\n m <- numeric(0)\n t <- \"n\"\n for (i in 0:maxorder) {\n n <- c(n, rep(i, i+1))\n m <- c(m, abs(seq(-i, i, by=2)))\n if (i >= 1) {\n t <- c(t, rep(\"s\" , (i+1) %/% 2))\n if (i %% 2 == 0) {\n t <- c(t, \"n\")\n }\n t <- c(t, rep(\"c\", (i+1) %/% 2))\n }\n }\n list(n=n, m=m, t=t)\n}\n\n## Vector of factors from conversion between \"normalized\" and conventional Zernike definitions\n\nzmult <- function(zlist = makezlist()) {\n mult <- sqrt(zlist$n+1)\n mult[zlist$m > 0] <- sqrt(2)*mult[zlist$m > 0]\n mult\n}\n\n## create a matrix of Zernike polynomial values\n\nzpm.arb <- function(rho, theta, phi=0, zlist=makezlist()) {\n\tzm <- matrix(0, nrow=length(rho), ncol=length(zlist$n))\n\tfor (i in (1:length(zlist$n))) {\n\t\tzm[,i] <- Zernike(rho,theta-pi*phi/180, zlist$n[i], zlist$m[i], zlist$t[i])\n\t}\n\tcolnames(zm) <- colnames(zm, do.NULL=FALSE, prefix=\"Z\")\n\tzm\n}\n\n## a faster Zernike matrix fill\n\nzpm <- function(rho, theta, phi=0, maxorder = 14, nthreads=parallel::detectCores()/2) {\n if (phi != 0) theta <- theta - pi*phi/180\n if (nthreads == 1) {\n zm <- zpmC(rho, theta, maxorder)\n } else {\n RcppParallel::setThreadOptions(numThreads = nthreads)\n zm <- zpmCP(rho, theta, maxorder)\n }\n colnames(zm) <- paste(\"Z\",0:(ncol(zm)-1), sep=\"\")\n zm\n}\n\n\n## fit zernikes to data\n\nfitzernikes <- function(wf, rho, theta, phi=0, maxorder = 14, \n nthreads=parallel::detectCores()/2, uselm=FALSE, isoseq=FALSE) {\n if (isoseq) {\n theta <- theta - pi * phi/180\n zm <- zpm_cart(x=rho*cos(theta), y=rho*sin(theta), maxorder=maxorder)\n } else {\n zm <- zpm(rho, theta, phi=phi, maxorder=maxorder, nthreads=nthreads)\n }\n zm.names <- colnames(zm)\n if (uselm) {\n fmla <- as.formula(paste(\"wf ~ -1 + \", paste(zm.names, collapse=\"+\")))\n dataf <- data.frame(cbind(wf, zm))\n fit <- lm(fmla, data=dataf)\n } else {\n fit <- qr.solve(crossprod(zm),crossprod(zm, wf))\n }\n fit\n}\n\n\n", "meta": {"hexsha": "ad39d4f86e143cff99b2752e1e083d8b23911d82", "size": 3868, "ext": "r", "lang": "R", "max_stars_repo_path": "R/zernikes.r", "max_stars_repo_name": "gmke/zernike", "max_stars_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/zernikes.r", "max_issues_repo_name": "gmke/zernike", "max_issues_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/zernikes.r", "max_forks_repo_name": "gmke/zernike", "max_forks_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3129251701, "max_line_length": 94, "alphanum_fraction": 0.5773009307, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7249875006660945}} {"text": " DSTEV Example Program Results\n\n Eigenvalues\n 0.6476 3.5470 8.6578 17.1477\n Eigenvectors\n 1 2 3 4\n 1 0.9396 0.3388 0.0494 0.0034\n 2 -0.3311 0.8628 0.3781 0.0545\n 3 0.0853 -0.3648 0.8558 0.3568\n 4 -0.0167 0.0879 -0.3497 0.9326\n\n Error estimate for the eigenvalues\n 3.8E-15\n\n Error estimates for the eigenvectors\n 1.3E-15 1.3E-15 7.5E-16 4.5E-16\n", "meta": {"hexsha": "b3334c5e1d470c881ac54686c41d0e51df6851e3", "size": 416, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/dstev_example.r", "max_stars_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_stars_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-01-28T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:26:43.000Z", "max_issues_repo_path": "examples/baseresults/dstev_example.r", "max_issues_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_issues_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/baseresults/dstev_example.r", "max_forks_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_forks_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-04-19T12:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:32:12.000Z", "avg_line_length": 24.4705882353, "max_line_length": 48, "alphanum_fraction": 0.5889423077, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.724615034020807}} {"text": "rsvd.checkargs <- function(x, k, q, retu, retvt)\n{\n assert.type(retu, \"logical\")\n assert.type(retvt, \"logical\")\n \n assert.natnum(k)\n if (k > nrow(x))\n comm.stop(\"'k' must be no greater than nrow(x)\")\n \n assert.natnum(q)\n \n ### TODO check for NA, NaN, Inf\n \n invisible(TRUE)\n}\n\n\n\n#' Random SVD\n#' \n#' @param x\n#' The input data matrix.\n#' @param k\n#' The number of singular values and/or left/right singular vectors\n#' to estimate.\n#' @param q\n#' An integer exponent, say 1, 2, or 3. See the paper for details.\n#' @param retu\n#' Logical; should the left singular vectors (\"U\") be returned?\n#' @param retvt\n#' Logical; should the transposed right singular vectors (\"VT\") be returned?\n#' \n#' @return\n#' A list cotaining the singular values, and, if requested, the\n#' left and/or right singular vectors.\n#' \n#' @references\n#' Halko, Martinsson, and Tropp. 2011. Finding structure with \n#' randomness: probabilistic algorithms for constructing approximate\n#' matrix decompositions. SIAM Review 53 217-288.\n#' \n#' @author\n#' George Ostrouchov and Drew Schmidt\n#' \n#' @examples\n#' \\dontrun{\n#' x <- matrix(rnorm(30), 10)\n#' \n#' rsvd(x)\n#' }\n#' \n#' @keywords SVD PCA\n#' @name rsvd\n#' @rdname rsvd\n#' @export\nrsvd <- function(x, k=1, q=3, retu=TRUE, retvt=TRUE)\n{\n rsvd.checkargs(x=x, k=k, q=q, retu=retu, retvt=retvt)\n \n if (class(x) != \"ddmatrix\")\n x <- as.matrix(x)\n \n k <- as.integer(k)\n q <- as.integer(q)\n \n \n ### Stage A from the paper\n n <- ncol(x)\n \n if (class(x) == \"matrix\")\n Omega <- matrix(runif(n*2L*k), nrow=n, ncol=2L*k)\n else if (class(x) == \"ddmatrix\")\n Omega <- ddmatrix(\"runif\", nrow=n, ncol=2L*k, bldim=x@bldim, ICTXT=x@ICTXT)\n \n Y <- x %*% Omega\n Q <- qr.Q(qr(Y))\n \n for (i in 1:q)\n {\n Y <- crossprod(x, Q)\n Q <- qr.Q(qr(Y))\n Y <- x %*% Q\n Q <- qr.Q(qr(Y))\n }\n \n \n ### Stage B\n B <- crossprod(Q, x)\n \n if (!retu)\n nu <- 0\n else\n nu <- min(nrow(B), ncol(B))\n \n if (!retvt)\n nv <- 0\n else\n nv <- min(nrow(B), ncol(B))\n \n svd.B <- La.svd(x=B, nu=nu, nv=nv)\n \n d <- svd.B$d\n d <- d[1L:k]\n \n \n # Produce u/vt as desired\n if (retu)\n {\n u <- svd.B$u\n u <- Q %*% u\n \n u <- u[, 1L:k, drop=FALSE]\n }\n \n if (retvt)\n {\n vt <- svd.B$vt[1L:k, , drop=FALSE]\n }\n \n # wrangle return\n if (retu)\n {\n if (retvt)\n svd <- list(d=d, u=u, vt=vt)\n else\n svd <- list(d=d, u=u)\n }\n else\n {\n if (retvt)\n svd <- list(d=d, vt=vt)\n else\n svd <- list(d=d)\n }\n \n return( svd )\n}\n", "meta": {"hexsha": "29d71c55a9af7ed137776b3a224b25a22c93cd58", "size": 2509, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rsvd.r", "max_stars_repo_name": "wrathematics/pbdML", "max_stars_repo_head_hexsha": "cac079480be8622b8ac781def5f81fe9932614bb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/rsvd.r", "max_issues_repo_name": "wrathematics/pbdML", "max_issues_repo_head_hexsha": "cac079480be8622b8ac781def5f81fe9932614bb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-09-22T22:36:57.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-22T22:45:14.000Z", "max_forks_repo_path": "R/rsvd.r", "max_forks_repo_name": "wrathematics/pbdML", "max_forks_repo_head_hexsha": "cac079480be8622b8ac781def5f81fe9932614bb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1811594203, "max_line_length": 79, "alphanum_fraction": 0.5559984057, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7245565490860517}} {"text": "# Example : 2 Chapter : 8.1 Page No: 414\n# Find movements , tensions, elongations of spring\nK1<-matrix(c(2,-1,0,-1,2,-1,0,-1,1),ncol=3)\nK11<-solve(K1)\nf<-c(1,1,1)\nu<-K11%*%f\nprint(\"Movements are given by mg/c * u and u is\")\nprint(u)\nA<-matrix(c(1,-1,0,0,1,-1,0,0,1),ncol=3)\ne<-A%*%u\nprint(\"Elongations are given by mg/c * e and e is\")\nprint(e)\ny<-solve(t(A))%*%f\nprint(\"Tensions are given by mg * y and y is\")\nprint(y)", "meta": {"hexsha": "5a83baa236e1bc05cbde7248a74dcd44673ab8e7", "size": 425, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.1.2/Ex8.1_2.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.1.2/Ex8.1_2.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.1.2/Ex8.1_2.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 28.3333333333, "max_line_length": 51, "alphanum_fraction": 0.6188235294, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762055074521, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7245387539105245}} {"text": "#' @export\n#' @title bufferCircle\n#' @description This function buffers a point by a specified radius \\code{n}. \n#' @param \\code{lonlat} = the position to buffer \n#' @param \\code{radius} = the radius in kilometers to buffer\n#' @param \\code{npoints} = number of discrete points to create (default is 100)\n#' @return data.frame of 101 indivual points of $lat and $lon\n#' @examples\n#' bufferCircle(c(-64.15,44.75),100)\n#' @author Adam Cook, \\email{Adam.Cook@@dfo-mpo.gc.ca}\n#' @export\nbufferCircle <- function(lonlat, radius, npoints=100) {\n\t#//**radius must be in km, this treats the globe as a sphere**\n\t \n\t\t Rearth <- 6378.137 \n\t Dd <- rep(radius / Rearth,npoints+1)\n\t \n\t Cc <- seq(0, 2*pi, by=2*pi/npoints) #turning direction\n\t\n\t lata <- lonlat[2] * (pi/180) #convert to radians\n\t lona <- lonlat[1] * (pi/180)\n\t\n\t latb <- asin(cos(Cc) * cos(lata) * sin(Dd) + sin(lata) * cos(Dd))\n\t dlon <- atan2(cos(Dd) - sin(lata) * sin(latb), sin(Cc) * sin(Dd) * cos(lata))\n\t lonb <- lona - dlon + pi/2\n\t\n\t lonb[lonb > pi] <- lonb[lonb > pi] - 2 * pi\n\t lonb[lonb < -pi] <- lonb[lonb < -pi] + 2 * pi\n\t\n\t latb <- latb * (180 / pi) #back to lat lon\n\t lonb <- lonb * (180 / pi)\n\t\n\t out <- data.frame(lon = lonb, lat = latb) \n\t return(out)\n }\n\n", "meta": {"hexsha": "2e1e96288c6c4a86f08d1e7430eb1e0a8bf7e71e", "size": 1301, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bufferCircle.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/bufferCircle.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/bufferCircle.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1621621622, "max_line_length": 83, "alphanum_fraction": 0.5857033051, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7245038600927278}} {"text": "# Since R is a vector based language that penalizes for loops, we will avoid\n# for-loops, instead using \"apply\" statement variants (like \"map\" in other\n# functional languages).\n\nset.seed(19771025) # set the seed to set the same results as this code\nN <- 10000 # trials\ntrue_answers <- sample(1:3, N, replace=TRUE)\n\n# We can assme that the contestant always choose door 1 without any loss of\n# generality, by equivalence. That is, we can always relabel the doors\n# to make the user-chosen door into door 1.\n# Thus, the host opens door '2' unless door 2 has the prize, in which case\n# the host opens door 3.\n\nhost_opens <- 2 + (true_answers == 2)\nother_door <- 2 + (true_answers != 2)\n\n## if always switch\nsummary( other_door == true_answers )\n## if we never switch\nsummary( true_answers == 1)\n## if we randomly switch\nrandom_switch <- other_door\nrandom_switch[runif(N) >= .5] <- 1\nsummary(random_switch == true_answers)\n\n\n\n## To go with the exact parameters of the Rosetta challenge, complicating matters....\n## Note that the player may initially choose any of the three doors (not just Door 1),\n## that the host opens a different door revealing a goat (not necessarily Door 3), and\n## that he gives the player a second choice between the two remaining unopened doors.\n\nN <- 10000 #trials\ntrue_answers <- sample(1:3, N, replace=TRUE)\nuser_choice <- sample(1:3, N, replace=TRUE)\n## the host_choice is more complicated\nhost_chooser <- function(user_prize) {\n # this could be cleaner\n bad_choices <- unique(user_prize)\n # in R, the x[-vector] form implies, choose the indices in x not in vector\n choices <- c(1:3)[-bad_choices]\n # if the first arg to sample is an int, it treats it as the number of choices\n if (length(choices) == 1) { return(choices)}\n else { return(sample(choices,1))}\n}\n\nhost_choice <- apply( X=cbind(true_answers,user_choice), FUN=host_chooser,MARGIN=1)\nnot_door <- function(x){ return( (1:3)[-x]) } # we could also define this\n # directly at the FUN argument following\nother_door <- apply( X = cbind(user_choice,host_choice), FUN=not_door, MARGIN=1)\n\n\n## if always switch\nsummary( other_door == true_answers )\n## if we never switch\nsummary( true_answers == user_choice)\n## if we randomly switch\nrandom_switch <- user_choice\nchange <- runif(N) >= .5\nrandom_switch[change] <- other_door[change]\nsummary(random_switch == true_answers)\n", "meta": {"hexsha": "bc7aa561a186c4391c2f8728c399b3273a5af3a7", "size": 2452, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Monty-Hall-problem/R/monty-hall-problem.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Monty-Hall-problem/R/monty-hall-problem.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Monty-Hall-problem/R/monty-hall-problem.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 38.9206349206, "max_line_length": 90, "alphanum_fraction": 0.7018760196, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7243990580158403}} {"text": "#loading the data\ndf = as.matrix(read.table('/home/smith/Downloads/nci.data.txt', header = FALSE , sep = \"\", dec = \".\"))\ndf2 = as.matrix(read.table('/home/smith/Downloads/label.txt', header = FALSE , sep = \"\", dec = \".\"))\nscaled_data = scale(t(df))\nr =nrow(scaled_data)\nc = nrow(scaled_data)\n#computing the pairwise differences\npair_diff = matrix(Inf ,nrow = r , ncol= c)\nfor (i in 1:r){\n for (j in 1:c){\n if(i!=j){\n pair_diff[i,j] = sqrt(sum((scaled_data[i,] - scaled_data[j,])^2))\n }\n }\n}\nupper_tri = upper.tri(pair_diff)\npair_diff[upper_tri] = Inf #making the reapeated distances infinity\n\ncluster_matrix = matrix(ncol =nrow(scaled_data), nrow = nrow(scaled_data))\ncluster_matrix[,1] = 1:64 #cluster matrix has all the cluster assignments from n to 1 cluster\nsl_pair_diff = pair_diff\nbranch_length = vector(length = r-1)\n#This for loop find the cluster assignments for single-linkage \nfor(m in 2:r){\n cluster_matrix[,m] = cluster_matrix[,m-1]\n min_diff = min(sl_pair_diff)\n r_min = which(sl_pair_diff ==min_diff , arr.ind =TRUE)[1,1]\n c_min = which(sl_pair_diff == min_diff, arr.ind =TRUE)[1,2]\n while(cluster_matrix[c_min,m] == cluster_matrix[r_min,m]){\n sl_pair_diff[r_min,c_min] = Inf\n min_diff = min(sl_pair_diff)\n r_min = which(sl_pair_diff ==min_diff , arr.ind =TRUE)[1,1]\n c_min = which(sl_pair_diff == min_diff, arr.ind =TRUE)[1,2]\n }\n branch_length[m-1] = min_diff\n sl_pair_diff[r_min,c_min] = Inf\n cluster_matrix[,m][cluster_matrix[,m] == cluster_matrix[r_min,m]] = cluster_matrix[c_min,m]\n cluster_matrix[,m] = as.numeric(factor(cluster_matrix[,m]))\n\n}\nsl_cluster_matrix = cluster_matrix\nprint(sl_cluster_matrix) #This is all cluster assignments at each level\nprint(branch_length) #This is the height at each of N-1 steps\n\n\n\n#The next part is for implementaion of Compllete Linkage\n# computing pair-wise distance again, this time using NaN value for unneeded redundancies\npair_diff = matrix(NaN ,nrow = r , ncol= c)\nfor (i in 1:r){\n for (j in 1:c){\n if(i!=j){\n pair_diff[i,j] = sqrt(sum((scaled_data[i,] - scaled_data[j,])^2))\n }\n }\n}\ncluster_matrix = matrix(ncol =nrow(scaled_data), nrow = nrow(scaled_data))\ncluster_matrix[,1] = 1:64\nbranch_length = vector(length = r-1)\ncl_pair_diff = pair_diff\n#This for loop find the cluster assignments for complete-linkage \nfor (m in 2:r){\n cluster_labels = as.data.frame(table(cluster_matrix[,m-1]))\n already_clustered = cluster_labels[,1]\n for(l in 1:length(already_clustered)){\n for(k in 1:length(already_clustered)){\n if(l!=k){\n cluster_value_1 = which(cluster_matrix[,m-1]==already_clustered[l])\n cluster_value_2 = which(cluster_matrix[,m-1]==already_clustered[k])\n comp_var =c(cluster_value_1,cluster_value_2)\n temp = max(cl_pair_diff[comp_var,comp_var], na.rm =TRUE)\n index = which(pair_diff ==temp,arr.ind =TRUE)\n cl_pair_diff[comp_var,comp_var] = NaN\n cl_pair_diff[index[1],index[2]]= temp \n } \n } \n }\n \n cluster_matrix[,m] = cluster_matrix[,m-1]\n min_diff = min(cl_pair_diff, na.rm =TRUE)\n r_min = which(cl_pair_diff ==min_diff , arr.ind =TRUE)[1,1]\n c_min = which(cl_pair_diff == min_diff, arr.ind =TRUE)[1,2]\n branch_length[m-1] = min_diff\n cl_pair_diff[r_min,c_min] = NaN\n cl_pair_diff[c_min,r_min] = NaN\n cluster_matrix[,m][cluster_matrix[,m] == cluster_matrix[r_min,m]] = cluster_matrix[c_min,m]\n cluster_matrix[,m] = as.numeric(factor(cluster_matrix[,m]))\n\n \n}\ncl_cluster_matrix = cluster_matrix\nprint(cl_cluster_matrix) #This is all cluster assignments at each level\nprint(branch_length) #This is the height at each of N-1 steps\n\n\n\n#The next part is for implementaion of Average Linkage\n\nbranch_length = vector(length = r-1)\ncl_pair_diff = pair_diff\n#This is an optional step of making redundant values zero,however, the loop already take cares of these values\nupper_tri = upper.tri(cl_pair_diff)\ncl_pair_diff[upper_tri] = NaN \n#This for loop find the cluster assignments for average-linkage \nfor (m in 2:r){\n cluster_labels = as.data.frame(table(cluster_matrix[,m-1]))\n already_clustered = cluster_labels[,1]\n for(l in 1:length(already_clustered)){\n for(k in 1:length(already_clustered)){\n if(l!=k){\n cluster_value_1 = which(cluster_matrix[,m-1]==already_clustered[l])\n cluster_value_2 = which(cluster_matrix[,m-1]==already_clustered[k])\n cl_pair_diff[cluster_value_1,cluster_value_1] =NaN\n cl_pair_diff[cluster_value_2,cluster_value_2] =NaN\n comp_var =c(cluster_value_1,cluster_value_2)\n temp = (sum(cl_pair_diff[comp_var,comp_var], na.rm =TRUE))/(length(cluster_value_1)*length(cluster_value_2))\n #temp = temp/(length(cluster_value_1)*length(cluster_value_2))\n cl_pair_diff[comp_var,comp_var] = NaN\n cl_pair_diff[cluster_value_1,cluster_value_2] = temp\n } \n } \n }\n cluster_matrix[,m] = cluster_matrix[,m-1]\n min_diff = min(cl_pair_diff, na.rm =TRUE)\n r_min = which(cl_pair_diff ==min_diff , arr.ind =TRUE)[1,1]\n c_min = which(cl_pair_diff == min_diff, arr.ind =TRUE)[1,2]\n \n branch_length[m-1] = min_diff\n cl_pair_diff[r_min,c_min] = NaN\n cluster_matrix[,m][cluster_matrix[,m] == cluster_matrix[r_min,m]] = cluster_matrix[c_min,m]\n cluster_matrix[,m] = as.numeric(factor(cluster_matrix[,m])) \n}\nal_cluster_matrix = cluster_matrix\nprint(al_cluster_matrix) #This is all cluster assignments at each level\nprint(branch_length) #This is the height at each of N-1 steps\n\n\n\n#The next part is for implementaion of Centroid Linkage\n#function to calculate distance\nmydist<- function(scaled_data){\n r =nrow(scaled_data)\n c = nrow(scaled_data)\n pair_diff = matrix(NaN ,nrow = r , ncol= c)\n for (i in 1:r){\n for (j in 1:c){\n if(i!=j){\n pair_diff[i,j] = sqrt(sum((scaled_data[i,] - scaled_data[j,])^2 ,na.rm=TRUE))\n }\n }\n}\n return(pair_diff)\n}\n\n#Next for loop find the cluster assignments for centroid-linkage \ncentroid_data = scaled_data\nnullified = matrix(FALSE,r,c) #This boolean matrix will keep track of the distances already used\nfor (m in 2:r){\n all_distance = mydist(centroid_data)\n diag(all_distance)= NaN\n upper_tri = upper.tri(all_distance)\n all_distance[upper_tri] = NaN\n all_distance[nullified] = NaN\n\n cluster_matrix[,m] = cluster_matrix[,m-1]\n min_diff = min(all_distance, na.rm = TRUE)\n r_min = which(all_distance ==min_diff , arr.ind =TRUE)[1,1]\n c_min = which(all_distance == min_diff, arr.ind =TRUE)[1,2]\n\n while(cluster_matrix[c_min,m] == cluster_matrix[r_min,m]){\n all_distance[r_min,c_min] = NaN\n min_diff = min(all_distance, na.rm = TRUE)\n r_min = which(all_distance == min_diff , arr.ind =TRUE)[1,1]\n c_min = which(all_distance == min_diff, arr.ind =TRUE)[1,2]\n }\n branch_length[m-1] = min_diff\n all_distance[r_min,c_min] = NaN\n cluster_matrix[,m][cluster_matrix[,m] == cluster_matrix[r_min,m]] = cluster_matrix[c_min,m]\n cluster_matrix[,m] = as.numeric(factor(cluster_matrix[,m]))\n nullified = is.nan(all_distance)\n\n cluster_labels = as.data.frame(table(cluster_matrix[,m-1]))\n already_clustered = as.numeric(as.matrix(cluster_labels[,1][cluster_labels[,2]>1]))\n\n for(l in 1:length(already_clustered)){\n cluster_value = which(cluster_matrix[,m-1]==already_clustered[l])\n if(length(cluster_value)>1)\n {\n total = colSums(scaled_data[cluster_value,])\n temp = total/length(cluster_value)\n centroid_data[cluster_value,] = temp\n }\n \n }\n \n}\n\ncent_cluster_matrix = cluster_matrix\nprint(cent_cluster_matrix) #This is all cluster assignments at each level\nprint(branch_length) #This is the height at each of N-1 steps\n\n\n#applying K-means to our dataset\nkm_out = kmeans(scaled_data , 3 , nstart = 20)\ntable(df2 , km_out$cluster)\n\nkm_out = kmeans(scaled_data , 4 , nstart = 20)\ntable(df2 , km_out$cluster)\nkm_out = kmeans(scaled_data , 5 , nstart = 20)\ntable(df2 , km_out$cluster)\nkm_out = kmeans(scaled_data , 6 , nstart = 20)\ntable(df2 , km_out$cluster)\nkm_out = kmeans(scaled_data , 7 , nstart = 20)\ntable(df2 , km_out$cluster)\nkm_out = kmeans(scaled_data , 15 , nstart = 20)\ntable(df2 , km_out$cluster)\n\n\n#comparing complete linkage and K-means both with clusters = 5\nkm_out = kmeans(scaled_data , 4, nstart = 20)\nkm_cluster = km_out$cluster\nhc_cluster = cl_cluster_matrix[,61]\ntable(km_cluster, hc_cluster)", "meta": {"hexsha": "eaf23746e33ab9957d77819aeb5026116e1a384f", "size": 8723, "ext": "r", "lang": "R", "max_stars_repo_path": "Assgn 3- Heirarchical Clustering Code.r", "max_stars_repo_name": "eshuenglish/Algorithm-Implementation-in-R", "max_stars_repo_head_hexsha": "7b6b75e010688050463a4126794d44effcefcdec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assgn 3- Heirarchical Clustering Code.r", "max_issues_repo_name": "eshuenglish/Algorithm-Implementation-in-R", "max_issues_repo_head_hexsha": "7b6b75e010688050463a4126794d44effcefcdec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assgn 3- Heirarchical Clustering Code.r", "max_forks_repo_name": "eshuenglish/Algorithm-Implementation-in-R", "max_forks_repo_head_hexsha": "7b6b75e010688050463a4126794d44effcefcdec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1165919283, "max_line_length": 123, "alphanum_fraction": 0.6755703313, "num_tokens": 2406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.724399049531779}} {"text": "#' Calculate Standard Error of Mean\n#'\n#' @param x a numerical vector\n#' @param na.rm a logical value whether we remove N/A value\n#'\n#' @return a numeric which is a statndard error of mean\n#'\n#' @importFrom stats na.omit\n#' @importFrom stats var\n#'\n#' @export\n#+\nse <- function(x, na.rm = FALSE) {\n\n # na.rm = TRUE, we remove NA using na.omit()\n if (na.rm) x <- na.omit(x)\n\n # calculate and return se\n sqrt(var(x) / length(x))\n}\n\n#' Summary table of variables\n#'\n#' @description This is alternative method of `summary()`\n#' for countable or continuous vairbales.\n#' Since this function returns a data frame,\n#' you can pass some output format function (e.g. `kable`) easily.\n#'\n#' @param data a `data.frame` object.\n#' @param vars a character vector of variables.\n#' @param stat a character vector of statisics.\n#' \"mean\" is an average, \"se\" is its standard errors,\n#' \"sd\" is a standard error, \"min\" is minimum, \"max\" is maximum,\n#' \"q25\" is a first quantile, \"median\" is median, \"q75\" is a third quantile.\n#' \"sum\" is a sum of variable, and \"N\" is sample size.\n#'\n#' @return an object whose class is `data.frame`\n#'\n#' @importFrom dplyr summarize_at\n#' @importFrom dplyr mutate\n#' @importFrom dplyr select\n#' @importFrom tidyr pivot_longer\n#' @importFrom tidyselect everything\n#' @importFrom magrittr %>%\n#'\n#' @export\n#+\nstatvars <- function(\n data, vars,\n stat = c(\n \"mean\", \"se\", \"sd\", \"min\", \"q25\", \"median\", \"q75\", \"max\", \"sum\", \"N\"\n )\n) {\n\n tab <- data %>%\n summarize_at(\n vars,\n list(\n mean = ~mean(., na.rm = TRUE),\n se = ~se(., na.rm = TRUE),\n sd = ~sd(., na.rm = TRUE),\n min = ~min(., na.rm = TRUE),\n q25 = ~quantile(., prob = .25, na.rm = TRUE),\n median = ~median(., na.rm = TRUE),\n q75 = ~quantile(., prob = .75, na.rm = TRUE),\n max = ~max(., na.rm = TRUE),\n sum = ~sum(., na.rm = TRUE),\n N = ~sum(!is.na(.))\n )\n )\n\n if (length(vars) == 1) {\n\n tab <- tab %>%\n mutate(vars = vars) %>%\n select(c(\"vars\", stat))\n\n } else {\n\n pattern <- \"(.*)_(mean|se|sd|min|q25|median|q75|max|sum|N)\"\n\n tab <- tab %>%\n pivot_longer(\n everything(),\n names_to = c(\"vars\", \".value\"),\n names_pattern = pattern\n ) %>%\n select(c(\"vars\", stat))\n\n }\n\n return(tab)\n\n}", "meta": {"hexsha": "7630539a5cc67a86c0b3bc6538ff6a12d548917e", "size": 2404, "ext": "r", "lang": "R", "max_stars_repo_path": "R/statvars.r", "max_stars_repo_name": "KatoPachi/Rkato", "max_stars_repo_head_hexsha": "383d78c19201e7099324cbabbae9b89602e6e3d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-03T14:16:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T14:16:05.000Z", "max_issues_repo_path": "R/statvars.r", "max_issues_repo_name": "KatoPachi/Rkato", "max_issues_repo_head_hexsha": "383d78c19201e7099324cbabbae9b89602e6e3d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-08-03T20:33:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T12:19:54.000Z", "max_forks_repo_path": "R/statvars.r", "max_forks_repo_name": "KatoPachi/Rkato", "max_forks_repo_head_hexsha": "383d78c19201e7099324cbabbae9b89602e6e3d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5744680851, "max_line_length": 80, "alphanum_fraction": 0.5540765391, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7243611296237403}} {"text": "# Preliminaries\n#-------------------------------------------------\n#install.packages('perm')\nlibrary(perm)\nrm(list = ls())\n\n# Fisher\n#-------------------------------------------------\n\n#permutations in a matrix\nperms <- chooseMatrix(8, 4)\n#observed values in treated [0,1,0,0,0,1,1,1]\nA <- matrix(c(0.462, 0.731, 0.571, 0.923, 0.333, 0.750, 0.893, 0.692), nrow=8, ncol=1, byrow=TRUE)\ntreatment_avg <- (1/4)*perms%*%A\ncontrol_avg <- (1/4)*(1-perms)%*%A\ntest_statistic <- abs(treatment_avg-control_avg)\nrownumber <- apply(apply(perms, 1, \n function(x) (x == c(0, 1, 0, 0, 0, 1, 1, 1))), \n 2, sum)\nrownumber <- (rownumber == 8)\nobserved_test <- test_statistic[rownumber == TRUE]\n\n#number of test statistics greater or equal the statistic observed\nlarger_than_observed <- (test_statistic >= observed_test)\nsum(larger_than_observed)\n\ndf <- data.frame(perms, control_avg, treatment_avg, test_statistic)\n\n# Fisher, large number (simulation by random instead of permutation)\n#-------------------------------------------------\nsimul_stat <- as.vector(NULL)\nschools <- read.csv('teachers_final.csv')\nset.seed(1001)\nfor(i in 1:1000) {\n print(i)\n schools$rand <- runif(100,min=0,max=1)\n schools$treatment_rand <- as.numeric(rank(schools$rand)<=49)\n schools$control_rand = 1-schools$treatment_rand\n simul_stat <-append(simul_stat,\n sum(schools$treatment_rand*schools$open)/sum(schools$treatment_rand) \n - sum(schools$control_rand*schools$open)/sum(schools$control_rand))\n}\n\nschools$control = 1-schools$treatment\nactual_stat <- sum(schools$treatment*schools$open)/sum(schools$treatment) - sum(schools$control*schools$open)/sum(schools$control)\nsum(abs(simul_stat) >= actual_stat)/NROW(simul_stat)\n#the result it's near to zero, so we need Neyman's\n\n# Neyman\n#---------------------------------------------------\n#Printing the ATE\nate <- actual_stat\nate\n\ncontrol_mean <- sum(schools$control*schools$open)/sum(schools$control)\ntreatment_mean <- sum(schools$treatment*schools$open)/sum(schools$treatment)\n\n#sample variances for treatment and control\ns_c <- (1/(sum(schools$control)-1))*sum(((schools$open-control_mean)*schools$control)^2)\ns_t <- (1/(sum(schools$treatment)-1))*sum(((schools$open-treatment_mean)*schools$treatment)^2)\n\n#formula to get neyman variance\nVneyman <- (s_c/sum(schools$control) + s_t/sum(schools$treatment))\nprint(sqrt(Vneyman))\n\n#t-statistic\nprint(actual_stat/sqrt(Vneyman))\nt_stat <- actual_stat/sqrt(Vneyman)\n\n#p-value\nprint(2 * (1 - pnorm(t_stat))) #near to zero\n\n#confident interval for 95%\nprint(actual_stat-1.96*sqrt(Vneyman))\nprint(actual_stat+1.96*sqrt(Vneyman))\n\n\n### Plotting Kernel Regression ###\n# (using np, ggplot doesn't have kernel regression)\n#install.packages('np')\nlibrary(np)\nbw_004 = npreg(xdat=schools$open, ydat=schools$pctpostwritten, bws = 0.04)\nplot(bw_004)\nbw_0001 = npreg(xdat=schools$open, ydat=schools$pctpostwritten, bws = 0.001)\nplot(bw_0001)\nbw_1 = npreg(xdat=schools$open, ydat=schools$pctpostwritten, bws = 1)\nplot(bw_1)\nbw_20 = npreg(xdat=schools$open, ydat=schools$pctpostwritten, bws = 20)\nplot(bw_20)\n\n\n### Plotting CDFs to know FSD ###\n#CDF: cumulative density function\n#FSD: first stochastic dominate\nlibrary(tidyverse)\n\n#Incorrect way\ncdf_treatment = ecdf(schools$treatment*schools$teacherscore)\ncdf_control = ecdf(schools$control*schools$teacherscore)\n#plot(cdf_treatment, col='blue')\nplot.ecdf(schools$treatment*schools$teacherscore, col='blue')\nlines(cdf_control, col='red')\n\n#Correct way\nschools$group[schools$treatment==1] <-\"T\"\nschools$group[schools$treatment==0] <-\"C\"\nggplot(schools, aes(pctpostwritten,colour = group)) + stat_ecdf()\n", "meta": {"hexsha": "c7e27951edc7e718fa97f6283f851deae2b3dd09", "size": 3662, "ext": "r", "lang": "R", "max_stars_repo_path": "homework7.r", "max_stars_repo_name": "samuxiii/r-projects", "max_stars_repo_head_hexsha": "13a17bdf5a3db2efcf785c4810bb55c86459bfb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework7.r", "max_issues_repo_name": "samuxiii/r-projects", "max_issues_repo_head_hexsha": "13a17bdf5a3db2efcf785c4810bb55c86459bfb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework7.r", "max_forks_repo_name": "samuxiii/r-projects", "max_forks_repo_head_hexsha": "13a17bdf5a3db2efcf785c4810bb55c86459bfb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-06-24T17:18:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T03:39:37.000Z", "avg_line_length": 33.9074074074, "max_line_length": 130, "alphanum_fraction": 0.6906062261, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7243611255075574}} {"text": "# Moving (rolling) averages: SMA, WMA, EMA in R\n\ninstall.packages(\"quantmod\") # instalujemy biblioteke \nlibrary(quantmod) # uruchamiamy ^ biblioteke\n\n# przyklad 1 dla Idea Bank SA\n\nstart <- as.Date(\"2019-01-01\") # data, od ktorej pobieramy dane; YYYY-MM-DD\nend <- as.Date(\"2019-05-01\") # data, do ktorej pobieramy dane; YYYY-MM-DD\n\ngetSymbols(\"IDA.WA\", src = \"yahoo\", from = start, to = end) # pobieramy dane nt. Idea Bank SA z Yahoo Finance (symbol w Yahoo Finance: IDA.WA; https://is.gd/Q82Ck2); wartosci w PLN\n\nhead(IDA.WA) # sprawdzamy czy zaciagnelismy dobre dane\n\ncandleChart(IDA.WA, up.col = \"green\", dn.col = \"red\", theme = \"white\", name = \"Idea Bank SA\") # rysujemy wykres swiecowy\naddSMA(n = 14, col = \"blue\") # rysujemy SMA z ostatnich 14 dni, kolor linii niebieski\naddWMA(n = 14, col = \"black\") # rysujemy WMA z ostatnich 14 dni, kolor linii czarny\naddEMA(n = 14, col = \"orange\") # rysujemy EMA z ostatnich 14 dni, kolor linii pomaranczowy\n\nSMA(IDA.WA[,-c(1,2,3,5,6)], n = 14) # obliczenie SMA; wykluczamy wszystkie kolumny oprocz tej z danymi, ktore nas interesuja tj. 4: IDA.WA.Close\n\n# przyklad 2 dla IBM \n\nstart <- as.Date(\"2009-01-01\")\nend <- as.Date(\"2019-01-01\")\n\ngetSymbols(\"IBM\", src = \"yahoo\", from = start, to = end) # wartosci w USD\n\ncandleChart(IBM, up.col = \"green\", dn.col = \"red\", theme = \"white\")\naddSMA(n = 90, col = \"blue\") # rysujemy SMA z ostatnich 90 dni\naddWMA(n = 90, col = \"black\")\naddEMA(n = 90, col = \"orange\")\n\nEMA(IBM[,-c(1,2,3,5,6)], n = 90) # EMA z ostatnich 90 dni", "meta": {"hexsha": "ed74100b1ef7c2f9733b51465540b34269d8dbcb", "size": 1509, "ext": "r", "lang": "R", "max_stars_repo_path": "R/moving_averages.r", "max_stars_repo_name": "vardecab/chunks", "max_stars_repo_head_hexsha": "87606761702eb9062e5de59c9fc8d4170eabf2ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/moving_averages.r", "max_issues_repo_name": "vardecab/chunks", "max_issues_repo_head_hexsha": "87606761702eb9062e5de59c9fc8d4170eabf2ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/moving_averages.r", "max_forks_repo_name": "vardecab/chunks", "max_forks_repo_head_hexsha": "87606761702eb9062e5de59c9fc8d4170eabf2ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3823529412, "max_line_length": 180, "alphanum_fraction": 0.6799204771, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7243464503912828}} {"text": "# GLAJENJE ČASOVNIH VRST\n# Finančni praktikum 2020/21\n# Mitja Mandić\n\n#PRVA NALOGA\n\n#uvoz in obdelava podatkov\nplatina <- read.csv(\"cetrta_naloga/platina20.csv\")\n\nplatina_zakljuceni <- platina$Close\n\n\nplatina_zakljuceni <- gsub(\",\", \"\", platina_zakljuceni)\nplatina_zakljuceni <- gsub(\"\\\\$\", \"\", platina_zakljuceni)\n\n#podatki do sredine maja 2020\n\ndolzina <- 129\n\nplatina_zakljuceni <- as.numeric(rev(platina_zakljuceni[1:dolzina]))\n\ngraf_platina <- ts.plot(platina_zakljuceni, ylab = \"Cena\")\ntitle(\"Platina\")\n\n\n#DRUGA NALOGA\n\n\n#druga a\nG <- function(vrsta, k) {\n \n glajene_vr <- c()\n #seštevamo delne vsote časovne vrste in jih delimo s k\n for (i in k:length(vrsta)) {\n glajene_vr[i] <- (1/k) * sum(vrsta[(i-k+1):i])\n }\n \n return(ts(glajene_vr))\n}\n\n\n\n#glajenje reda 7, k = 7\n\nglajena.7 <- G(platina_zakljuceni, 7)\n\nnaslednji_dan <- glajena[length(glajena)]\n\nts.plot(platina_zakljuceni,glajena.7, ylab = \"Cena\", col = c(\"black\", \"red\"))\ntitle(\"Glajenje reda 7\")\n\n#druga d\n\n#standardna kvadratična napaka\nMSE.7 <- sum((platina_zakljuceni[8:dolzina-1]-glajena.7[8:dolzina-1]) ^ 2) / (dolzina - 7)\n\n#postopek ponovljen še za reda k = 14 in k = 30\n#k = 14\nglajena.14 <- G(platina_zakljuceni,14)\n\nts.plot(platina_zakljuceni, glajena.14, ylab = \"Cena\", col = c(\"black\", \"red\"))\ntitle(\"Glajenje reda 14\")\nglajena.14.graf <- recordPlot\n\nMSE.14 <- sum((platina_zakljuceni[15:dolzina-1]-glajena.14[15:dolzina-1]) ^ 2) / (dolzina - 14)\n\n#k = 30\nglajena.30 <- G(platina_zakljuceni,30)\n\nts.plot(platina_zakljuceni, glajena.30, ylab = \"Cena\", col = c(\"black\", \"red\"))\ntitle(\"Glajenje reda 30\")\nglajena.30.graf <- recordPlot()\n\nMSE.30 <- sum((platina_zakljuceni[31:dolzina-1]-glajena.14[31:dolzina-1]) ^ 2) / (dolzina - 31)\n\n\npar(mfrow = c(2,2))\nts.plot(platina_zakljuceni,glajena.7, ylab = \"Cena\", col = c(\"black\", \"red\"))\ntitle(\"Glajenje reda 7\")\nts.plot(platina_zakljuceni, glajena.14, ylab = \"Cena\", col = c(\"black\", \"red\"))\ntitle(\"Glajenje reda 14\")\nts.plot(platina_zakljuceni, glajena.30, ylab = \"Cena\", col = c(\"black\", \"red\"))\ntitle(\"Glajenje reda 30\")\n\n\n\n#TRETJA NALOGA\n\n\n#eksponentno glajenje\n\nEG <- function(vrsta, alpha){\n l <- c()\n #začetna vrednost se ujema s prvo vrednostjo iz časovne vrste\n l[1] <- vrsta[1]\n for (i in 2:length(vrsta)){\n #rekurzivna formula za računanje naprej\n l[i] <- alpha * vrsta[i] + (1-alpha) * l[i-1]\n }\n return(ts(l))\n}\n\n#izbral sem vrednost 0.2, izračunal eksponentno glajeno vrsto.\nEG.02 <- EG(platina_zakljuceni, 0.2)\n\nts.plot(EG.02, platina_zakljuceni, col = c(\"red\", \"black\"), ylab = \"Cena\")\ntitle(\"Eskponentno glajenje\")\n\n\n\n\n\n", "meta": {"hexsha": "01ebe4b668cb651ba1ce5c4cab99fca21df2c1c0", "size": 2580, "ext": "r", "lang": "R", "max_stars_repo_path": "cetrta_naloga/Mandic4.r", "max_stars_repo_name": "mitja-mandic/financni-praktikum", "max_stars_repo_head_hexsha": "fe7ececd401b7a002b9e11bd69938ba98a96a081", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cetrta_naloga/Mandic4.r", "max_issues_repo_name": "mitja-mandic/financni-praktikum", "max_issues_repo_head_hexsha": "fe7ececd401b7a002b9e11bd69938ba98a96a081", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cetrta_naloga/Mandic4.r", "max_forks_repo_name": "mitja-mandic/financni-praktikum", "max_forks_repo_head_hexsha": "fe7ececd401b7a002b9e11bd69938ba98a96a081", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8318584071, "max_line_length": 95, "alphanum_fraction": 0.680620155, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7243464503912826}} {"text": "int2str <- function(x, b) {\n\tif(x==0) return(\"0\")\n\tif(x<0) return(paste0(\"-\", base(-x,b)))\n\t\n\tmap <- c(as.character(0:9), letters)\n\tres <- \"\"\n\twhile (x>0) {\n\t\tres <- c(map[x %% b + 1], res)\n\t\tx <- x %/% b\n\t}\n\treturn(paste(res, collapse=\"\"))\n}\n\nstr2int <- function(s, b) {\n\tmap <- c(as.character(0:9), letters)\n\ts <- strsplit(s,\"\")[[1]]\n\tres <- sapply(s, function(x) which(map==x))\n\tres <- as.vector((res-1) %*% b^((length(res)-1):0))\n\treturn(res)\n}\n\n## example: convert 255 to hex (ff):\nint2str(255, 16)\n\n## example: convert \"1a\" in base 16 to integer (26):\nstr2int(\"1a\", 16)\n", "meta": {"hexsha": "5b09d005360defa47354a7f42a2a9cba91c259a9", "size": 576, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Non-decimal-radices-Convert/R/non-decimal-radices-convert.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Non-decimal-radices-Convert/R/non-decimal-radices-convert.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Non-decimal-radices-Convert/R/non-decimal-radices-convert.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3333333333, "max_line_length": 52, "alphanum_fraction": 0.5555555556, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7242313497309223}} {"text": "## Table 11.5, DeGroot (4th ed.)\nboiling.pt <- read.csv(file = \"dados_ponto_fervura.csv\") \nhead(boiling.pt)\n\n## Ajustando o modelo\nlinmod <- lm(pressao ~ pt_fervura, data = boiling.pt)\nsummary(linmod)\n\n### plotting code taken from https://rstudio-pubs-static.s3.amazonaws.com/71339_d0b8346f41314979bc394448c5d60d86.html\ntemp_var <- predict(linmod, interval = \"prediction\")\nnew_df <- cbind(boiling.pt, temp_var)\n\nlibrary(ggplot2)\np0 <- ggplot(new_df, aes(pt_fervura, pressao))+\n geom_point() +\n scale_x_continuous(\"Ponto de fervura da água (ºF)\") + \n scale_y_continuous(\"Pressão atmosférica (inHG)\") +\n theme_bw(base_size = 16)\np0\n\np1 <- p0 + \n geom_line(aes(y = lwr), color = \"red\", linetype = \"dashed\")+\n geom_line(aes(y = upr), color = \"red\", linetype = \"dashed\")+\n geom_smooth(method=lm, se = TRUE) + \n theme_bw(base_size = 16)\n\np1", "meta": {"hexsha": "5c66cd2c563c68889165be31bbe7feda5c548be6", "size": 843, "ext": "r", "lang": "R", "max_stars_repo_path": "code/regressao_linear.r", "max_stars_repo_name": "jlduim/Statistical_Inference_BSc", "max_stars_repo_head_hexsha": "6dfa2441c0b09bfe39a68367a242a81d76c41778", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/regressao_linear.r", "max_issues_repo_name": "jlduim/Statistical_Inference_BSc", "max_issues_repo_head_hexsha": "6dfa2441c0b09bfe39a68367a242a81d76c41778", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/regressao_linear.r", "max_forks_repo_name": "jlduim/Statistical_Inference_BSc", "max_forks_repo_head_hexsha": "6dfa2441c0b09bfe39a68367a242a81d76c41778", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2222222222, "max_line_length": 117, "alphanum_fraction": 0.7034400949, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.7242075966916558}} {"text": "# Example : 3 Chapter : 4.1 Page No: 197\n# Rows of given matrix are perpendicular to the vector in nullspace\nA<-matrix(c(1,5,3,2,4,7),nrow=2)\nx<-c(1,1,-1)\nfor(i in 1:nrow(A)){\n dot_product<-sum(A[i,]*x)\n if(dot_product==0){\n print(paste(\"Row \",i,\"is perpendicular to x\"))\n }\n}", "meta": {"hexsha": "be7a53ffa93402b54ac14ef78a9b2bdb9f0115d2", "size": 288, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.1.3/Ex4.1_3.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.1.3/Ex4.1_3.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.1.3/Ex4.1_3.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 28.8, "max_line_length": 67, "alphanum_fraction": 0.625, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7242046118380183}} {"text": "## Bayesian online change point detection and offline learning\n\n## Inference in joint Gaussian distribution\n## Get P(X1|X2=x2) where P(X1,X2) is jointly Gaussian\n## returns the conditional mean and coviance matrix of P(x_1|x_2)\n## \n##\n## x2; numeric, an sample of X2, satisfying length(x2)=2){\n for(i in nPars[-1L]){\n out$m[[i]] <- c((m0*k0 + x[i])/k[1],\n (out$m[[i-1]]*k[1L:(i-1L)] + x[i]) / k[2L:i])\n out$S[[i]] <- c(S0+ x[i]^2+ k0*(m0^2) - k[1]*(out$m[[i]][1]^2),\n out$S[[i-1]]+ x[i]^2+ k[1L:(i-1L)]*(out$m[[i-1]]^2) - k[2L:i] * (out$m[[i]][-1]^2))\n out$logS[[i]] <- log(out$S[[i]])\n ## -D/2 log(pi) + D/2 log(k_{i-1}/k_i) + v_{i-1}/2 log(|S_{i-1}|) - v_i/2 log(|S_i|) + lmvGamma(v_i/2) - lmvGamma(v_{i-1}/2)\n out$p[[i]] <- d2logpi + logkii[1L:i] + vi2[1L:i] * c(logs0,out$logS[[i-1]]) - v2[1L:i]*out$logS[[i]] + loggammavii[1L:i]\n }\n }\n }else if(model==\"multivariate-gaussian\"){\n ## out <- list(m=lapply(nPars,FUN = function(l){matrix(0,l,D)}),\n ## S=lapply(nPars,FUN = function(l){array(0,dim = c(l,D,D))}))\n stop(\"multivariate-gaussian observation not supported yet\")\n }\n\n return(out)\n}\n\n## loglikelihood for Left Truncated and Right Censored data\n## return:\n## log P(q+1|q) = log S(q+1) - log S(q) and\n## log P(0|q) = log f(q+1) - log S(q)\n## as an nx2 matrix, n is the number of inputs, the first column is log P(q+1|q), second column is log P(0|q)\n## q: numeric vector\n## model.pars: parameters for the selected model\n## weibull: shape parameter and scale parameter()\n##\n## Example\n## logLTRC(1:10,shape = 2,scale = 10)\nlogLTRC <- function(q,cpt_model=c(\"weibull\",\"gamma\",\"exponential\"),shape=NULL,scale=NULL){\n cpt_model <- match.arg(cpt_model)\n if(cpt_model==\"weibull\"){\n ## lower.tail=FALSE is the survival function\n\n ## ## when assuming p(0|i) is dead at time t+1\n ## matrix(c(pweibull(q+1,shape=shape,scale=scale,lower.tail = FALSE,log.p = TRUE),dweibull(q+1,shape=shape,scale=scale,log = TRUE))-\n ## pweibull(q,shape=shape,scale=scale,lower.tail = FALSE,log.p = TRUE),ncol = 2)\n\n ## ## when assuming p(0|i) is dead at time (t,t+1]\n out <- matrix(0,nrow = length(q),ncol = 2)\n out[,1] <- pweibull(q+1,shape=shape,scale=scale,lower.tail = FALSE,log.p = TRUE)-pweibull(q,shape=shape,scale=scale,lower.tail = FALSE,log.p = TRUE)\n out[,2] <- log(-expm1(out[,1])) #IMPORTANT if use log(1-exp(out[,1])) will result in log(0) in some of the parameter settings, to avoid underflow, use expm1(x) to replace exp(x)-1\n out\n }else if(cpt_model==\"gamma\"){\n stop(\"In LTRC(): \",cpt_model,\" not supported yet!\")\n }else if(cpt_model==\"exponential\"){\n stop(\"In LTRC(): \",cpt_model,\" not supported yet!\")\n }else{\n stop(\"In LTRC(): \",cpt_model,\" not supported yet!\")\n }\n}\n\n## generate random shape and scale sample, for the change point distribution\n## when cpt_model = \"weibull\"\n## gamma distribution with prior parameter shape and scale for inverse-scale parameter\n## uniform distribution with prior start and end for shape parameter\n## other cpt_model are not yet supported\nrcpt <- function(cpt_model=c(\"weibull\",\"gamma\",\"exponential\"),cpt_prior=list()){\n cpt_model <- match.arg(cpt_model)\n if(cpt_model==\"weibull\"){\n shape=runif(1,cpt_prior$start,cpt_prior$end)\n scale = 1/rgamma(1,cpt_prior$shape,cpt_prior$scale) #since gamma is for inverse-scale, now I need to inverse it back\n c(shape,scale)\n }else{\n stop(\"In rcpt(): \",cpt_model,\" not supported yet!\")\n }\n}\n\n## constructor of a \"bcp\" object, used in offline learning\n## use S3 with environment to achieve \"pass by reference\"\n##\n## x: numeric matrix, or an object that can be coerced to a matrix. Observation sequence, each row of x is a TRANSPOSE of an observation\n## breaks: the ending index of each segments. breaks = NULL is equivalent to breaks = nrow(x)\n## cpt_model: name of the change point distribution\n## obs_model: name of the observation distribution\n## obs_prior: prior parameters for observation model\n## if obs_model = \"univariate-normal\" or \"multivariate-gaussian\", prior should be a named list: list(m0,k0,v0,S0)\n## if obs_model = \"poisson\" or \"exponential\", prior should be a be a named list: list(scale)\n## if obs_model = \"gamma\" or \"weibull\", prior should be a named list: list(shape,scale)\n## if obs_model = ...\n## shape: initial shape parameter for change point distribution, no need to specify\n## scale: initial scale parameter for change point distribution, no need to specify\nbcp <- function(x=NULL,breaks=NULL,cpt_model=c(\"weibull\",\"gamma\",\"exponential\"),obs_model=c(\"univariate-gaussian\",\"multivariate-gaussian\",\"multinomial\",\"poisson\",\"exponential\",\"gamma\",\"linear\"),obs_prior=list(),cpt_prior=list(),shape=NULL,scale=NULL){\n\n cpt_model <- match.arg(cpt_model)\n obs_model <- match.arg(obs_model)\n\n object <- new.env(parent=globalenv())\n\n x <- as.matrix(x)\n object$x <- x\n\n if(is.null(breaks)){\n object$breaks <- c(0,nrow(x))\n object$Nsegs <- 1 #number of segments\n object$segLengths <- nrow(x) #length of each segment\n }else{\n if(any(breaks<=0 | breaks > nrow(x)) | is.unsorted(breaks)) stop(\"Error in bcp(): values in 'breaks' has to be ordered and range between [1,nrow(x))\")\n object$breaks <- c(0,breaks)\n object$Nsegs <- length(object$breaks)-1\n object$segLengths <- diff(object$breaks)\n }\n\n object$nPars <- numeric(0) #number of unique run-lengths per time point\n for(i in 1:object$Nsegs)\n object$nPars <- c(object$nPars,1:object$segLengths[i])\n object$D <- ncol(x) #dimension\n object$T <- nrow(x)\n\n object$maxRun <- max(diff(object$breaks)) #maximum run length\n\n if(is.null(shape) & is.null(scale)){\n ss <- rcpt(cpt_model = cpt_model,cpt_prior = cpt_prior)\n object$shape <- ss[1]\n object$scale <- ss[2]\n }else if(!is.null(shape) & !is.null(scale)){\n object$shape <- shape\n object$scale <- scale\n }else{\n stop(\"Error in bcp(): shape and scale should both be NULL of non-NULL\")\n }\n object$cpt_model <- cpt_model\n object$obs_model <- obs_model\n object$obs_prior <- obs_prior\n object$cpt_prior <- cpt_prior\n\n ## generate lower/upper search bound for L-BFGS-B algorithm\n if(cpt_model==\"weibull\"){\n object$lower <- c(cpt_prior$start,1e-7)\n object$upper <- c(cpt_prior$end,qgamma(0.99999999,shape = cpt_prior$shape,scale=cpt_prior$scale))\n ## object$upper <- c(cpt_prior$end,500)\n }else{\n stop(\"In bcp(): \",cpt_model,\" not supported yet!\")\n }\n\n class(object) <- 'bcp'\n \n return(object)\n\n}\n\n## offline forward filtering\n## x: numeric matrix, or an object that can be coerced to a matrix. Observation sequence, each row of x is a TRANSPOSE of an observation\n## cpt_model: name of the change point distribution\n## shape: shape parameter for change point distribution\n## scale: scale parameter for change point distribution\n## obs_model: name of the observation distribution\n## obs_prior: prior parameters for observation model\n## if obs_model = \"univariate-normal\" or \"multivariate-gaussian\", prior should be a named list: list(m0,k0,v0,S0)\n## if obs_model = \"poisson\" or \"exponential\", prior should be a be a named list: list(scale)\n## if obs_model = \"gamma\" or \"weibull\", prior should be a named list: list(shape,scale)\n## if obs_model = ...\nbcpFiltering <- function(bcpObj,...) UseMethod(\"bcpFiltering\")\nbcpFiltering.bcp <- function(bcpObj){\n ## if(nrow(bcpObj$x)<2) stop(\"Error in bcpFiltering(): there should be at least 2 observations\")\n \n bcpObj$a <- lapply(bcpObj$nPars,FUN = function(l){rep(0,l)}) #place holder for filtered result\n ## generate the transition matrix\n ## first column: P(q+1|q), second column: P(0|q)\n bcpObj$transition <- logLTRC(0L:(bcpObj$maxRun-1L),cpt_model = bcpObj$cpt_model,shape = bcpObj$shape,scale=bcpObj$scale)\n bcpObj$transition <- exp(bcpObj$transition)\n \n ## generate the prediction probability: log P(x_t | r_t, x^{(r_t)})\n bcpObj$pxr <- list()\n for(s in 1:bcpObj$Nsegs){\n bcpObj$pxr <- c(bcpObj$pxr,bcpPrediction(x=bcpObj$x[(bcpObj$breaks[s]+1):bcpObj$breaks[s+1],,drop=FALSE],model = bcpObj$obs_model,prior = bcpObj$obs_prior)$p) #only log probability is needed, so append a \"$p\" at the end\n }\n bcpObj$pxr_exp <- lapply(bcpObj$pxr,exp) #not log version\n \n tmp <- 0 #temporary variable\n LL <- 0\n start <- 0 #starting location of each segment\n for(s in 1:bcpObj$Nsegs){\n start <- bcpObj$breaks[s]\n bcpObj$a[[start+1]] <- 1\n LL <- LL+ bcpObj$pxr[[start+1]] #observed data log likelihood\n for(i in 2:bcpObj$segLengths[s]){\n bcpObj$a[[start+i]] <- log(c(sum(bcpObj$transition[1:(i-1),2]*bcpObj$a[[start+i-1]]),bcpObj$transition[1:(i-1),1]*bcpObj$a[[start+i-1]]))+\n bcpObj$pxr[[start+i]]\n tmp <- logsumexp(matrix(bcpObj$a[[start+i]],nrow = 1)) #normalizing constant of the filtering process, which happens to be log P(x_t|x_1:t-1)\n LL <- LL+tmp\n bcpObj$a[[start+i]] <- bcpObj$a[[start+i]]-tmp\n bcpObj$a[[start+i]] <- exp(bcpObj$a[[start+i]])\n }\n }\n\n ## add prior likelihood\n if(bcpObj$cpt_model==\"weibull\"){\n logprior <- dunif(bcpObj$shape,min = bcpObj$cpt_prior$start,max = bcpObj$cpt_prior$end,log = TRUE)+\n dgamma(bcpObj$scale,shape = bcpObj$cpt_prior$shape,scale = bcpObj$cpt_prior$scale,log = TRUE)\n }else{\n stop(\"In bcpEM.bcp().obj(): \",bcpObj$cpt_model,\" not supported yet!\")\n }\n \n LL <- LL+logprior\n \n ## append resuts to bcp object\n bcpObj$LL <- LL\n}\n\n## offline forward filtering and backward smoothing\nbcpSmoothing <- function(bcpObj,...) UseMethod(\"bcpSmoothing\")\nbcpSmoothing.bcp <- function(bcpObj){\n ## ----------------first part same as bcpFiltering----------------\n ## ---forward filtering---\n bcpFiltering(bcpObj)\n \n ## ---backward smoother---\n bcpObj$b <- lapply(bcpObj$nPars,FUN = function(l){rep(0,l)}) #place holder for backward result\n bcpObj$g <- lapply(bcpObj$nPars,FUN = function(l){rep(0,l)}) #place holder for smoothed result\n ## invisible(gc)\n start <- 0 #starting location of each segment\n for(s in 1:bcpObj$Nsegs){\n start <- bcpObj$breaks[s]\n ## end <- bcpObj$breaks[s+1]\n bcpObj$b[[bcpObj$breaks[s+1]]] <- rep(1,bcpObj$segLengths[s])\n bcpObj$g[[bcpObj$breaks[s+1]]] <- bcpObj$a[[bcpObj$breaks[s+1]]]\n for(i in (bcpObj$segLengths[s]-1):1){\n ## transition: first column: P(q+1|q), second column: P(0|q)\n bcpObj$b[[start+i]] <- bcpObj$transition[1:i,1] * bcpObj$pxr_exp[[start+i+1]][-1] * bcpObj$b[[start+i+1]][-1]+\n bcpObj$transition[1:i,2] * bcpObj$pxr_exp[[start+i+1]][1] * bcpObj$b[[start+i+1]][1]\n bcpObj$b[[start+i]] <- bcpObj$b[[start+i]]/sum(bcpObj$b[[start+i]]) #normalize to make sure it won't underflow\n bcpObj$g[[start+i]] <- bcpObj$b[[start+i]]*bcpObj$a[[start+i]]\n bcpObj$g[[start+i]] <- bcpObj$g[[start+i]]/sum(bcpObj$g[[start+i]])\n }\n }\n}\n\n## Two slice likelihoods, and filtered and smoothed\nbcpTwoslice <- function(bcpObj,...) UseMethod(\"bcpTwoslice\")\nbcpTwoslice.bcp <- function(bcpObj){\n bcpSmoothing(bcpObj)\n\n ## can be see as a aparse version of the twoslice matrix\n ## because t in 1:T-1, so run length are in 0:T-2, i.e. T-1 unique different run lengths\n bcpObj$pii <- matrix(0,nrow = bcpObj$maxRun-1,ncol=2) #place holder for transition counts\n for(s in 1:bcpObj$Nsegs){\n start <- bcpObj$breaks[s]\n for(i in 1:(bcpObj$segLengths[s]-1)){\n ## tansition: first column: P(q+1|q), second column: P(0|q)\n tmp <- bcpObj$transition[1:i,,drop=FALSE] * bcpObj$a[[start+i]]\n tmp[,1] <- tmp[,1] * bcpObj$b[[start+i+1]][-1] * bcpObj$pxr_exp[[start+i+1]][-1]\n tmp[,2] <- tmp[,2] * bcpObj$b[[start+i+1]][1] * bcpObj$pxr_exp[[start+i+1]][1]\n tmp <- tmp/sum(tmp) #normalize\n bcpObj$pii[1:i,] <- bcpObj$pii[1:i,] + tmp #the transition counts\n }\n }\n \n}\n\n\n## Offline learning with exact method\n## use generalized EM algorithm\n## \n## nstart: number of random restarts\n## maxit: maximum number of EM iterations for each (re)start\n## deps: converge if LL-previousLL=2){\n ss <- rcpt(cpt_model = bcpObj$cpt_model,cpt_prior = bcpObj$cpt_prior)\n bcpObj$shape <- ss[1]\n bcpObj$scale <- ss[2]\n }\n\n ## main EM loop start --------------------------------\n it <- 0\n maxLLit <- -Inf #current maximum likelihood/postori\n while(it <= maxit){\n ## 1. E step-------------------------------\n ## filter, smoother and twoslice\n bcpTwoslice(bcpObj)\n ## if(bcpObj$LL-maxLLit< -deps){\n if(bcpObj$LL < maxLLit){\n cat(\"diff\",bcpObj$LL-maxLLit,\"\\n\")\n stop(\"decreasing likelihood, LL: \",bcpObj$LL) #some numerical error is irreducible\n }\n else if(bcpObj$LL-maxLLit maxLL){\n maxLL <- maxLLit\n bcpObj$MAP <- c(bcpObj$shape,bcpObj$scale) #get the best MAP estimate\n }\n }\n \n}\n\nbcpMCMC <- function(bcpObj,burnin=100,nSample=5000) UseMethod(\"bcpMCMC\")\nbcpMCMC.bcp <- function(bcpObj,burnin=100,nSample=5000){\n}\n\n## constructor of a \"bcpo\" object, used in online filtering\n## use S3 with environment to achieve \"pass by reference\"\n##\n## cpt_model: name of the change point distribution\n## shape: shape parameter for change point distribution\n## scale: scale parameter for change point distribution\n## obs_model: name of the observation distribution\n## obs_prior: prior parameters for observation model\n## if obs_model = \"univariate-normal\" or \"multivariate-gaussian\", prior should be a named list: list(m0,k0,v0,S0)\n## if obs_model = \"poisson\" or \"exponential\", prior should be a be a named list: list(scale)\n## if obs_model = \"gamma\" or \"weibull\", prior should be a named list: list(shape,scale)\n## if obs_model = ...\n## l: inference lag, bcpOline will perform online filtering when when l=0, smoothing when l = Inf, fixed lag smoothing when 0 bcpoObj$filterTracker){\n magneticHead <- bcpoObj$filterTracker+1L\n if(magneticHead==1){\n bcpoObj$a[[1]] <- 1\n bcpoObj$filterTracker <- magneticHead\n bcpoObj$pCPT <- 1\n bcpoObj$isCPT <- TRUE\n next\n }\n bcpoObj$a[[magneticHead]] <- log(c(sum(bcpoObj$transition[1:(magneticHead-1),2]*bcpoObj$a[[magneticHead-1]]),bcpoObj$transition[1:(magneticHead-1),1]*bcpoObj$a[[magneticHead-1]])) + bcpoObj$pxr[[magneticHead]]\n bcpoObj$a[[magneticHead]] <- bcpoObj$a[[magneticHead]]-logsumexp(matrix(bcpoObj$a[[magneticHead]],nrow = 1)) #minus the logsumexp to normalize\n bcpoObj$a[[magneticHead]] <- exp(bcpoObj$a[[magneticHead]])\n bcpoObj$filterTracker <- magneticHead\n bcpoObj$pCPT <- c(bcpoObj$pCPT,bcpoObj$a[[magneticHead]][1]) #attach change point probability\n bcpoObj$isCPT <- c(bcpoObj$isCPT,which.max(bcpoObj$a[[magneticHead]])==1)\n }\n\n ## online fixed-lag smoother ----------------------------\n magneticHead <- 0\n magneticEnd <- 0\n while(bcpoObj$smootherTracker < (bcpoObj$T-bcpoObj$l) & bcpoObj$l > 0L){\n magneticHead <- bcpoObj$smootherTracker+1L\n magneticEnd <- bcpoObj$smootherTracker+1L+bcpoObj$l\n bPre <- rep(1,magneticEnd) #the last backward info\n ## pass backward info\n for(i in (magneticEnd-1L):magneticHead){\n b <- bcpoObj$transition[1:i,1] * bcpoObj$pxr_exp[[i+1]][-1] * bPre[-1]+\n bcpoObj$transition[1:i,2] * bcpoObj$pxr_exp[[i+1]][1] * bPre[1]\n b <- b/sum(b) #normalize to make sure it won't underflow\n bPre <- b\n }\n ## merge with forward info\n bcpoObj$a[[magneticHead]] <- b*bcpoObj$a[[magneticHead]] #merge backward info into a\n bcpoObj$a[[magneticHead]] <- bcpoObj$a[[magneticHead]]/sum(bcpoObj$a[[magneticHead]])\n bcpoObj$smootherTracker <- magneticHead\n bcpoObj$pCPT[magneticHead] <- bcpoObj$a[[magneticHead]][1] #update the believe of the lagged change point probability\n bcpoObj$isCPT[magneticHead] <- which.max(bcpoObj$a[[magneticHead]])==1 #update the changepoint ideicator\n }\n\n}\n", "meta": {"hexsha": "615f859687ab741bfe3576084815de0fa75ce5e3", "size": 32691, "ext": "r", "lang": "R", "max_stars_repo_path": "R/changepoints.r", "max_stars_repo_name": "chenhaotian/Changepoints", "max_stars_repo_head_hexsha": "4ce53432a29343012419c3bcc01d3e60cd5f9f5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2016-08-15T14:55:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T04:53:13.000Z", "max_issues_repo_path": "R/changepoints.r", "max_issues_repo_name": "chenhaotian/Changepoints", "max_issues_repo_head_hexsha": "4ce53432a29343012419c3bcc01d3e60cd5f9f5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-05-03T10:32:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T14:55:21.000Z", "max_forks_repo_path": "R/changepoints.r", "max_forks_repo_name": "chenhaotian/Changepoints", "max_forks_repo_head_hexsha": "4ce53432a29343012419c3bcc01d3e60cd5f9f5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-01-05T01:59:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T18:12:20.000Z", "avg_line_length": 45.0910344828, "max_line_length": 251, "alphanum_fraction": 0.5988804258, "num_tokens": 9833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.72415228709793}} {"text": "# If we list all the natural numbers below 10 that are multiples of 3 or 5,\n# we get 3, 5, 6 and 9. The sum of these multiples is 23.\n\n# Find the sum of all the multiples of 3 or 5 below 1000.\n\n# Gives remainder when x is divided by y\nrem <- function(x, y) {\n a <- (x / y)\n b <- floor(a)\n diff <- a - b\n return(diff* y)\n}\n\n# Takes two numbers and returns true if x is a multiple of y\nmo <- function(x, y) {\n r <- rem(x, y)\n return(r == 0)\n}\n\nnums <- 1:999\nfun1 <- function(x) { return (mo(x,3) || mo(x,5)) }\nindexes <- sapply(nums, fun1)\nsum(nums[indexes])", "meta": {"hexsha": "0ac9e18fac16d7d29c5d11f773091a9644692275", "size": 562, "ext": "r", "lang": "R", "max_stars_repo_path": "problem01.r", "max_stars_repo_name": "aquaporin/projecteuler", "max_stars_repo_head_hexsha": "fcf61c62231923fc0cf4dc3200ae4bc699c0d0ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem01.r", "max_issues_repo_name": "aquaporin/projecteuler", "max_issues_repo_head_hexsha": "fcf61c62231923fc0cf4dc3200ae4bc699c0d0ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem01.r", "max_forks_repo_name": "aquaporin/projecteuler", "max_forks_repo_head_hexsha": "fcf61c62231923fc0cf4dc3200ae4bc699c0d0ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4347826087, "max_line_length": 75, "alphanum_fraction": 0.6227758007, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7241522651285351}} {"text": "d1<- function(S,K,t,r,sig) {\n ans <- (log(S/K) + (r + sig^2/2)*t) / (sig*sqrt(t))\n return(ans)\n} \n\nd2 <- function(S,K,t,r,sig) {\n return(d1(S,K,t,r,sig) - sig*sqrt(t))\n}\n\nCall <- function(S,K,t,r,sig) {\n d_1 <- d1(S,K,t,r,sig)\n d_2 <- d2(S,K,t,r,sig)\n return(S*pnorm(d_1) - K*exp(-r*t)*pnorm(d_2))\n}\n\n\nprint(d1(300,250,1,0.03,0.15))\nmicrobenchmark::microbenchmark(Call(300,250,1,0.03,0.15))\n", "meta": {"hexsha": "6508d952aa8721799906fc41910ad944e9b1db33", "size": 397, "ext": "r", "lang": "R", "max_stars_repo_path": "Benchmarks/black_scholes/R/black_scholes.r", "max_stars_repo_name": "JeannotJeannot/Learn", "max_stars_repo_head_hexsha": "b6a40a12772de06655e1c7ae4d7c1791a01e0c48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-10-03T02:20:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T20:50:17.000Z", "max_issues_repo_path": "Benchmarks/black_scholes/R/black_scholes.r", "max_issues_repo_name": "JeannotJeannot/Learn", "max_issues_repo_head_hexsha": "b6a40a12772de06655e1c7ae4d7c1791a01e0c48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-10-02T00:16:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T19:34:34.000Z", "max_forks_repo_path": "Benchmarks/black_scholes/R/black_scholes.r", "max_forks_repo_name": "JeannotJeannot/Learn", "max_forks_repo_head_hexsha": "b6a40a12772de06655e1c7ae4d7c1791a01e0c48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-03-13T19:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T13:49:42.000Z", "avg_line_length": 20.8947368421, "max_line_length": 57, "alphanum_fraction": 0.5692695214, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7240256851187642}} {"text": "# Packages used : pracma\n# To install pracma,type following in command line while connected to internet\n# install.packages(\"pracma\") \n# package can be included by command \" library(pracma) \"\n# for more information about pracma visit https://cran.r-project.org/web/packages/pracma/index.html\n\n# Example : 3.4C Chapter : 3.4 Page No: 162\n# Find the Complete solution of the given system\n\nlibrary(pracma)\ncompletesolution <- function(A,b){\n R<-rref(A)\n m<-nrow(A)\n n<-ncol(A)\n pivotcol<-c() #vector to store the column numbers of pivot columns\n freecol<-c() #vector to store the column numbers of free columns\n i<-1\n j<-1\n \n # to find which columns are pivot and which are free\n while(i<=m & j<=n){\n if(R[i,j]==1){\n pivotcol<-c(pivotcol,j)\n i<-i+1\n j<-j+1\n }\n else{\n j<-j+1\n }\n }\n y<-length(pivotcol)\n freecol<-c(1:n)\n freecol<-freecol[!freecol%in%pivotcol]\n x<-length(freecol)\n N<-c()\n #find the basis for null space based on Row reduced echelon form of given matrix\n if(y==n){\n N<-c()\n }\n for(i in 1:x){\n temp<-c(1:n)\n for(j in 1:x){\n temp[freecol[j]]<-0\n }\n temp[freecol[i]]<-1\n temp[freecol[i]]\n for(j in 1:y){\n temp[pivotcol[j]]<-R[j,freecol[i]]*-1\n }\n N<-c(N,temp)\n }\n N<-matrix(N,nrow=n,ncol=x)\n s<-N\n Ab<-cbind(A,b)\n Rd<-rref(Ab)\n temp<-Rd[,n+1]\n p<-c(1:n)\n for(i in 1:length(freecol)){\n p[freecol[i]]<-0\n }\n for(i in 1:length(pivotcol)){\n p[pivotcol[i]]<-temp[i]\n }\n print(\"The special solution is\")\n print(s)\n print(\"The particular solution is\")\n print(p)\n print(\"Complete solution = particular solution + Special solution\")\n}\nA<-matrix(c(1,2,4,2,4,8,1,4,6,0,8,8),nrow=3)\nb<-c(4,2,10)\ncompletesolution(A,b)", "meta": {"hexsha": "1d77f3aa38d0d459d277aefdedcd8f4fc027d66e", "size": 1732, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH3/EX3.4.c/Ex3_3.4C.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH3/EX3.4.c/Ex3_3.4C.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH3/EX3.4.c/Ex3_3.4C.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 24.0555555556, "max_line_length": 99, "alphanum_fraction": 0.6172055427, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7236910857281172}} {"text": "=begin\n # sample-galois-group01.rb\n\n require \"algebra/rational\"\n require \"algebra/polynomial\"\n \n P = Algebra.Polynomial(Rational, \"x\")\n x = P.var\n \n (x**3 - 3*x + 1).galois_group.each do |g|\n p g\n end\n #=> [0, 1, 2]\n # [1, 2, 0]\n # [2, 0, 1]]\n \n (x**3 - x + 1).galois_group.each do |g|\n p g\n end\n #=> [0, 1, 2]\n # [1, 0, 2]\n # [2, 0, 1]\n # [0, 2, 1]\n # [1, 2, 0]\n # [2, 1, 0]\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "8db27e4dd150dd19a4bdedba44a360550438e40b", "size": 439, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-galois-group01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-galois-group01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-galois-group01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6785714286, "max_line_length": 43, "alphanum_fraction": 0.4555808656, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.7235428032659211}} {"text": "# Above Ground Biomass estimation\n#\n# Estimate above ground biomass following Chave et al. (2005)\n#\n# Chave, J. et al. 2005. Tree allometry and improved estimation of carbon \n# stocks and balance in tropical forests. - Oecologia 145: 87–99.\n#\n\nestbiomass <- function(ro, h=NULL, dhb=NULL, chb=NULL, type=NULL){\n\n if (is.null(chb) & is.null(dhb)) { stop(\"chb or dhb must be defined\\n\") }\n if (!is.null(chb) & is.null(dhb)) { dhb <- chb/pi }\n if (missing(ro)) { stop(\"ro must be defined\\n\") }\n if (!(type %in% c(\"dry\",\"moist\",\"mangrove\",\"wet\"))){\n stop(\"type must be defined as: 'dry', 'moist', 'mangrove' or 'wet'\\n\")\n }\n \n if (!is.null(h)){\n out <- switch(type,\n dry = exp(-2.187 + 0.916 * log(ro * (dhb^2) * h)),\n moist = exp(-2.977 + log(ro * (dhb^2) * h)),\n mangrove = exp(-2.977 + log(ro * (dhb ^ 2) * h)),\n wet = exp(-2.557 + 0.940 * log(ro * (dhb^2) * h)))\n } else {\n out <- switch(type,\n dry = (ro * exp(-0.667 + (1.784 * log(dhb)) + (0.207 * (log(dhb) ^ 2)) - (0.0281 * (log(dhb) ^ 3)))),\n moist = (ro * exp(-1.449 + (2.148 * log(dhb)) + (0.207 * (log(dhb) ^ 2)) - (0.0281 * (log(dhb) ^ 3)))),\n mangrove = (ro * exp(-1.349 + (1.980 * log(dhb)) + (0.207 * (log(dhb) ^ 2)) - (0.0281 * (log(dhb) ^ 3)))),\n wet = (ro * exp(-1.239 + (1.980 * log(dhb)) + (0.207 * (log(dhb) ^ 2)) - (0.0281 * (log(dhb) ^ 3)))))\n }\n \n return(out)\n}\n", "meta": {"hexsha": "88656bff104b6d04bf64c62ba1077b9d2dabb349", "size": 1493, "ext": "r", "lang": "R", "max_stars_repo_path": "estbiomass/estbiomass.r", "max_stars_repo_name": "MarioJose/r-functions", "max_stars_repo_head_hexsha": "a6b2693bd8151769cc799e81bbcc10654a85123e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-06-07T23:19:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T11:54:46.000Z", "max_issues_repo_path": "estbiomass/estbiomass.r", "max_issues_repo_name": "MarioJose/r-functions", "max_issues_repo_head_hexsha": "a6b2693bd8151769cc799e81bbcc10654a85123e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "estbiomass/estbiomass.r", "max_forks_repo_name": "MarioJose/r-functions", "max_forks_repo_head_hexsha": "a6b2693bd8151769cc799e81bbcc10654a85123e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9117647059, "max_line_length": 124, "alphanum_fraction": 0.4929671802, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.7233100368212532}} {"text": "euclidean <- function(a, b) sqrt(sum((a - b) ^ 2))\n\nrectKernel <- function(dist, h) if (dist <= h) 0.5 else 0\n\ntrKernel <- function(dist, h) if (dist <= h) (h - dist) / h else 0\n\nepKernel <- function(dist, h) if (dist <= h) (1 - dist ^ 2) * 0.75 else 0\n\ngaussKernel <- function(dist, h) exp(sqrt(h / pi * 0.5) * -0.5 * (dist * h) ^ 2)\n\nkvKernel <-function(dist, h) if (dist <= h) 15 / 16 * (1 - (dist / h) ^ 2) ^ 2 else 0\n\nparzen <- function(dset, labels, point, h, kernel, dist = euclidean) {\n dsetLength <- length(dset[,1])\n distances <- array(dim = c(dsetLength))\n \n uLabels <- unique(labels)\n # print(\"LABBB\")\n # print(apply(uLabels, 1, paste))\n classScores <- array(0L, dim = c(length(uLabels)))\n names(classScores) = uLabels;\n classScores[\"undefined\"] <- 0.000001\n \n for (i in 1:dsetLength) {\n classScores[labels[i]] <- classScores[labels[i]] + kernel(dist(point, dset[i,]), h)\n }\n \n return(names(which.max(classScores)))\n}\n\ngenerateMaps <- function() {\n xs <- seq(from = 0.5, to = 7.5, by = 0.1)\n ys <- seq(from = -1, to = 3.5, by = 0.1)\n \n colors <- c(\"setosa\" = \"blue\", \"virginica\" = \"red\", \"versicolor\" = \"green\", \"undefined\" = \"grey\")\n \n kernels <- c(\"rect\" = rectKernel, \"tr\" = trKernel, \"ep\" = epKernel, \"gauss\" = gaussKernel, \"kv\" = kvKernel)\n \n # par(mfrow = c(length(kernels) / 2, 2), pty=\"s\", mar=c(1,1,1,1))\n \n index <- 1\n for (kernelName in names(kernels)) {\n kernel <- kernels[[kernelName]]\n png(sprintf(\"plot-%03d.png\", index), width = 1024, height = 700, unit = \"px\", pointsize = 20)\n cat(\"Kernel:\", kernelName, index, \"of\", length(kernels), \"\\n\")\n index <- index + 1\n plot(iris[, 3:4], col = colors[paste(iris$Species)], pch=16, asp=1)\n \n all <- length(xs) * length(ys)\n progress = 1\n for (i in xs) {\n for (j in ys) {\n cat(\"\\rProcessing point\", progress, \"of\", all)\n progress <- progress + 1\n result <- parzen(iris[3:4], paste(iris$Species), c(i, j), 0.4, kernel)\n points(i, j, col = colors[result], pch = 21)\n }\n }\n cat(\"\\rDone. \\n\")\n dev.off()\n }\n}\n\n\nparzen_loo <- function (dset, labels, kernel, hs) {\n dsetLen <- dim(dset)[1]\n hLen <- length(hs)\n ans <- array(0L, dim = c(hLen))\n \n for (i in 1:hLen) {\n cat(\"h:\", hs[i], \"index:\", i, \"of\", hLen, \"\\n\")\n for (j in 1:dsetLen) {\n cat(\"\\rProcessing sample\", j, \"of\", dsetLen)\n tmpRes <- parzen(dset[-j,], labels[-j], dset[j,], hs[i], kernel)\n if (tmpRes != paste(labels[j])) {\n ans[i] <- ans[i] + 1\n }\n }\n print(ans)\n }\n \n ans <- ans / dsetLen\n return (ans)\n}\n\ngenerateLoos <- function() {\n kernels <- c(\"tr\" = trKernel, \"ep\" = epKernel, \"gauss\" = gaussKernel, \"kv\" = kvKernel)\n hs <- seq(from = 0, to = 6, by = 0.2)\n \n index <- 1\n for (kernelName in names(kernels)) {\n kernel <- kernels[[kernelName]]\n png(sprintf(\"loo-%03d.png\", index), width = 1324, height = 700, unit = \"px\", pointsize = 20)\n cat(\"Kernel:\", kernelName, index, \"of\", length(kernels), \"\\n\")\n index <- index + 1\n \n loo <- parzen_loo(iris[3:4], iris$Species, kernel, hs)\n plot(hs, loo, type=\"l\", xlab=\"h\", ylab=\"LOO\")\n points(hs[which.min(loo)], loo[which.min(loo)], pch = 19, col = \"red\")\n text(hs[which.min(loo)], loo[which.min(loo)] + 0.05, paste(\"best:\", hs[which.min(loo)]))\n \n cat(\"\\rDone. \\n\")\n dev.off()\n }\n}\n\n\n# generateLoos()\ngenerateMaps()\n\n#parzen(iris[3:4], paste(iris$Species), c(4, 1), 0.4, rectKernel)\n\n", "meta": {"hexsha": "26f508fbb2cf728f485f443766f1e2dde45a1491", "size": 3493, "ext": "r", "lang": "R", "max_stars_repo_path": "2 - Parzen window method/parzen.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2 - Parzen window method/parzen.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2 - Parzen window method/parzen.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9115044248, "max_line_length": 109, "alphanum_fraction": 0.5556827942, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.72328192276052}} {"text": "# Master Thesis Project - Extreme Value Theory\n# We assume that the stock prices follow a geometric\n# Brownian motion (Black-Scholes model). We plot the\n# empirical stock price data as well as the simulated\n# geometric Brownian motions associated to them.\n# Killian Martin--Horgassan\n# 08-06-2015\n\n# Clear the environment\nrm(list=ls())\n\n# Close all already open graphic windows\ngraphics.off()\n\n# Sourcing the auxiliary files\nsource(\"loadStockData_plain.r\")\nsource(\"firstElement.r\")\nsource(\"computeApproximateGradient.r\")\nsource(\"meanAndVariance.r\")\nsource(\"Visualisation_StockPriceVariations.r\")\n\n\n# Remark : the csv uses the metastock data format \n# 7 columns : - Ticker (identifier of the stock\n# and stockmarket on which it is listed)\n#\t\t\t\t\t - Date (yyyymmdd)\n#\t\t\t\t\t - Open\n#\t\t\t\t\t - High\n#\t\t\t\t\t - Low\n#\t\t\t\t\t - Close\n#\t\t\t\t\t - Volume\n# By default, the highest price is used i.e. column 3.\nCHOICE <- 3\n\n# Loading the original data for the LVMHH and Total\n# stocks and getting the indexes where to cut the \n# data.\ndf_plain <- loadStockData_plain(CHOICE)\nindexes <- Visualisation_StockPriceVariations()\nindex_lvmh <- indexes[1]-1\nindex_total <- indexes[2]-1\n\nS_lvmh <- df_plain[[3]]\nS_total <- df_plain[[5]]\n\nS_lvmh <- S_lvmh[1:index_lvmh]\nS_total <- S_total[1:index_total]\n\nLS_lvmh <- log(S_lvmh)\nLS_total <- log(S_total)\n\nLR_lvmh <- diff(LS_lvmh)\nLR_total <- diff(LS_total)\n\nindex_lvmh <- length(LR_lvmh)\nindex_total <- length(LR_total)\n\nm_lvmh <- mean(LR_lvmh)\ns2_lvmh <- var(LR_lvmh)\n\nm_total <- mean(LR_total)\ns2_total <- var(LR_total)\n\n# Building the Geometric Brownian motions \nB_lvmh1 <- rnorm(index_lvmh,0,1)\nB_lvmh1 <- S_lvmh[1]*exp(cumsum((m_lvmh + 0.5*s2_lvmh) + sqrt(s2_lvmh)*B_lvmh1))\n\nB_lvmh2 <- rnorm(index_lvmh,0,1)\nB_lvmh2 <- S_lvmh[1]*exp(cumsum((m_lvmh + 0.5*s2_lvmh) + sqrt(s2_lvmh)*B_lvmh2))\n\nB_lvmh3 <- rnorm(index_lvmh,0,1)\nB_lvmh3 <- S_lvmh[1]*exp(cumsum((m_lvmh + 0.5*s2_lvmh) + sqrt(s2_lvmh)*B_lvmh3))\n\nB_lvmh4 <- rnorm(index_lvmh,0,1)\nB_lvmh4 <- S_lvmh[1]*exp(cumsum((m_lvmh + 0.5*s2_lvmh) + sqrt(s2_lvmh)*B_lvmh4))\n\nB_lvmh5 <- rnorm(index_lvmh,0,1)\nB_lvmh5 <- S_lvmh[1]*exp(cumsum((m_lvmh + 0.5*s2_lvmh) + sqrt(s2_lvmh)*B_lvmh5))\n\nminima_lvmh <- min(c(B_lvmh1, B_lvmh2, B_lvmh3, B_lvmh4, B_lvmh5))\nmaxima_lvmh <- max(c(B_lvmh1, B_lvmh2, B_lvmh3, B_lvmh4, B_lvmh5))\n\nB_total1 <- rnorm(index_total,0,1)\nB_total1 <- S_total[1]*exp(cumsum((m_total + 0.5*s2_total) + sqrt(s2_total)*B_total1))\n\nB_total2 <- rnorm(index_total,0,1)\nB_total2 <- S_total[1]*exp(cumsum((m_total + 0.5*s2_total) + sqrt(s2_total)*B_total2))\n\nB_total3 <- rnorm(index_total,0,1)\nB_total3 <- S_total[1]*exp(cumsum((m_total + 0.5*s2_total) + sqrt(s2_total)*B_total3))\n\nB_total4 <- rnorm(index_total,0,1)\nB_total4 <- S_total[1]*exp(cumsum((m_total + 0.5*s2_total) + sqrt(s2_total)*B_total4))\n\nB_total5 <- rnorm(index_total,0,1)\nB_total5 <- S_total[1]*exp(cumsum((m_total + 0.5*s2_total) + sqrt(s2_total)*B_total5))\n\nminima_total <- min(c(B_total1, B_total2, B_total3, B_total4, B_total5))\nmaxima_total <- max(c(B_total1, B_total2, B_total3, B_total4, B_total5))\n\nquartz()\ndev.new(width = 7, heigth = 7)\npng(file = \"cleanedLVMH.png\")\nplot(1:index_lvmh, S_lvmh[1:index_lvmh], col = 'grey', lwd = 2,\n\ttype = 'l', main = 'LVMH Stock actual & simulated', xlab =\n 'Time steps in weeks', ylab = 'Stock prices', ylim = \n c(minima_lvmh, maxima_lvmh))\nlines(1:index_lvmh, B_lvmh1, col = 'red')\nlines(1:index_lvmh, B_lvmh2, col = 'blue')\nlines(1:index_lvmh, B_lvmh3, col = 'green')\nlines(1:index_lvmh, B_lvmh4, col = 'yellow')\nlines(1:index_lvmh, B_lvmh5, col = 'purple')\ndev.off()\ngraphics.off()\n\nquartz()\ndev.new(width = 7, heigth = 7)\npng(file = \"cleanedTotal.png\")\nplot(1:index_total, S_total[1:index_total], col = 'grey', lwd = 2,\n\ttype = 'l', main = 'Total Stock actual & simulated', xlab =\n 'Time steps in weeks', ylab = 'Stock prices', ylim = \n c(minima_total, maxima_total))\nlines(1:index_total, B_total1, col = 'red')\nlines(1:index_total, B_total2, col = 'blue')\nlines(1:index_total, B_total3, col = 'green')\nlines(1:index_total, B_total4, col = 'yellow')\nlines(1:index_total, B_total5, col = 'purple')\ndev.off()\ngraphics.off()\n\nB_totalBeta1 <- rnorm(6*index_total,0,1/sqrt(6))\nB_totalBeta1 <- S_total[1]*exp(cumsum((m_total + 0.5*s2_total) + sqrt(s2_total)*B_totalBeta1))\n\nB_totalBeta2 <- rnorm(6*index_total,0,1/sqrt(6))\nB_totalBeta2 <- S_total[1]*exp(cumsum((m_total + 0.5*s2_total) + sqrt(s2_total)*B_totalBeta2))\n\nminima_total_Beta <- min(c(B_totalBeta1, B_totalBeta2))\nmaxima_total_Beta <- max(c(B_totalBeta1, B_totalBeta2))\n\n\nquartz()\ndev.new(width = 7, heigth = 7)\npng(file = \"cleanedTotal_better_simulation.png\")\nplot(1:index_total, S_total[1:index_total], col = 'grey', lwd = 2,\n\ttype = 'l', main = 'Total Stock actual [weekly increment] & \\n simulated [daily increment]', xlab =\n 'Time steps in weeks', ylab = 'Stock prices')#, ylim = \n #c(minima_total_Beta, maxima_total_Beta))\nlines(1:(6*index_total), B_totalBeta1, col = 'purple')\nlines(1:(6*index_total), B_totalBeta2, col = 'blue')\n\ndev.off()\ngraphics.off()\n\n\nB_lvmhBeta1 <- rnorm(6*index_lvmh,0,1/sqrt(6))\nB_lvmhBeta1 <- S_lvmh[1]*exp(cumsum((m_lvmh + 0.5*s2_lvmh) + sqrt(s2_lvmh)*B_lvmhBeta1))\n\nB_lvmhBeta2 <- rnorm(6*index_lvmh,0,1/sqrt(6))\nB_lvmhBeta2 <- S_lvmh[1]*exp(cumsum((m_lvmh + 0.5*s2_lvmh) + sqrt(s2_lvmh)*B_lvmhBeta2))\n\nminima_lvmh_Beta <- min(c(B_lvmhBeta1, B_lvmhBeta2))\nmaxima_lvmh_Beta <- max(c(B_lvmhBeta1, B_lvmhBeta2))\n\nquartz()\ndev.new(width = 7, heigth = 7)\npng(file = \"cleanedLVMH_better_simulation.png\")\nplot(1:index_lvmh, S_lvmh[1:index_lvmh], col = 'grey', lwd = 2,\n\ttype = 'l', main = 'LVMH Stock actual [weekly increment] & \\n simulated [daily increment]', xlab =\n 'Time steps in weeks', ylab = 'Stock prices')#, ylim = \n #c(minima_total_Beta, maxima_total_Beta))\nlines(1:(6*index_lvmh), B_lvmhBeta1, col = 'purple')\nlines(1:(6*index_lvmh), B_lvmhBeta2, col = 'blue')\n\ndev.off()\ngraphics.off()\n\n\n\n\n\n\n", "meta": {"hexsha": "024cc77bca3c7df54cf529c2fc6786c30f47e536", "size": 5958, "ext": "r", "lang": "R", "max_stars_repo_path": "r_files_gbm_task7/GBM_LVMH_Total.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r_files_gbm_task7/GBM_LVMH_Total.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r_files_gbm_task7/GBM_LVMH_Total.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7362637363, "max_line_length": 100, "alphanum_fraction": 0.7035918093, "num_tokens": 2209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.7231040244167634}} {"text": "## https://israeldi.github.io/bookdown/_book/monte-carlo-simulation-of-stock-portfolio-in-r-matlab-and-python.html\n\nsource('/home/dlhjel/GitHub_repos/R-setup/setup.r')\n\n##-----------------------------------------------------------------------------\n## Determine mean for each asset and covariance matrix\ndata <- '\n Date AAPL GOOG FB\n11/15/17 166.5791 1020.91 177.95\n11/16/17 168.5693 1032.50 179.59\n11/17/17 167.6333 1019.09 179.00\n11/20/17 167.4658 1018.38 178.74\n11/21/17 170.5791 1034.49 181.86\n11/22/17 172.3721 1035.96 180.87\n11/24/17 172.3820 1040.61 182.78\n11/27/17 171.5150 1054.21 183.03\n11/28/17 170.5101 1047.41 182.42\n11/29/17 166.9732 1021.66 175.13\n'\nhistory <- as_tibble(readall(data))\nhistory$Date <- as.Date(history$Date, \"%m/%d/%Y\")\nincrement <- (max(history$Date) - min(history$Date)) / nrow(history)\n# alternately, I could grab the most common increment\n# increment <- mode(diff(history$Date))\nprice <- history[2:ncol(history)]\n\n# This function returns the first differences of a t x q df of data\nreturns = function(df){\n rows <- nrow(df)\n return <- df[2:rows, ] / df[1:rows-1, ] - 1\n}\n\n# Get the asset returns\nreturn <- returns(price)\n\n## calculate mean return for each asset\nmeans = colMeans(return)\n\n## Get the Variance Covariance Matrix of Stock Returns\npairs(return)\ncoVarMat = cov(return)\nprint(coVarMat)\n\n## Lower Triangular Matrix from Choleski Factorization, L where L * t(L) = CoVarMat\n## needed for R_i = mean_i + L_ij * Z_ji\nL = t( chol(coVarMat) )\nprint(L)\n\n##-----------------------------------------------------------------------------\n## SET PARAMETERS FOR MONTE CARLO SIMULATIONS\n\n# Set number of Monte Carlo Simulations\nmc_rep = 1000\n# Set number of days for the simulation\nsim_days = 30\n# Set simulation start date\nsim_start <- Sys.Date()\n# Calculate simulation end date\nsim_end <- sim_start + increment * sim_days\n# Set date vector for simulation (length should be sim_days + 1)\nDate <- seq(sim_start, sim_end, increment)\n\n# Suppose we invest our money evenly among all three assets \n# We use today's Price 11/14/2018 to find the number of shares each stock \n# that we buy\nweights <- c(1/3, 1/3, 1/3)\nprint(weights)\n\n##-----------------------------------------------------------------------------\n## START MONTE CARLO SIMULATION\n\n## initialize sim_return matrix \n## row for each simulation date\n## column for each monte carlo simulation\ncum_sim_m = matrix(0, sim_days, mc_rep)\n\n## Extend means vector to a matrix\n## one row for each account (or investment column) repeated in columns for each simulation\nmeans_matrix = matrix(rep(means, sim_days), nrow = ncol(return))\n\n## set seed if want to repeat exactly\nset.seed(200)\nfor (i in 1:mc_rep) {\n ## do following for each monte carlo simulation\n\n ## obtain random z values for each account (rows) for each date increment (columns)\n Z <- matrix( rnorm( ncol(return) * sim_days ), ncol = sim_days)\n\n ## simulate returns for each increment forward in time (assumed same as whatever data was)\n sim_return <- means_matrix + L %*% Z\n ## to view as a dataframe\n ## dfsim <- as_tibble(as.data.frame(t(sim_return)))\n\n ## Calculate vector of portfolio returns\n cum_sim_i = cumprod( weights %*% sim_return + 1 )\n\n ## Add it to the monte-carlo matrix\n cum_sim_m[,i] = cum_sim_i;\n}\n# put results into dataframe\ncum_sim_df <- as_tibble(as.data.frame(cum_sim_m))\n# add row for starting value\nones <- rep(1, ncol(cum_sim_df))\ncum_sim_df <- rbind(ones, cum_sim_df)\n\n\n##-----------------------------------------------------------------------------\n## DISPLAY RESULTS\n\n# plot results\n# first establish plot area\nylim <- range(cum_sim_df)\nplot(Date, cum_sim_df$V1, type='n',\n ylab='Simulation Returns',\n ylim=ylim)\nfor (i in 2:ncol(cum_sim_df)) {\n lines(Date, t(cum_sim_df[i]), type='l')\n}\n\n# Porfolio Returns statistics at end of simulation\ncum_final <- as.numeric( cum_sim_df[nrow(cum_sim_df),] )\ncum_final_stats <- data.frame(mean = mean(cum_final),\n median = median(cum_final),\n sd = sd(cum_final))\nprint(cum_final_stats)\n\n## Construct Confidential Intervals for returns\n## first define function\nci <- function(df, conf) {\n # calculate confidence limit for specified confidence level\n # note specified conf = 1 - alpha\n # i.e., if want alpha=0.05 to get 95% conf limit, specify 0.95\n apply(df, 1, function(x) quantile(x, conf))\n}\n## create dataframe of confidence intervals\ndf <- cum_sim_df\ncis <- as_tibble( data.frame(Date,\n conf_99.9_upper_percent = ci(df, 0.999),\n conf_99.0_upper_percent = ci(df, 0.99),\n conf_95.0_upper_percent = ci(df, 0.95),\n conf_50.0_percent = ci(df, 0.5),\n conf_95.0_lower_percent = ci(df, 0.05),\n conf_99.0_lower_percent = ci(df, 0.01),\n conf_99.9_lower_percent = ci(df, 0.001)) )\n\n## plot confidence intervals on simulation\nlines(cis$Date, cis$conf_99.9_upper_percent, lwd=4, lty=2, col='red')\nlines(cis$Date, cis$conf_50.0_percent , lwd=4, col='red')\nlines(cis$Date, cis$conf_99.9_lower_percent, lwd=4, lty=2, col='red')\n", "meta": {"hexsha": "4db690137b2f3d28fc8846b627eb1b4f6f6c7380", "size": 5393, "ext": "r", "lang": "R", "max_stars_repo_path": "portfolio_return_v01.r", "max_stars_repo_name": "dhjelmar/Retirement", "max_stars_repo_head_hexsha": "2f844025e72d89c241aac5a6bd14780c48bb8dbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "portfolio_return_v01.r", "max_issues_repo_name": "dhjelmar/Retirement", "max_issues_repo_head_hexsha": "2f844025e72d89c241aac5a6bd14780c48bb8dbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "portfolio_return_v01.r", "max_forks_repo_name": "dhjelmar/Retirement", "max_forks_repo_head_hexsha": "2f844025e72d89c241aac5a6bd14780c48bb8dbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9533333333, "max_line_length": 114, "alphanum_fraction": 0.6202484702, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7230500322593884}} {"text": "marginOfError =\nfunction(prob, # sample probability (or response rate)\n n, # sample size\n N=NULL,\n conf.level=0.95 # Confidence interval\n ) {\n z <- qnorm(p=1.0 - (1.0 - conf.level) * 0.5)\n B <- prob * (1 - prob)\n moe <- z * sqrt(B / n)\n\n if (!is.null(N)) {\n # tmp <- z ^ 2 * (prob * (1 - prob)) / moe^2\n # n <- tmp / (1 + tmp / N)\n # n + n/N * tmp <- tmp\n # n <- tmp * (1 - n/N)\n fpcf <- sqrt((N - n) / (N - 1))\n moe <- moe * fpcf\n }\n return(moe)\n}\n\nsampleSize =\nfunction(prob,\n moe, # Margin of error\n N=NULL, # Population size\n conf.level=0.95\n ) {\n z <- qnorm(p=1.0 - (1.0 - conf.level) * 0.5)\n B <- prob * (1 - prob)\n n <- z ^ 2 * B / moe^2\n if (!is.null(N)) {\n n <- n * N / (n + N - 1)\n }\n return(n)\n}\n\n\nbinom.test =\nfunction() {\n prob <- 0.15\n moe <- 0.025\n N <- 1000\n n <- sampleSize(prob=prob, moe=moe, N=N)\n message(n)\n message(\"Expected margin of error: \", moe)\n moe <- marginOfError(prob=prob, n=n, N=N)\n message(moe)\n}\n", "meta": {"hexsha": "321537ccc6223db43130c9efb38c74090065cc9d", "size": 1110, "ext": "r", "lang": "R", "max_stars_repo_path": "stats/binomial.r", "max_stars_repo_name": "daigotanaka/r-utils", "max_stars_repo_head_hexsha": "787b08973cd4e2d8c6f9de36baa994102cdda65b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-09-27T08:18:45.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-27T08:18:45.000Z", "max_issues_repo_path": "stats/binomial.r", "max_issues_repo_name": "daigotanaka/r-utils", "max_issues_repo_head_hexsha": "787b08973cd4e2d8c6f9de36baa994102cdda65b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stats/binomial.r", "max_forks_repo_name": "daigotanaka/r-utils", "max_forks_repo_head_hexsha": "787b08973cd4e2d8c6f9de36baa994102cdda65b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6530612245, "max_line_length": 55, "alphanum_fraction": 0.4486486486, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7228687868848599}} {"text": "next.perm <- function(p) {\n\tn <- length(p)\n\ti <- n - 1\n\tr = TRUE\n\tfor(i in (n-1):1) {\n\t\tif(p[i] < p[i+1]) {\n\t\t\tr = FALSE\n\t\t\tbreak\n\t\t}\n\t}\n\t\n\tj <- i + 1\n\tk <- n\n\twhile(j < k) {\n\t\tx <- p[j]\n\t\tp[j] <- p[k]\n\t\tp[k] <- x\n\t\tj <- j + 1\n\t\tk <- k - 1\n\t}\n\t\n\tif(r) return(NULL)\n\t\n\tj <- n\n\twhile(p[j] > p[i]) j <- j - 1\n\tj <- j + 1\n\t\n\tx <- p[i]\n\tp[i] <- p[j]\n\tp[j] <- x\n\treturn(p)\n}\n\nprint.perms <- function(n) {\n\tp <- 1:n\n\twhile(!is.null(p)) {\n\t\tcat(p,\"\\n\")\n\t\tp <- next.perm(p)\n\t}\n}\n\nprint.perms(3)\n# 1 2 3\n# 1 3 2\n# 2 1 3\n# 2 3 1\n# 3 1 2\n# 3 2 1\n", "meta": {"hexsha": "52b6245e000912d2e2707e132047ea4ba6ee55cc", "size": 534, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Permutations/R/permutations.r", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Task/Permutations/R/permutations.r", "max_issues_repo_name": "djgoku/RosettaCodeData", "max_issues_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Permutations/R/permutations.r", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10.8979591837, "max_line_length": 30, "alphanum_fraction": 0.3988764045, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7227679498447923}} {"text": "#' @title plot3AgeComparisons\n#' @description plot triplets of age readings on a hexagon to compare 3 age readers or to compare 3 aging methods\n#' @family abysmally documented\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\nplot3AgeComparisons = function(triplets,color=\"grey60\",offset=.20){\n\n# triplets is a matrix with number of rows equal to number of fish aged, and 3 columns.\n# Each column contains the age readings obtained from one reader (or one aging method).\n# The object is to compare the columns to see how the readers may differ.\n\n# color sets the darkness of the grid of reference points. What you see on the screen may differ from\n# what your printer gives you.\n\n# offset determines how close to the reference point the number of observations is printed. \n\n# makes use of the function regpolygon()\n\n# This function will implement the graphing procedure described by Evans, \n# G.T. and J.M. Hoenig. 1998. Viewing and Testing Symmetry in Contingency \n# Tables, with Application to Fish Ages. Biometrics 54:620-629.\n\n# Programmed by J. Hoenig, Virginia Institute of Marine Science, hoenig@vims.edu\n\n# First, test if the matrix triplets is numeric.\n\n if(!is.numeric(triplets)) {return(\"matrix is not numeric\")}\n\n# determine if there are NAs and, if so, eliminate them and alert the user.\n\ntest = complete.cases(triplets)\nwarn = sum(!test)\nif (warn > 0) cat(\"warning: there are \",warn,\" records with missing values\")\ntriplets = triplets[test,]\n\n# now, subtract the lowest value in each row of triplets from each entry in the row\n\nrowmins = apply(triplets,1,min)\ntriplets = triplets - rowmins\nmaxdif = max(triplets)\n\n\n# draw a regular hexagon\n\n hexagon = regpolygon(lenside=maxdif)\n xvalues = hexagon$x\n yvalues = hexagon$y\n\n par(fin=c(5,5.62))\n\n plot(xvalues,yvalues,ylab=\"\",xlab=\"\",type=\"l\",xlim=c(-maxdif,maxdif),\n ylim=c(-maxdif,maxdif),xaxt=\"n\",yaxt=\"n\")\n\n# now add radii\n for (i in 1:6) {\n lines(x=c(0,xvalues[i]),y=c(0,yvalues[i]))\n }\n\n# now add a grid of plotting nodes\nx = matrix(NA,nrow=2*maxdif+1,ncol=2*maxdif+1)\ny = matrix(NA,nrow=2*maxdif+1,ncol=2*maxdif+1)\n\nfor (i in 1:(2*maxdif+1)){\n for (j in 1:(maxdif+1)) {\n x[i,j] = i-maxdif-1-(j-1)*cos(pi/3)\n y[i,j] = (j-1)*sin(pi/3)\n }\n}\n\nfor (i in 1:maxdif){\n for (j in (i+1):(maxdif+1)) {\n x[i,j] = NA\n y[i,j] = NA\n }\n}\n\nfor (i in 1:(2*maxdif+1)){\n for (j in 1:(maxdif+1)) {\n points(x[i,j],y[i,j],pch=20,col=color)\n points(x[i,j],-y[i,j],pch=20,col=color)\n }\n}\n\n# now count how many observations there are at each plotting point\n\nnumcells = (maxdif + 1)^3\ncount = rep(NA,numcells)\ndim(count) = c((maxdif+1),(maxdif+1),(maxdif+1))\nxcoord = rep(NA,numcells)\ndim(xcoord) = c((maxdif+1),(maxdif+1),(maxdif+1))\nycoord = rep(NA,numcells)\ndim(ycoord) = c((maxdif+1),(maxdif+1),(maxdif+1))\n\nfor (i in 1:dim(triplets)[1]) {\n if (is.na(count[(triplets[i,1]+1),(triplets[i,2]+1),(triplets[i,3]+1)])) {\n count[(triplets[i,1]+1),(triplets[i,2]+1),(triplets[i,3]+1)] = 0 }\n count[(triplets[i,1]+1),(triplets[i,2]+1),(triplets[i,3]+1)] = \n count[(triplets[i,1]+1),(triplets[i,2]+1),(triplets[i,3]+1)] + 1\n}\nfor (i in 1:(maxdif+1)) {\n for (j in 1:(maxdif+1)) {\n for (k in 1:(maxdif+1)) {\n # compute the x & y coordinates for the plotting location\n xcoord[i,j,k] = i - j*cos(pi/3) - k*cos(pi/3)\n ycoord[i,j,k] = j*sin(pi/3) - k*sin(pi/3)\n }\n }\n}\n\n# now plot the data\n\nfor (i in 1:(maxdif+1)){\n for (j in 1:(maxdif+1)){\n for (k in 1:(maxdif+1)){\n if(!is.na(count[i,j,k])) points((xcoord[i,j,k]+offset),ycoord[i,j,k],pch=as.character(count[i,j,k]))\n }\n }\n}\n\ntext(4.06,.45,\"A\")\ntext(-2.3,3.8,\"B\")\ntext(-2.3,-3.8,\"c\")\n\n return(list(triplets=triplets,x=x,y=y,count=count,xcoord=xcoord,ycoord=ycoord))\n\n}\n\n##################################################################\n\n# regpolygon: compute (x,y) pairs that define the locations of the vertices of a regular polygon\n# CJG, Aug. 7, 1995 modified by JM Hoenig June 2007 to run in R\n\nregpolygon <- function(n=6,lenside=1,startang=0){\n\n # n : the number of sides\n # lenside : the length of each vertex to the center of the regular polygon\n # startang : the angle (degrees) of the first point on the polygon \n # w.r.t. the x-axis\n\n startang <- startang*(pi/180) # convert to radians\n \n vertices <- seq(startang, startang+(2*pi), length=(n+1) )\n x <- cos(vertices)\n y <- sin(vertices)\n\n x <- x*lenside\n y <- y*lenside\n\n return(list(x=x,y=y))\n\n}\n", "meta": {"hexsha": "ce4c725a92f726d98670e645fda2fa5f0a9fa228", "size": 4493, "ext": "r", "lang": "R", "max_stars_repo_path": "R/plot3AgeComparisons.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/plot3AgeComparisons.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/plot3AgeComparisons.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5592105263, "max_line_length": 113, "alphanum_fraction": 0.6430002226, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7226099500840332}} {"text": "## beta via MLE in R\n\n#' Title\n#'\n#' @param fmu formula object\n#' @param method character string\n#' @param data dataset\n#' @param brange vector\n#'\n#' @export\n#'\nbetamle <-function(fmu,method='BFGS', data, brange){\n\n #attach(data, warn.conflicts=FALSE)\n\n Fmu <- terms(fmu, data=data)\n X.vars <- as.character(attr(Fmu, \"variables\"))[c(-1, -2)]\n X.data <- model.matrix(fmu)\n\n Y.var <- as.character(attr(Fmu, \"variables\"))[2]\n Y.data <- model.frame(fmu)[,1]\n\n setrange <- function(z, brange) {\n t <- (z-brange[1])/(brange[2]-brange[1])\n t[which(t == 0)] <- .001\n t[which(t == 1)] <- .999\n t\n }\n\n dv <- setrange(Y.data, brange)\n nx <- ncol(X.data)\n\n neglnl<-function(theta){\n\t nu <- theta[1:nx]\n\t omega <- theta[(nx+1):(2*nx)]\n\n\t X <- X.data\n\n\n\t p1 <-exp(as.vector(X%*%nu))\n\t p2 <- exp(as.vector(X%*%omega))\n\n\t -sum(lgamma(p1 + p2) + (p1-1)*log(dv) + (p2-1)*log(1-dv) - lgamma(p1) - lgamma(p2) )\n\t }\n\n result <- optim(rep(0,2*nx), neglnl, hessian=T, method=\"BFGS\")\n\n coef<-result$par\n coef_nu <- coef[1:nx]\n coef_omega <- coef[(nx+1):(2*nx)]\n var<-solve(result$hessian)\n var_nu <- var[1:nx]\n var_omega <- var[(nx+1):(2*nx)]\n se<-sqrt(diag(var))\n se_nu <- se[1:nx]\n se_omega <- se[(nx+1):(2*nx)]\n zscore<-coef/se\n zscore_nu <- zscore[1:nx]\n zscore_omega <- zscore[(nx+1):(2*nx)]\n pvalue<-2.0*(1.0-pnorm(abs(zscore)))\n pscore_nu <- pvalue[1:nx]\n pscore_omega <- pvalue[(1+nx):(2*nx)]\n\n res <- cbind(coef_nu, se_nu, zscore_nu, pscore_nu,\n coef_omega, se_omega, zscore_omega, pscore_omega)\n\t colnames(res) <- c(\"Nu Coef.\",\"Nu SE\",\"Nu Z\",\"Nu p\", \"Omega Coef\", \"Omega SE\", \"Omega Z\", \"Omega p\")\n\t rownames(res) <- c(\"constant\",X.vars)\n\n cat(\"\\n\",paste(\"Beta MLE Model of\",Y.var),\"\\n\")\n\n\t print(round(res,2))\n if (print(result$convergence==0))\n\t cat(\"\\nLikelihood:\",-result$value,\"\\n\")\n else\n\t cat(\"\\nDid NOT converge\\n\")\n\n\t rval <- list(\"coef\"=coef,\n\t \"coef_nu\"=coef_nu,\n\t \"coef_omega\"=coef_omega,\n\t \"var\"=var,\n\t \"var_nu\"=var_nu,\n\t \"var_omega\"=var_omega,\n\t \"results\" = res,\n\t \"Likelihood\"=-result$value)\n\t rval\n }\n\n", "meta": {"hexsha": "7e3a06e635ec4d954dc5b3a629af1836d2eabbc2", "size": 2263, "ext": "r", "lang": "R", "max_stars_repo_path": "R/betamle.r", "max_stars_repo_name": "jjbrehm/BadApple", "max_stars_repo_head_hexsha": "0fe9a9742c53fdafa8788c90f905f8d2d3c7d913", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-07T19:56:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-07T19:56:28.000Z", "max_issues_repo_path": "R/betamle.r", "max_issues_repo_name": "jjbrehm/BadApple", "max_issues_repo_head_hexsha": "0fe9a9742c53fdafa8788c90f905f8d2d3c7d913", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/betamle.r", "max_forks_repo_name": "jjbrehm/BadApple", "max_forks_repo_head_hexsha": "0fe9a9742c53fdafa8788c90f905f8d2d3c7d913", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7159090909, "max_line_length": 103, "alphanum_fraction": 0.5408749448, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7225103457565043}} {"text": "library(MASS)\r\n\r\nf <- function(n) {\r\n factorial(n)\r\n}\r\n\r\ndispn <- function(n, m) {\r\n f(n)/f(n-m)\r\n}\r\n\r\nstirling <- function(n) {\r\n n*log(n) - n + (1/2)*log(2*pi*n)\r\n}\r\n\r\n\r\n# ESERCIZIO 1\r\n\r\nwhite <- 4\r\nred <- 3\r\ngreen <- 4\r\n\r\n# formule\r\n\r\npermutazioni_es1 <- f(white+red+green)/(f(white)*(f(green)*(f(red))))\r\n\r\nprint(permutazioni_es1)\r\n \r\n# ESERCIZIO 2\r\nconsonanti <- 9\r\nvocali <- 5\r\n\r\nconsonanti_parola <- 6\r\nvocali_parola <- 4\r\n\r\n# formule\r\n\r\ndisp_cons <- choose(consonanti, consonanti_parola)\r\ndisp_voca <- choose(vocali, vocali_parola)\r\npermutazioni_es2 <- f(consonanti_parola+vocali_parola)\r\nparole <- disp_cons * disp_voca * permutazioni_es2\r\nparole_log <- log(parole)\r\nprint(parole_log)\r\n\r\n# ESERCIZIO 3\r\nn_terzo <- 1548\r\nprint(stirling(n_terzo), digits=22)\r\n", "meta": {"hexsha": "c5e6083341e07347c3770114842c16dab67619be", "size": 830, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 13.r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio 13.r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio 13.r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6595744681, "max_line_length": 70, "alphanum_fraction": 0.5975903614, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7224539016486792}} {"text": "# __ _____ _ __ _ \n# <(o )___ | _ |___ ___ ___| |_ ___ ___ | | ___| |_ ___ \n# ( ._> / | __| _| -_|_ -| _| -_|_ -| | |__| .'| . |_ -|\n# `---' |__| |_| |___|___|_| |___|___| |_____|__,|___|___|\n#==============================================================================\n# Outlier Treatment\n#==============================================================================\n# Title : Outlier treatment.r\n# Description : Outlier Treatment\n# Author : Isaias V. Prestes \n# Date : 20170822\n# Version : 0.0.2\n# Usage : Run in R 3.4\n# Notes : Source r-statistics.co by Selva Prabhakaran\n# R version : 3.4\n#==============================================================================\n# install.packages('car')\n# install.packages('outliers')\n\n#==============================================================================\n# LIBRARY DEPENDENCE\n#==============================================================================\nlibrary(car)\nlibrary(outliers)\n \n#==============================================================================\n# Data\n#==============================================================================\n\n# Inject outliers into data.\ncars1 <- cars[1:30, ] # original data\ncars_outliers <- data.frame(\n\tspeed=c(19,19,20,20,20), \n\tdist=c(190, 186, 210, 220, 218)) # introduce outliers.\ncars2 <- rbind(cars1, cars_outliers) # data with outliers.\n\n# Plot of data with outliers.\npar(mfrow=c(1, 2))\nplot(cars2$speed, cars2$dist, xlim=c(0, 28), ylim=c(0, 230), \n\tmain=\"With Outliers\", xlab=\"speed\", ylab=\"dist\", pch=\"*\", col=\"red\", cex=2)\nabline(lm(dist ~ speed, data=cars2), col=\"blue\", lwd=3, lty=2)\n\n# Plot of original data without outliers. Note the change in slope (angle) of \n# best fit line.\nplot(cars1$speed, cars1$dist, xlim=c(0, 28), ylim=c(0, 230), \n\tmain=\"Outliers removed \\n A much better fit!\", xlab=\"speed\", ylab=\"dist\", \n\tpch=\"*\", col=\"red\", cex=2)\nabline(lm(dist ~ speed, data=cars1), col=\"blue\", lwd=3, lty=2)\n\n#==============================================================================\n# Detect outliers\n#==============================================================================\n\n#------------------------------------------------------------------------------\n# Univariate approach ----------------------------------------------------------\n#------------------------------------------------------------------------------\nurl <- \"http://rstatistics.net/wp-content/uploads/2015/09/ozone.csv\" \ninputData <- read.csv(url) # import data\n\noutlier_values <- boxplot.stats(inputData$pressure_height)$out # outlier values.\nboxplot(inputData$pressure_height, main=\"Pressure Height\", boxwex=0.1)\nmtext(paste(\"Outliers: \", paste(outlier_values, collapse=\", \")), cex=0.6)\n\n#------------------------------------------------------------------------------\n# Bivariate approach ----------------------------------------------------------\n#------------------------------------------------------------------------------\nozone <- read.csv(url)\n# For categorical variable\nboxplot(ozone_reading ~ Month, data=ozone, \n\tmain=\"Ozone reading across months\") # clear pattern is noticeable.\nboxplot(ozone_reading ~ Day_of_week, data=ozone, \n\tmain=\"Ozone reading for days of week\") \n\t# this may not be significant, as day of week variable is a subset of the \n\t# month var.\n\n# For continuous variable (convert to categorical if needed.)\nboxplot(ozone_reading ~ pressure_height, data=ozone, \n\tmain=\"Boxplot for Pressure height (continuos var) vs Ozone\")\nboxplot(ozone_reading ~ cut(pressure_height, \n\tpretty(inputData$pressure_height)), data=ozone, \n\tmain=\"Boxplot for Pressure height (categorial) vs Ozone\", cex.axis=0.5)\n\n#------------------------------------------------------------------------------\n# Multivariate approach -------------------------------------------------------\n#------------------------------------------------------------------------------\n\n# Cooks Distance --------------------------------------------------------------\n# https://onlinecourses.science.psu.edu/stat501/node/340\n\nmod <- lm(ozone_reading ~ ., data=ozone)\ncooksd <- cooks.distance(mod)\n\n# In general use, those observations that have a cook’s distance greater than \n# 4 times the mean may be classified as influential. This is not a hard \n# boundary.\n\n# plot cook's distance\nplot(cooksd, pch=\"*\", cex=2, main=\"Influential Obs by Cooks distance\") \nabline(h = 4*mean(cooksd, na.rm=T), col=\"red\") # add cutoff line\ntext(x=1:length(cooksd)+1, y=cooksd, \n\tlabels=ifelse(cooksd>4*mean(cooksd, na.rm=T),\n\tnames(cooksd),\"\"), col=\"red\") # add labels\n# influential row numbers\t\ninfluential <- as.numeric(names(cooksd)[(cooksd > 4*mean(cooksd, na.rm=T))]) \nhead(ozone[influential, ]) # influential observations.\n\n#==============================================================================\n# Outliers Test\n#==============================================================================\ncar::outlierTest(mod)\n\n# outliers package ------------------------------------------------------------\nset.seed(666)\ny=rnorm(100)\noutlier(y)\noutlier(y,opposite=TRUE)\ndim(y) <- c(20,5) # convert it to a matrix\noutlier(y)\noutlier(y,opposite=TRUE)\n\nset.seed(666)\nx = rnorm(10)\nscores(x) # z-scores => (x-mean)/sd\nscores(x, type=\"chisq\") # chi-sq scores => (x - mean(x))^2/var(x)\nscores(x, type=\"t\") # t scores\nscores(x, type=\"chisq\", prob=0.9) # beyond 90th %ile based on chi-sq\nscores(x, type=\"chisq\", prob=0.95) # beyond 95th %ile\nscores(x, type=\"z\", prob=0.95) # beyond 95th %ile based on z-scores\nscores(x, type=\"t\", prob=0.95) # beyond 95th %ile based on t-scores\n\n#==============================================================================\n# Treating the outliers\n#==============================================================================\n# 1. Imputation\n# 2. Capping\n# For missing values that lie outside the 1.5*IQR limits, we could cap it \n# by replacing those observations outside the lower limit with the value of \n# 5th-ile and those that lie above the upper limit, with the value of 95th \n# -ile. Below is a sample code that achieves this.\n# 3. Prediction\n\nx <- ozone$pressure_height\nqnt <- quantile(x, probs=c(.25, .75), na.rm = T)\ncaps <- quantile(x, probs=c(.05, .95), na.rm = T)\nH <- 1.5 * IQR(x, na.rm = T)\nx[x < (qnt[1] - H)] <- caps[1]\nx[x > (qnt[2] + H)] <- caps[2]\n", "meta": {"hexsha": "a0a9aeab295a2889bed648229084539d4057ccc1", "size": 6447, "ext": "r", "lang": "R", "max_stars_repo_path": "Outliers/Outlier treatment.r", "max_stars_repo_name": "isix/R", "max_stars_repo_head_hexsha": "806e2a22e5abd93dc7933d3b9e8c3368562e1eaa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Outliers/Outlier treatment.r", "max_issues_repo_name": "isix/R", "max_issues_repo_head_hexsha": "806e2a22e5abd93dc7933d3b9e8c3368562e1eaa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Outliers/Outlier treatment.r", "max_forks_repo_name": "isix/R", "max_forks_repo_head_hexsha": "806e2a22e5abd93dc7933d3b9e8c3368562e1eaa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5608108108, "max_line_length": 81, "alphanum_fraction": 0.4782069179, "num_tokens": 1563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7224509913731492}} {"text": "\nconfidenceInterval <- function(x, confidenceLevel=0.95){\nN <- length(x)\nalpha <- 1-confidenceLevel\nif (N<30)\n stat <- qt(1-alpha/2, N-1)\nelse\n stat <- qnorm(1-alpha/2)\ninterval <- stat * sd(x) / sqrt(N)\nmean_value <- mean(x)\nresult <- c(mean_value-interval, mean_value+interval)\nnames(result) <- c(\"lower\", \"upper\")\nresult\n}", "meta": {"hexsha": "9d5d18e920d0cca83007dcd5990291e8fc2b0213", "size": 327, "ext": "r", "lang": "R", "max_stars_repo_path": "project/R_resources.r", "max_stars_repo_name": "Fjellstedt/Fjellstedt", "max_stars_repo_head_hexsha": "57dc06a134bb0c654fc8886073fa0393ef368843", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/R_resources.r", "max_issues_repo_name": "Fjellstedt/Fjellstedt", "max_issues_repo_head_hexsha": "57dc06a134bb0c654fc8886073fa0393ef368843", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/R_resources.r", "max_forks_repo_name": "Fjellstedt/Fjellstedt", "max_forks_repo_head_hexsha": "57dc06a134bb0c654fc8886073fa0393ef368843", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3571428571, "max_line_length": 56, "alphanum_fraction": 0.6727828746, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7222031630032627}} {"text": "#install.packages(\"GA\")\nlibrary(GA)\n\n# Funkcja przykładowa z dokumentacji\n# f <- function(x) (x^2+x)*cos(x) # Badana funkcja\n# lbound <- -10 # Dolne ograniczenie funkcji\n# rbound <- 10 # Górne ogranicznie funkcji\n\nf <- function(x) x*sin(10*pi*x)+1\n\nfitnessF <- function(x)\n{\n f <- f(x)\n \n penalty1 <- 0\n if (x <= -1) {\n penalty1 <- -x-1\n }\n \n penalty2 <- 0\n if (x >= 2) {\n penalty2 <- x - 2\n }\n \n f + penalty1 + penalty2\n}\n\nlbound <- -1000\nrbound <- 1000\n\nfA <- function(x) -fitnessF(x) # Funkcja odwrotna do badanej, ponieważ minimalizujemy funkcję\n\n# Genetic algorithm\nGA <- ga(\n type = \"real-valued\",\n fitness = fA,\n lower = c(th = lbound), upper = rbound,\n popSize = 50, maxiter = 100000, run = 1000\n)\nsummary(GA)\nplot(GA)\n\ncurve(f, from = lbound, to = rbound, 200) # rysowanie wykresy funkcji\n#points(GA@solution, GA@fitnessValue, col = 2, pch = 19) # ozaczanie punktu na wykresie / tutaj szukanego ekstremum w zakresie\npoints(GA@solution, fitnessF(GA@solution), col = 2, pch = 19) # Musimy uzyskać wartość z funkcji wyjściowej, gdyż badamy funkcje odwrotną\n", "meta": {"hexsha": "8b2112174f65fd3630918f6215a58560a0975d55", "size": 1088, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ga/func/2d/ga_minimum_of_func_penalty.r", "max_stars_repo_name": "reyzeer/algorytmy-genetyczne", "max_stars_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ga/func/2d/ga_minimum_of_func_penalty.r", "max_issues_repo_name": "reyzeer/algorytmy-genetyczne", "max_issues_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ga/func/2d/ga_minimum_of_func_penalty.r", "max_forks_repo_name": "reyzeer/algorytmy-genetyczne", "max_forks_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.652173913, "max_line_length": 137, "alphanum_fraction": 0.6525735294, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7221854354857111}} {"text": "# independent.test.equal.var.r\r\n x <- c(21.6,20.8,17.6,20.1,20.1,21.9,20.6,19.4,21.5,26.1) \r\n y <- c(20.6,20.4,20.2,20.2,18.0,19.8,20.9,19.7,20.3,19.7,22.7)\r\n mx <- mean(x); my <- mean(y)\r\n sdx <- sd(x); sdy <- sd(y)\r\n sp <- sqrt( (9*sdx^2+10*sdy^2)/(10+11-2) )\r\n t0 <- (mx-my)/(sp*sqrt(1/10+1/11))\r\n t0\r\n 1-pt(t0, 19)\r\n lbd <- (mx-my) - qt(0.995, 19)*sp*sqrt(1/10+1/11)\r\n lbd\r\n ubd <- (mx-my) + qt(0.995, 19)*sp*sqrt(1/10+1/11)\r\n ubd\r\n\r\n", "meta": {"hexsha": "9914f07dd8a8cd65ffde8c00fbefa6b2a49c58f6", "size": 450, "ext": "r", "lang": "R", "max_stars_repo_path": "R.2019.2/advanced.R/Rcode/Chap3/indep.test.equal.var.r", "max_stars_repo_name": "tolkien/misc", "max_stars_repo_head_hexsha": "84651346a3a0053b6a2af31db26c227a34da33c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R.2019.2/advanced.R/Rcode/Chap3/indep.test.equal.var.r", "max_issues_repo_name": "tolkien/misc", "max_issues_repo_head_hexsha": "84651346a3a0053b6a2af31db26c227a34da33c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R.2019.2/advanced.R/Rcode/Chap3/indep.test.equal.var.r", "max_forks_repo_name": "tolkien/misc", "max_forks_repo_head_hexsha": "84651346a3a0053b6a2af31db26c227a34da33c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0, "max_line_length": 65, "alphanum_fraction": 0.5022222222, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7221039133290245}} {"text": "\r\nif(FALSE){\r\n\"Time series is a series of data points in which each data point is associated with a timestamp. \r\nA simple example is the price of a stock in the stock market at different points of time on a given day. \r\nAnother example is the amount of rainfall in a region at different months of the year. \r\nR language uses many functions to create, manipulate and plot the time series data. \r\nThe data for the time series is stored in an R object called time-series object. \r\nIt is also a R data object like a vector or data frame.\"\r\n\r\n#The time series object is created by using the ts() function\r\n#timeseries.object.name <- ts(data, start, end, frequency)\r\n\"data is a vector or matrix containing the values used in the time series.\r\nstart specifies the start time for the first observation in time series.\r\nend specifies the end time for the last observation in time series.\r\nfrequency specifies the number of observations per unit time.\"\r\n\r\n}\r\nfunction1 <- function(){\r\n#We create an R time series object for a period of 12 months and plot it.\r\n# Get the data points in form of a R vector.\r\nrainfall <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071)\r\n\r\n# Convert it to a time series object.\r\nrainfall.timeseries <- ts(rainfall,start = c(2012,1),frequency = 12)\r\n\r\n# Print the timeseries data.\r\nprint(rainfall.timeseries)\r\n\r\n# Give the chart file a name.\r\npng(file = \"rainfall.png\")\r\n\r\n# Plot a graph of the time series.\r\nplot(rainfall.timeseries)\r\n\r\n# Save the file.\r\ndev.off()\r\n}\r\n# function1()\r\n\r\nif(FALSE){\r\n\"The value of the frequency parameter in the ts() function decides the time intervals\r\nat which the data points are measured\"\r\n\"frequency = 12 pegs the data points for every month of a year.\r\nfrequency = 4 pegs the data points for every quarter of a year.\r\nfrequency = 6 pegs the data points for every 10 minutes of an hour.\r\nfrequency = 24*6 pegs the data points for every 10 minutes of a day.\"\r\n}\r\n\r\nfunction2 <- function(){\r\n# Get the data points in form of a R vector.\r\nrainfall1 <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071)\r\nrainfall2 <- \r\n c(655,1306.9,1323.4,1172.2,562.2,824,822.4,1265.5,799.6,1105.6,1106.7,1337.8)\r\n\r\n# Convert them to a matrix.\r\ncombined.rainfall <- matrix(c(rainfall1,rainfall2),nrow = 12)\r\n\r\n# Convert it to a time series object.\r\nrainfall.timeseries <- ts(combined.rainfall,start = c(2012,1),frequency = 12)\r\n\r\n# Print the timeseries data.\r\nprint(rainfall.timeseries)\r\n\r\n# Give the chart file a name.\r\npng(file = \"rainfall_combined.png\")\r\n\r\n# Plot a graph of the time series.\r\nplot(rainfall.timeseries, main = \"Multiple Time Series\")\r\n\r\n# Save the file.\r\ndev.off()\r\n}\r\nfunction2()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "67644a3b1f939c8ba985fe32696e30f49e0417b8", "size": 2839, "ext": "r", "lang": "R", "max_stars_repo_path": "R/analysis.r", "max_stars_repo_name": "Mobink980/R-Programming", "max_stars_repo_head_hexsha": "a09ff201995ed3c5edde53c634489b61e6bc2e61", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-05T21:26:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-05T21:26:08.000Z", "max_issues_repo_path": "R/analysis.r", "max_issues_repo_name": "Mobink980/R-Programming", "max_issues_repo_head_hexsha": "a09ff201995ed3c5edde53c634489b61e6bc2e61", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/analysis.r", "max_forks_repo_name": "Mobink980/R-Programming", "max_forks_repo_head_hexsha": "a09ff201995ed3c5edde53c634489b61e6bc2e61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4452054795, "max_line_length": 106, "alphanum_fraction": 0.6843959141, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7219955550249507}} {"text": "\n\n\nfunction medcouple(vector X):\n // X is a vector of size n\n \n // compute initial ingredients as for the naïve medcouple\n sort_decreasing(X)\n \n xm := median(X)\n xscale := 2*max(X)\n \n Zplus := [(x - xm)/xscale | x in X such that x >= xm]\n Zminus := [(x - xm)/xscale | x in X such that x <= xm]\n \n p := size(Zplus)\n q := size(Zminus)\n \n function h(i,j):\n a := Zplus[i]\n b := Zminus[j]\n \n if a == b:\n return signum(p - 1 - i - j)\n else:\n return (a + b)/(a - b)\n endif\n endfunction\n \n // begin Kth pair algorithm (Johnson & Mizoguchi)\n \n // the initial left and right boundaries, two vectors of size p\n L := [0, 0, ..., 0]\n R := [q - 1, q - 1, ..., q - 1]\n \n // number of entries to the left of the left boundary\n Ltotal := 0\n \n // number of entries to the left of the right boundary\n Rtotal := p*q\n \n // since we are indexing from zero, the medcouple index is one\n // less than its rank\n medcouple_index := floor(Rtotal/2)\n \n // iterate while the number of entries between the boundaries is\n // greater than the number of rows in the matrix\n while Rtotal - Ltotal > p:\n \n // compute row medians and their associated weights, but skip\n // any rows that are already empty\n middle_idx := [i | i in [0, 1, ..., p - 1] such that L[i] <= R[i]]\n row_medians := [h(i, floor((L[i] + R[i])/2) | i in middle_idx]\n weights := [R[i] - L[i] + 1 | i in middle_idx]\n \n WM := weighted median(row_medians, weights)\n \n // new tentative right and left boundaries\n P := greater_h(h, p, q, WM)\n Q := less_h(h, p, q, WM)\n \n Ptotal := sum(P) + size(P)\n Qtotal := sum(Q)\n \n // determine which entries to discard, or if we've found the medcouple\n if medcouple_index <= Ptotal - 1:\n R := P\n Rtotal := P\n else:\n if medcouple_index > Qtotal - 1:\n L := Q\n Ltotal := Qtotal\n else:\n // found the medcouple, rank of the weighted median equals medcouple index\n return WM\n endif\n endif\n \n endwhile\n \n // did not find the medcouple, but there are very few tentative entries remaining\n remaining := [h(i,j) | i in [0, 1, ..., p - 1],\n j in [L[i], L[i] + 1, ..., R[i]]\n such that L[i] <= R[i] ]\n \n // select the medcouple by rank amongst the remaining entries\n medcouple := select_nth(remaining, medcouple_index - Ltotal)\n \n return medcouple\n endfunction\n\n", "meta": {"hexsha": "fe3ce3261cfcfd7750abe40cc75d6b653cb73bd3", "size": 2982, "ext": "r", "lang": "R", "max_stars_repo_path": "rhaste.r", "max_stars_repo_name": "dgomez10/xanon", "max_stars_repo_head_hexsha": "540bdf0229f53652591e593cf057a0c9e04e2dc8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rhaste.r", "max_issues_repo_name": "dgomez10/xanon", "max_issues_repo_head_hexsha": "540bdf0229f53652591e593cf057a0c9e04e2dc8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rhaste.r", "max_forks_repo_name": "dgomez10/xanon", "max_forks_repo_head_hexsha": "540bdf0229f53652591e593cf057a0c9e04e2dc8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4130434783, "max_line_length": 93, "alphanum_fraction": 0.4725016767, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7219103217921019}} {"text": "#!/usr/bin/Rscript \n\n# Author : Bhishan Poudel \n# Date : Feb 9, 2016\n# Program: \n\n# Set the working directory \nthis.dir <- dirname(parent.frame(2)$ofile) \nsetwd(this.dir) \n\n# Start device driver to save output\n#postscript(file= \"Pareto_shape_parameter.eps\", height = 14, width = 8)\n\n# Estimates of Pareto shape parameter (power-law slope)\nnpts <- 100\nalpha.MLE <- function(x) 1 / mean(log(x))\nalpha.MVUE <- function(x) (1-(2/npts)) / mean(log(x))\nalpha.mom <- function(x) 1 / (1-1/mean(x))\nalpha.LS.EDF <- function(x) {\n lsd <- log(sort(x)) ; lseq <- log((npts:1) / npts)\n tmp <- lm(lseq~lsd)\n # plot(lsd, lseq) ; abline(tmp,col=2)\n -tmp$coef[2] }\nalpha.LS.hist <- function(x) {\n hx <- hist(x, nclass=20, plot=F)\n counts <- hx$counts\n ldens <- log(hx$density[counts>0])\n lmidpts <- log(hx$mids[counts>0])\n tmp1 <- lm(ldens~lmidpts)\n # plot(lmidpts, ldens) ; abline(tmp1, col=2)\n alpha.LS.hist <- -1 - as.numeric(tmp1$coef[2])\n return(alpha.LS.hist) }\nalpha.LS.hist.wt <- function(x) {\n hx <- hist(x, nclass=20, plot=F)\n counts <- hx$counts\n ldens <- log(hx$density[counts>0])\n lmidpts <- log(hx$mids[counts>0])\n tmp2 <- lm(ldens~lmidpts, weights=counts[counts>0])\n alpha.LS.hist.wt <- -1 - as.numeric(tmp2$coef[2])\n return(alpha.LS.hist.wt) }\nsix_alphas <- function(x) {\n out <- c(alpha.MLE(x), alpha.MVUE(x), alpha.mom(x),\n alpha.LS.EDF(x), alpha.LS.hist(x), alpha.LS.hist.wt(x))\n return(out) }\n\n# Turn off device driver \n#dev.off() \n\n\n", "meta": {"hexsha": "891c083ff30070bd05d8f9c55c0094f2d45f3871", "size": 1516, "ext": "r", "lang": "R", "max_stars_repo_path": "AstroSeminar2019Spring/ModernStatistics_R/chap4/Pareto_distribution_estimators/Pareto_shape_parameter.r", "max_stars_repo_name": "bhishanpdl/AstroSeminar_OU", "max_stars_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AstroSeminar2019Spring/ModernStatistics_R/chap4/Pareto_distribution_estimators/Pareto_shape_parameter.r", "max_issues_repo_name": "bhishanpdl/AstroSeminar_OU", "max_issues_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AstroSeminar2019Spring/ModernStatistics_R/chap4/Pareto_distribution_estimators/Pareto_shape_parameter.r", "max_forks_repo_name": "bhishanpdl/AstroSeminar_OU", "max_forks_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.32, "max_line_length": 71, "alphanum_fraction": 0.6147757256, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7218888512132486}} {"text": "=begin\n # sample-lagrange-multiplier01.rb\n\n require 'algebra'\r\n P = MPolynomial(Rational)\r\n t, x, y, z = P.vars('txyz')\r\n f = x**3+2*x*y*z - z**2\r\n g = x**2 + y**2 + z**2 - 1\r\n \r\n fx = f.derivate(x)\r\n fy = f.derivate(y)\r\n fz = f.derivate(z)\r\n \r\n gx = g.derivate(x)\r\n gy = g.derivate(y)\r\n gz = g.derivate(z)\r\n \r\n F = [fx - t * gx, fy - t * gy, fz - t * gz, g]\r\n \r\n Groebner.basis(F).each do |h|\r\n p h.factorize\r\n end\r\n \r\n #(1/7670)(7670t - 11505x - 11505yz - 335232z^6 + 477321z^4 - 134419z^2)\r\n #x^2 + y^2 + z^2 - 1\r\n #(1/3835)(3835xy - 19584z^5 + 25987z^3 - 6403z)\r\n #(1/3835)(3835x + 3835yz - 1152z^4 - 1404z^2 + 2556)(z)\r\n #(1/3835)(3835y^3 + 3835yz^2 - 3835y - 9216z^5 + 11778z^3 - 2562z)\r\n #(1/3835)(3835y^2 - 6912z^4 + 10751z^2 - 3839)(z)\r\n #(1/118)(118y - 1152z^3 + 453z)(z)(z - 1)(z + 1)\r\n #(1/1152)(z)(z - 1)(3z - 2)(3z + 2)(z + 1)(128z^2 - 11)\r\n \r\n \r\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "1154bf659e899f7ed108b58d507d0fcbfbb00e0b", "size": 916, "ext": "rd", "lang": "R", "max_stars_repo_path": "work/consider/algebra-0.72/doc/sample-lagrange-multiplier01.rb.v.rd", "max_stars_repo_name": "rubyworks/stick", "max_stars_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-04-24T05:51:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-24T05:51:21.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-lagrange-multiplier01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "work/consider/algebra-0.72/doc/sample-lagrange-multiplier01.rb.v.rd", "max_forks_repo_name": "rubyworks/stick", "max_forks_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4444444444, "max_line_length": 74, "alphanum_fraction": 0.5087336245, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7215835938152827}} {"text": "# Cyclical mean\n# 'Cyclical mean'\n\n#' Cyclical mean\n#'\n#' Calculate the mean of a set of cyclical values, e.g. calendar months, day of year, angles. The code transform the cycle to cartesian vectors, calculates summed vector, and get the cycle of the sum vector.\n#' \n#' @param x vector of cyclical values\n#' @param steps number of steps in the cycle\n#' \n#' @return collapsed string\n#' @export\ncyclicalMean = function(x, steps=360){\n radial_frac = 2*pi/steps\n x_angle = radial_frac * x\n vec_x = cos(x_angle)\n vec_y = sin(x_angle)\n vec_x_mean = mean(vec_x)\n vec_y_mean = mean(vec_y)\n a_mean = atan2(vec_y_mean, vec_x_mean)\n x_mean = steps * a_mean / (2 * pi)\n x_mean = ifelse(x_mean < 0, steps+x_mean, x_mean)\n x_mean\n}\n\n", "meta": {"hexsha": "428acab4d23750692315893d37b0231e744413b7", "size": 729, "ext": "r", "lang": "R", "max_stars_repo_path": "R/cyclicalMean.r", "max_stars_repo_name": "kraaijenbrink/pkrf", "max_stars_repo_head_hexsha": "464db030db837f2e47c45a53235c37821290d79a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/cyclicalMean.r", "max_issues_repo_name": "kraaijenbrink/pkrf", "max_issues_repo_head_hexsha": "464db030db837f2e47c45a53235c37821290d79a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/cyclicalMean.r", "max_forks_repo_name": "kraaijenbrink/pkrf", "max_forks_repo_head_hexsha": "464db030db837f2e47c45a53235c37821290d79a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-03T16:13:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-03T16:13:24.000Z", "avg_line_length": 28.0384615385, "max_line_length": 207, "alphanum_fraction": 0.7037037037, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.966914017797636, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.7214522515868459}} {"text": "###################################\n### Part 3: Plotting Data ###\n###################################\n##\n#\n\n# We are going to work with one of R's built-in data sets called 'iris'.\n# First, let's find out more about the data:\n\n#######################\n# Complete Exercise 4 #\n#######################\n\n\n# Let's analyze just the petal widths of the versicolor species in 'iris'.\n\n# We can create a new data frame by extracting a subet of all versicolor records,...\nversicolor <- iris[iris$Species == 'versicolor',]\nversicolor\n\n# ...then create a numeric vector of versicolor petal widths, or...\nversicolor_pw <- versicolor$Petal.Width\nversicolor_pw\n\n# ...do the same thing all in one line\nversicolor_pw <- iris[iris$Species == 'versicolor', 'Petal.Width']\nversicolor_pw\n\n# As with most programming languages, there is usually more than one way to do things in R.\n# Keep this in mind as you are learning the language.\n\n### Calculating simple statistics ###\n\n# Before we create any plots, let's get some simple statistics on the pedal widths of versicolor:\n \nmean(versicolor_pw)\nmedian(versicolor_pw)\nvar(versicolor_pw)\nsd(versicolor_pw)\n\n# We can also look at the correlation between versicolor's petal width and it's petal length.\n# First let's create a vector for versicolor's petal lengths.\nversicolor_pl <- iris[iris$Species == 'versicolor', 'Petal.Length']\nversicolor_pl\n\n# By default, cor() uses the Pearson method. Values range from -1 to 1. Does petal width have\n# a correlation with petal length?\ncor(versicolor_pw,versicolor_pl)\n\n\n### Plotting Data ###\n\n## Scatterplot ##\n\n# Let's plot the versicolor petal lengths and widths\n plot(versicolor_pw,versicolor_pl)\n \n # Add a regression line\n abline(lm(versicolor_pl~versicolor_pw))\n \n # Change the title\n title(\"Versicolor Petal Width vs Length\")\n\n\n# What happens if we plot the whole 'iris' data set?\nplot(iris)\n\n# Calling plot() on the whole data set makes a scatterplot matrix that plots every variable\n# against every other variable. What if we just want to look at one of these scatterplots?\nplot(iris$Petal.Length, iris$Petal.Width)\n\n## Boxplot ##\n\n# Boxplot of petal length by species \nboxplot(Petal.Length~Species, data = iris, main=\"Petal Length by Iris Species\",\n ylab=\"Length (cm)\")\n\n## Dot Plot ##\n\n# Take a random sample of size 40 from the iris dataset, sampling without replacement\niris_ran_subset <- iris[sample(1:nrow(iris), 40, replace=FALSE),]\n\n# Sort the rows so that all of the same species are together\niris_ran_subset_sorted <- iris_ran_subset[order(iris_ran_subset$Species),]\n\n# Create a new column, 'Color'\niris_ran_subset_sorted$Color=\"black\"\n\n# Set Color values by Species\niris_ran_subset_sorted$Color[iris_ran_subset_sorted$Species == \"virginica\"] = \"red\"\niris_ran_subset_sorted$Color[iris_ran_subset_sorted$Species == \"versicolor\"] = \"blue\"\niris_ran_subset_sorted$Color[iris_ran_subset_sorted$Species == \"setosa\"] = \"black\"\n\n# Plot the data\ndotchart(iris_ran_subset_sorted$Sepal.Width,labels=iris_ran_subset_sorted$Species,cex=.9,\n main=\"Comparison of Sepal Width by Iris Species\", \n xlab=\"Sepal Width (cm)\", col=iris_ran_subset_sorted$Color)\n\n## Histogram ##\n\n# We can also make a histogram that describes the distribution of sepal length values:\nhist(iris$Sepal.Length)\n\n# Let's give the histogram more detail by increasing the number of bins. This is done with\n# the 'breaks' argument:\n\nhist(iris$Sepal.Length, breaks = 15)\n\n# Hmm...the x axis is a little off. Let's adjust it with the 'xlim' argument:\n \nhist(iris$Sepal.Length, breaks = 25, xlim = c(4, 8))\n\n\n#######################\n# Complete Exercise 5 #\n#######################\n\n\n# On a side note...remember when we introduced lists earlier? A common use of lists is to\n# gather different types of R objects in one container. Many functions, including hist(),\n# return a list of different values. Each attribute of the returned histogram correlates\n# to a specific component of the list. For example, if we assign the output of\n# hist(iris$Sepal.Length) to a variable, we can capture the returned list:\n \nsepal_hist <- hist(iris$Sepal.Length)\nsepal_hist\n\n# There are many other built-in data sets in R. To see a list...\n\ndata()\n", "meta": {"hexsha": "acb7729dc5d3afbf923cb9a7debfc73ac67934ec", "size": 4200, "ext": "r", "lang": "R", "max_stars_repo_path": "Workshop_Files/Part_3-Plotting_Data.r", "max_stars_repo_name": "carsonicator/R_Refresher_July_2018", "max_stars_repo_head_hexsha": "eb5268b7527454f774163dda52ce1da9f4875d22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-17T14:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-17T14:04:14.000Z", "max_issues_repo_path": "Workshop_Files/Part_3-Plotting_Data.r", "max_issues_repo_name": "carsonicator/R_Refresher_July_2018", "max_issues_repo_head_hexsha": "eb5268b7527454f774163dda52ce1da9f4875d22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Workshop_Files/Part_3-Plotting_Data.r", "max_forks_repo_name": "carsonicator/R_Refresher_July_2018", "max_forks_repo_head_hexsha": "eb5268b7527454f774163dda52ce1da9f4875d22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-17T14:24:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-17T14:24:20.000Z", "avg_line_length": 32.0610687023, "max_line_length": 97, "alphanum_fraction": 0.7164285714, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7213494861851147}} {"text": "#number of trials\r\nn<-5\r\n# the probability of success when one person is selected from the population is\r\nz<-0.9\r\n# probability that all five heads of the households are employed\r\ny<-5\r\nprobability_forall5employed<-(factorial(n))/(factorial(y)*factorial(n-y))*(z^y)*(1-z)^(n-y)\r\nprint(probability_forall5employed)", "meta": {"hexsha": "e8d64c1fa3afc7acce6776f3370abdcfdab55455", "size": 315, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.8/Ex4_8.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.8/Ex4_8.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.8/Ex4_8.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 39.375, "max_line_length": 92, "alphanum_fraction": 0.746031746, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632316144273, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.7213165887273572}} {"text": "#Copyright (c) 2016 Riccardo Francescato\na <- c(16.85,16.40,17.21,16.35,16.52,17.04,16.96,17.15,16.59,16.57)\nb <- c(16.62,16.75,17.37,17.12,16.98,16.87,17.34,17.02,17.08,17.27)\n#confidency level\nalpha = .05 \n#type of test: 0 left tail 1 double tail 2 right tail\ntype = 2\n#calculations....\nn0 = length(a)\t\t# number of reps for sample 0\nn1 = length(b)\t\t# number of reps for sample 1\nxbar0 = mean(a)\t\t# sample 0 mean \nxbar1 = mean(b)\t\t# sample 1 mean \ns0 = sd(a)\t\t\t# sample 0 standard deviation \ns1 = sd(b)\t\t\t# sample 1 standard deviation \nf = (s0^2)/(s1^2)\nif(type == 0){\n\tfc = qf(alpha,df1=n0-1,df2=n1-1,lower.tail=F)\n\tcat(\"Results of lower tail\\n\")\n\tcat(\"First sample\\n\")\n\tcat(paste(\"# of elements: \", n0, \" Mean: \", xbar0, \" St Dev: \",s0))\n\tcat(\"\\nSecond sample\\n\")\n\tcat(paste(\"# of elements: \", n1, \" Mean: \", xbar1, \" St Dev: \",s1))\n\tcat(paste(\"\\nf: \",f))\n\tcat(paste(\"\\nfalpha: \",fc))\n\tif(f>fc) cat(\"\\nREJECT H0\\n\") else cat(\"\\nACCEPT H0\\n\")\n}else if(type == 1){\n\tfct = qf(alpha/2,df1=n0-1,df2=n1-1,lower.tail=F)\n\tfcb = qf(1-alpha/2,df1=n0-1,df2=n1-1,lower.tail=F)\n\tcat(\"Results of 2-tail tail\\n\")\n\tcat(\"First sample\\n\")\n\tcat(paste(\"# of elements: \", n0, \" Mean: \", xbar0, \" St Dev: \",s0))\n\tcat(\"\\nSecond sample\\n\")\n\tcat(paste(\"# of elements: \", n1, \" Mean: \", xbar1, \" St Dev: \",s1))\n\tcat(paste(\"\\nf0: \",f))\n\tcat(paste(\"\\nfalpha +: \",fct))\n\tcat(paste(\"\\nfalpha -: \",fcb))\n\tif(ffct) cat(\"\\nREJECT H0\\n\") else cat(\"\\nACCEPT H0\\n\")\n\n}else if(type == 2){\n\tfc = qf(alpha,df1=n0-1,df2=n1-1,lower.tail=F)\n\tcat(\"Results of lower tail\\n\")\n\tcat(\"First sample\\n\")\n\tcat(paste(\"# of elements: \", n0, \" Mean: \", xbar0, \" St Dev: \",s0))\n\tcat(\"\\nSecond sample\\n\")\n\tcat(paste(\"# of elements: \", n1, \" Mean: \", xbar1, \" St Dev: \",s1))\n\tcat(paste(\"\\nf: \",f))\n\tcat(paste(\"\\nfalpha: \",fc))\n\tif(f>fc) cat(\"\\nREJECT H0\\n\") else cat(\"\\nACCEPT H0\\n\")\n}\n", "meta": {"hexsha": "0a22087f2eca01561189cb3837ac34f6ca75b604", "size": 1842, "ext": "r", "lang": "R", "max_stars_repo_path": "Test_of_hp_2_series_VARIANCE.r", "max_stars_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_stars_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Test_of_hp_2_series_VARIANCE.r", "max_issues_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_issues_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test_of_hp_2_series_VARIANCE.r", "max_forks_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_forks_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.84, "max_line_length": 68, "alphanum_fraction": 0.605320304, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7213084562368933}} {"text": "## Set up and plot hypothetical paths of GDP per capita\n\n## Set up scenarios\n# Each scenario has ID, alpha, sI, gL, gA, delta, KY0, A0\nscenario <- c('A','B','C','D','E')\nalpha <- c(.3,.3,.3,.3,.3)\nsI <- c(.2,.2,.2,.1,.4)\ngL <- c(.01,.01,.01,.01,.01)\ngA <- c(.02,.02,.02,.02,.02)\ndelta <- c(.05,.05,.05,.05,.05)\nKY0 <- c(2.5,1.5,4,2.5,2.5)\nA0 <- c(10,10,10,10,10)\nlabel <- c('C','B','D','E','A') # allows different label for test purposes\n\n# Year vector gives total periods to run over\nyear <- c(0:40)\ns <- 0 # initializes Solow vector\n\n# Merge year and scenario data to create scenario/year dataframe\nall_scenario <- data.frame(scenario,alpha,sI,gL,gA,delta,KY0,A0) # combine scenario parameters\nyear_scenario <- expand.grid(year,scenario) # create year/scenario combinations\nnames(year_scenario) <- c(\"year\",\"scenario\")\ns <- merge(year_scenario,all_scenario,by=\"scenario\") # add parameters to year/scenario combos\n\n# Make calculations of various values using theory\ns$conv <- 1 - (1-s$alpha)*(s$delta + s$gA + s$gL) # convergence factor\ns$kystar <- s$sI/(s$gL+s$gA+s$delta) # steady state capital/output ratio\ns$ky <- s$KY0*(s$conv^s$year) + (s$kystar)*(1-(s$conv)^s$year) # actual KY ratio\ns$kylag <- s$KY0*(s$conv^(s$year-1)) + (s$kystar)*(1-(s$conv)^(s$year-1)) # actual KY ratio\ns$lny <- (s$alpha/(1-s$alpha))*log(s$ky) + log(s$A0) + s$gA*s$year # actual log GDP p.c.\ns$lnystar <-(s$alpha/(1-s$alpha))*log(s$kystar) + log(s$A0) + s$gA*s$year # BGP log GDP p.c.\ns$gky <- log(s$ky) - log(s$kylag)\ns$gy <- (s$alpha/(1-s$alpha))*s$gky + s$gA\n\n# Plot figure of scenarios and their BGP's\nfig <- plot_ly(s, x = ~year, y = ~lny, linetype = ~scenario, type = 'scatter', mode = 'lines')\n#fig <- add_trace(fig, x = ~year, y = ~lnystar, linetype = ~scenario, type = 'scatter', mode = 'lines')\nfig <- layout(fig, title = list(text = 'log GDP per capita', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Log of GDP per capita'),\n hovermode=\"x unified\")\napi_create(fig, filename = \"sim-solow-lny\")\n\nfig <- plot_ly(s, x = ~year, y = ~gy, linetype = ~label, type = 'scatter', mode = 'lines')\nfig <- layout(fig, title = list(text = 'Growth rates', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Growth rate of GDP per capita'),\n hovermode=\"x unified\")\napi_create(fig, filename = \"sim-solow-gy\")\n\nfig <- plot_ly(s, x = ~year, y = ~ky, linetype = ~scenario, type = 'scatter', mode = 'lines')\nfig <- layout(fig, title = list(text = 'Capital/output ratio', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Capital/output ratio'),\n hovermode=\"x unified\")\napi_create(fig, filename = \"sim-solow-ky\")", "meta": {"hexsha": "300cf04328f89cc41b2fb45ba92c2cd4251e2a62", "size": 2735, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Guide_Sim_Solow.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/Guide_Sim_Solow.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Guide_Sim_Solow.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 48.8392857143, "max_line_length": 103, "alphanum_fraction": 0.6135283364, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7905303137346444, "lm_q1q2_score": 0.7213084404400094}} {"text": "nthroot <- function(A, n, tol=sqrt(.Machine$double.eps))\n{\n ifelse(A < 1, x0 <- A * n, x0 <- A / n)\n repeat\n {\n x1 <- ((n-1)*x0 + A / x0^(n-1))/n\n if(abs(x1 - x0) > tol) x0 <- x1 else break\n }\n x1\n}\nnthroot(7131.5^10, 10) # 7131.5\nnthroot(7, 0.5) # 49\n", "meta": {"hexsha": "b1e4c8fc6663c8316b726ebeacb40bc6242aa425", "size": 283, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Nth-root/R/nth-root.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Nth-root/R/nth-root.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Nth-root/R/nth-root.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 21.7692307692, "max_line_length": 56, "alphanum_fraction": 0.4734982332, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7212068320295892}} {"text": "#'@title Get the seasonality score for a given monthly time series\n#'\n#'@description The seasonality score of a monthly time series is computed as its departure from a uniform distribution.\n#'\n#'@usage tsData.ss <- getSeasonalityScore(tsData)\n#'\n#'@details\n#' The degree of seasonality of a monthly time series is based on its departure from a uniform distribution.\n#' If the number of cases for a given concept is uniformly distributed across all time periods (in this case, all months), \n#' then its monthly prevalence (as well as proportion) would be constant. In this case, the time series would be\n#' considered \"absolutely non-seasonal\" and its \"seasonality score\" would be zero.\n#' Similarly, if all the cases occur at a single point in time (that is, in a single month), such a time series would be considered\n#' \"absolutely seasonal\" and its seasonality score would be 1. All other time series would have\n#' a seasonality score between 0 and 1. Currently, only monthly time series are supported.\n#' NB: To be able to compute a seasonality score, a time series must have a minimum of three complete years of data. \n#' \n#'@param tsData A time series object.\n#'\n#'@return A numeric value between 0 and 1 (inclusive) representing the seasonality of a time series.\n#'\n#'@import dplyr\n#'@export\n\ngetSeasonalityScore <- function(tsData)\n{\n\ttsObj <- tsData\n\tmaxDist <- 1.83\n\tunifDist <- 1/12\n\tminMonths <- 36\n\n\tif (frequency(tsObj) != 12)\n\t\tstop(\"ERROR: Only monthly time series are supported\")\n\t\t\n\ttsObj <- Castor::tsCompleteYears(tsObj)\n\n\tif (length(tsObj) < minMonths)\n\t\tstop(\"ERROR: Time series must have a minimum of three complete years of data\")\n\t\n\ttsObj.yrProp <- Castor::sumAcrossYears(tsObj)$PROP\n\n\ttsObj.ss <- round(sum(abs(tsObj.yrProp-unifDist))/maxDist,2)\n\n\treturn (tsObj.ss)\n}", "meta": {"hexsha": "8f631e659dccb6d4d6e0c3d2bedabce5756dc49e", "size": 1803, "ext": "r", "lang": "R", "max_stars_repo_path": "R/getSeasonalityScore.r", "max_stars_repo_name": "OHDSI/Castor", "max_stars_repo_head_hexsha": "a64faf53509b50bfedf9057f042355fe2e17974b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-11T18:51:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T16:13:55.000Z", "max_issues_repo_path": "R/getSeasonalityScore.r", "max_issues_repo_name": "OHDSI/Castor", "max_issues_repo_head_hexsha": "a64faf53509b50bfedf9057f042355fe2e17974b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-23T18:35:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T16:41:40.000Z", "max_forks_repo_path": "R/getSeasonalityScore.r", "max_forks_repo_name": "OHDSI/Castor", "max_forks_repo_head_hexsha": "a64faf53509b50bfedf9057f042355fe2e17974b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9772727273, "max_line_length": 131, "alphanum_fraction": 0.7404326123, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.7208790161310745}} {"text": "# FUNCTIONS\n\n\nis_prime_6k1 <- function(n) {\n if (n <= 3) {\n return(n > 1)\n } else if (n %% 2 == 0 || n %% 3 == 0) {\n return(FALSE)\n }\n\n i <- 5\n while (i * i <= n) {\n if (n %% i == 0 || n %% (i + 2) == 0) {\n return(FALSE)\n }\n i <- i + 6\n }\n\n return(TRUE)\n}\n\n\n# SCRIPT\n\n\ni <- 1\nn <- 1\nwhile (i != 10001) {\n n <- n + 2\n i <- i + is_prime_6k1(n)\n}\n\nmessage(n)\n", "meta": {"hexsha": "3ef4b21cc9886b97c89d32f5a8cee22716ca9a5e", "size": 429, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/pe_0007.r", "max_stars_repo_name": "shanedrabing/project-euler", "max_stars_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/pe_0007.r", "max_issues_repo_name": "shanedrabing/project-euler", "max_issues_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/pe_0007.r", "max_forks_repo_name": "shanedrabing/project-euler", "max_forks_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.6176470588, "max_line_length": 47, "alphanum_fraction": 0.3613053613, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.7208790038413836}} {"text": "## Dale W.R. Rosenthal, 2018\n## You are free to distribute and use this code so long as you attribute\n## it to me or cite the text.\n## The legal disclaimer in _A Quantitative Primer on Investments with R_\n## applies to this code. Use or distribution without these comment lines\n## is forbidden.\n\nprice.tree <- function(numsteps, under.tree, opt.payoffs,\n rf, delta.t, ups=0, downs=0) {\n if (numsteps > 0) {\n up.value <- price.tree(numsteps-1, under.tree, opt.payoffs,\n rf, delta.t, ups+1, downs)\n down.value <- price.tree(numsteps-1, under.tree, opt.payoffs,\n rf, delta.t, ups, downs+1)\n } else {\n # We have reached a leaf; return the option payoff\n return(opt.payoffs[downs+1])\n }\n under.up.value <- under.tree[downs+1,ups+1+1]\n under.down.value <- under.tree[downs+1+1,ups+1]\n H <- (up.value-down.value)/(under.up.value-under.down.value)\n B <- (under.up.value*down.value - under.down.value*up.value)/\n (under.up.value - under.down.value)*exp(-rf*delta.t)\n H*under.tree[downs+1,ups+1] + B\n}\n\nrf <- 0.03 # 3% risk-free rates\nsigma <- 0.45 # 45% volatility\nT <- 1.25 # 15-month option\nn.steps <- 16 # number of steps total\ndelta.t <- T/n.steps # interpolated time step size\nu <- exp(sigma*sqrt(delta.t)) # up move\nd <- exp(-sigma*sqrt(delta.t)) # down move\ns0 <- 100 # initial stock price\nK <- 80 # strike price\n\n## This creates a full matrix with the tree -- and steps beyond the tree\n## in the lower-right triangle of the matrix. Since this is an easy way\n## to create the tree, we will just ignore the lower-right triangle.\nunderlier.tree <- s0*d^(0:n.steps)%*%t(u^(0:n.steps))\noption.payoffs <- pmax(s0*u^(n.steps:0)*d^(0:n.steps) - K, 0)\nprice.tree(numsteps=n.steps, underlier.tree, option.payoffs, rf, delta.t)\n", "meta": {"hexsha": "52d2782564b883f6ed63dbc152dad6d91dc71781", "size": 1870, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch21-option-tree.r", "max_stars_repo_name": "bmoretz/Quantitative-Investments", "max_stars_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-26T05:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T21:50:54.000Z", "max_issues_repo_path": "Quantitative Primer/samples/ch21-option-tree.r", "max_issues_repo_name": "bmoretz/Quantitative-Investments", "max_issues_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quantitative Primer/samples/ch21-option-tree.r", "max_forks_repo_name": "bmoretz/Quantitative-Investments", "max_forks_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-03T09:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:50:55.000Z", "avg_line_length": 43.488372093, "max_line_length": 73, "alphanum_fraction": 0.6347593583, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7208790029126722}} {"text": "url <- \"https://ww2.amstat.org/publications/jse/datasets/fruitfly.dat.txt\"\ndata <- read.table(url)\ndata <- data[, c(-1, -6)]\n\nnames(data) <- c(\"partners\", \"type\", \"longevity\", \"thorax\")\npar(mfrow = c(3, 2))\nplot(data$thorax, data$longevity, col = data$partners, pch = data$type)\n\ndata0 <- data[data$partners == 0, ]\nplot(data0$thorax, data0$longevity, col = data$partners, pch = data$type)\n\ndata1 <- data[data$partners == 1, ]\nplot(data1$thorax, data1$longevity, col = data$partners, pch = data$type)\n\ndata8 <- data[data$partners == 8, ]\nplot(data8$thorax, data8$longevity, col = data$partners, pch = data$type)\n\np0 <- as.integer(data$partners == 0)\np1t0 <- as.integer(data$partners == 1 & data$type == 0)\np1t1 <- as.integer(data$partners == 1 & data$type == 1)\np8t0 <- as.integer(data$partners == 8 & data$type == 0)\np8t1 <- as.integer(data$partners == 8 & data$type == 1)\n\ndata_dummy <- cbind(data, p0, p1t0, p1t1, p8t0, p8t1)\nboxplot(cbind(data_dummy[data_dummy$p0 == 1, ]$longevity,\n data_dummy[data_dummy$p1t0 == 1, ]$longevity,\n data_dummy[data_dummy$p1t1 == 1, ]$longevity,\n data_dummy[data_dummy$p8t0 == 1, ]$longevity,\n data_dummy[data_dummy$p8t1 == 1, ]$longevity)\n)\n\n# use p0 as control group\nfitfull <- lm(thorax ~ p1t0 + p1t1 + p8t0 + p8t1, data_dummy)\nfitintercept <- lm(thorax ~ 1, data_dummy)\n# not significant, so null hypothesis: model is the same should be acc.ed\nprint(anova(fitintercept, firfull))\n\nreg_wo <- lm(longevity ~ type, data1)\nprint(summary(reg_wo))\n\nreg_w <- lm(longevity ~ type + thorax, data1)\nprint(summary(reg_w))\n\nreg_full_fail <- lm(longevity ~ thorax\n + as.factor(partners) * as.factor(type), data)\n\nprint(summary(reg_full_fail)) # some NA here, and most var are not significant\n\n\nreg_full <- lm(longevity ~ thorax + p1t0 + p1t1 + p8t0 + p8t1, data_dummy)\nprint(summary(reg_full))\n\nreg_reduce <- lm(longevity ~\n thorax +\n I(p1t0 - p8t1) +\n I(p1t1 + p8t1) +\n I(p8t0 + p8t1), data_dummy)\nprint(summary(reg_reduce))\n\nprint(anova(reg_reduce, reg_full))", "meta": {"hexsha": "da990a5779ac351dcbd27da10bce67a161c29dc5", "size": 2106, "ext": "r", "lang": "R", "max_stars_repo_path": "Computational_Statistics/Exercices/2_1.r", "max_stars_repo_name": "DanDoge/course_ethz", "max_stars_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Computational_Statistics/Exercices/2_1.r", "max_issues_repo_name": "DanDoge/course_ethz", "max_issues_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computational_Statistics/Exercices/2_1.r", "max_forks_repo_name": "DanDoge/course_ethz", "max_forks_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1, "max_line_length": 78, "alphanum_fraction": 0.6528964862, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7208790015341879}} {"text": "spectralClustering <- function(affinity, K, type=3) {\n\t\n ###This function implements the famous spectral clustering algorithms. There are three variants. The default one is the third type. \n ###THe inputs are as follows:\n \n #affinity: the similarity matrix;\n #K: the number of clusters\n # type: indicators of variants of spectral clustering \n\t\n d = rowSums(affinity)\n d[d == 0] = .Machine$double.eps\n D = diag(d)\n L = D - affinity\n if (type == 1) {\n NL = L\n } else if (type == 2) {\n Di = diag(1 / d)\n NL = Di %*% L\n } else if(type == 3) {\n Di = diag(1 / sqrt(d))\n NL = Di %*% L %*% Di\n }\n eig = eigen(NL)\n res = sort(abs(eig$values),index.return = TRUE)\n U = eig$vectors[,res$ix[1:K]]\n normalize <- function(x) x / sqrt(sum(x^2))\n if (type == 3) {\n U = t(apply(U,1,normalize))\n }\n eigDiscrete = .discretisation(U)\n eigDiscrete = eigDiscrete$discrete\n labels = apply(eigDiscrete,1,which.max)\n \n \n \n return(labels)\n}\n", "meta": {"hexsha": "b0f31f4a886e6779c7eed34df5511d8764d295d1", "size": 971, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/SNFtools/spectralClustering.r", "max_stars_repo_name": "AleZandona/ml_rSNFi", "max_stars_repo_head_hexsha": "a765042fd45dbe88b544eb2611dee171a0939caa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-22T12:17:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-05T11:26:44.000Z", "max_issues_repo_path": "scripts/SNFtools/spectralClustering.r", "max_issues_repo_name": "AleZandona/ml_rSNFi", "max_issues_repo_head_hexsha": "a765042fd45dbe88b544eb2611dee171a0939caa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/SNFtools/spectralClustering.r", "max_forks_repo_name": "AleZandona/ml_rSNFi", "max_forks_repo_head_hexsha": "a765042fd45dbe88b544eb2611dee171a0939caa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5526315789, "max_line_length": 134, "alphanum_fraction": 0.605561277, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7208393609646963}} {"text": "ex1 = function()\n{\n\tdata = read.table(\"D:\\\\Facultate\\\\Capitole Speciale de Inteligenta Artificiala\\\\homework3\\\\data\\\\alcool.dat\", header=T, sep=\"\", dec=\".\")\n\t\n\t#1\n\tx = data[,2]\n\ty = data[,3]\n\tplot(x, y, pch=20, main='Scatter plot alcohol',\n\t\txlab='Median alcohol consumption',\n\t\tylab='Hearth disease related deaths')\n\t\n\t#2\n\t#raw formula\n\tx_mean = mean(x)\n\ty_mean = mean(y)\n\tr = sum( (x-x_mean) * (y-y_mean) ) /\n\t (sqrt(sum( (x-x_mean)^2 )) * sqrt(sum( (y-y_mean)^2 )))\n\tmessage(\"My formula's result: \", r)\n\n\t#r function\n\tmessage(\"R formula's result: \", cor(x,y))\n}\n\nex2 = function()\n{\n\tdata = read.table(\"D:\\\\Facultate\\\\Capitole Speciale de Inteligenta Artificiala\\\\homework3\\\\data\\\\iq.dat\", header=T, sep=\"\", dec=\".\")\n\n\t#1\n\tx = data[,2]\n\ty = data[,3]\n\n\tplot(x, y, pch=20, main='Scatter plot IQ',\n\t\txlab='IQ',\n\t\tylab='Grade')\n\n\t#2\n\tx_mean = mean(x)\n\ty_mean = mean(y)\n\tb1 = sum( (x-x_mean) * (y-y_mean) )/sum( (x-x_mean)^2 )\n\tb0 = y_mean - b1*x_mean\n\tabline(b0, b1, lwd=3, col='red')\n\n\tmessage(\"Grade estimate for 115 IQ: \", b0 + b1*115)\n\tmessage(\"Grade estimate for 130 IQ: \", b0 + b1*130)\n}\n\nex3 = function(m, a, b, xmin, xmax, sigma)\n{\n\tx = runif(m, min=xmin, max=xmax)\n\te = rnorm(m, 0, sigma)\n\ty = a + b*x + e\n\tcbind(x, y)\n}\n\nex4 = function(obs)\n{\n\tx = obs[,1]\n\ty = obs[,2]\n\t\n\tx_mean = mean(x)\n\ty_mean = mean(y)\n\tb = sum( (x-x_mean) * (y-y_mean) )/sum( (x-x_mean)^2 )\n\ta = y_mean - b*x_mean\n\t\n\ty_estimate = a + b*x\n\tsse = sum( (y - y_estimate)^2 )\n\ts = sqrt(sse / (length(y) - 2))\n\tsb = s / sqrt(sum( (x-x_mean)^2 ))\n\tt = qt(0.975, df=(length(x) - 2))\n\t\n\tblow = b - t*sb\n\tbhigh = b + t*sb\n\n\tsa = sb*sqrt( sum(x^2) / length(x) )\n\talow = a - t*sa\n\tahigh = a + t*sa\n\t\n\tcbind(c(a,b), c(blow, bhigh), c(alow, ahigh))\n}\n\nplot_and_save = function(m, a, b, xmin, xmax, sigma, id)\n{\n\tpdf(file=paste(\"D:\\\\Facultate\\\\Capitole Speciale de Inteligenta Artificiala\\\\homework3\\\\graphs\\\\graph_\", id, \".pdf\", sep=\"\"),\n\t\twidth=8, height=8\n\t)\n\t\n\tobs = ex3(m, a, b, xmin, xmax, sigma)\n\tres = ex4(obs)\n\n\tplot(obs[,1], obs[,2], pch=20,\n\t\tmain=paste('a: ', res[1,1], ', b: ', res[2,1], '\\n',\n\t\t\t'CI b: [', res[1,2], ' , ', res[2,2], ']\\n',\n\t\t\t'CI a: [', res[1,3], ' , ', res[2,3], ']', sep=\"\"),\n\t\txlab='x',\n\t\tylab='y')\n\n\tabline(a, b, lwd=3, col='red')\n\tabline(res[1,1], res[2,1], lwd=2, col='green')\n\n\tdev.off()\n}\n\nex5 = function()\n{\n\t#a\n\tplot_and_save(100, 10, 0.8, -200, 200, 1.5, 'a')\n\n\t#b\n\tplot_and_save(10, 10, 0.8, -5, 5, 1, 'b')\n\n\t#c\n\tplot_and_save(10000, 10, 0.8, -5, 5, 1, 'c')\n\n\t#d\n\tplot_and_save(10, 10, 0.8, 5, 5.2, 1, 'd')\n\n\t#e\n\tplot_and_save(10000, 10, 0.8, 5, 5.2, 1, 'e')\n\n\t#f\n\tplot_and_save(10, 10, 0.8, 5, 5.2, 0.01, 'f')\n\n\t'done'\n}", "meta": {"hexsha": "2d6bfca4a861a28862f5f0a1a2e9168bef566e01", "size": 2633, "ext": "r", "lang": "R", "max_stars_repo_path": "homework3/hw3.r", "max_stars_repo_name": "Amihaeseisergiu/Special-Chapters-Of-Artificial-Intelligence", "max_stars_repo_head_hexsha": "508de2e5277632d59f3330c9269357fdaf1fb5cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework3/hw3.r", "max_issues_repo_name": "Amihaeseisergiu/Special-Chapters-Of-Artificial-Intelligence", "max_issues_repo_head_hexsha": "508de2e5277632d59f3330c9269357fdaf1fb5cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework3/hw3.r", "max_forks_repo_name": "Amihaeseisergiu/Special-Chapters-Of-Artificial-Intelligence", "max_forks_repo_head_hexsha": "508de2e5277632d59f3330c9269357fdaf1fb5cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2338709677, "max_line_length": 137, "alphanum_fraction": 0.5624762628, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7206975453142396}} {"text": "# Source: Mollet and Cailliet 2002. Mar Freshwater Res. Comparative population\r\n# demography of elasmobranch using life history tables, Leslie matrices and\r\n# stage-based matrix models\r\n\r\nrm(list=ls(all=TRUE)) # removes all previous material from R's memory\r\n\r\n\r\n# Define a function to compute basic demographic parameters\r\nbasic_demographic_parameters <- function(M) {\r\n\r\n # finite growth rate (max eigenvalue)\r\n vM <- eigen(M); \r\n lambda <- Re(vM$values[1]); # Real part of the first eigenvector\r\n\r\n # population structure, i.e., the normalized right eigenvector \r\n # associated to the maximum eigenvalue \r\n ps <- Re(vM$vectors[,1]); \r\n ps <- ps / sum(ps); # normalize\r\n \r\n # reproductive value, i.e, the left eigenvector associated to the\r\n # maximum eigenvalue (it is computed as the right eigenvector of the\r\n # transposed matrix)\r\n rv <- Re(eigen(t(M))$vectors[,1]);\r\n rv <- rv / rv[1]; # standardize relative to 1st class\r\n \r\n #Sensitivity and elasticity\r\n sens <- outer(rv,ps) / sum(rv*ps) # sensitivity\r\n elas <- (sens*M) / lambda # elasticity [%]\r\n\r\n return(list(lambda=lambda, ps=ps, rv=rv, elast=elas))\r\n \r\n}\r\n\r\n#############################################################################\r\n# let's look first at the full matrix\r\n\r\n# create a 10x10 matrix and assign 0 to all the elements\r\ntransM <- matrix(nrow=10, ncol=10, byrow=TRUE, data=0)\r\n\r\n# set reproductive rate\r\n# Only age 3 and older reproduce\r\nfor (j in 3:10) transM[1,j] <- 1.8929\r\n\r\n# set survivals\r\n# Fill in the sub-diagonal for ages 1-9\r\nfor (j in 1:9) transM[j+1,j] <- 0.631\r\n\r\n#check the transition matrix\r\ntransM\r\n\r\n#plot the transition matrix \r\nimage(1:nrow(transM), 1:ncol(transM), t(transM), ylim =c(ncol(transM)+0.5, 0.5) )\r\n\r\n\r\n# Call our function\r\nbdp_transM_L <- basic_demographic_parameters(transM); bdp_transM_L \r\n\r\nsum(bdp_transM_L$ps[3:10])\r\n\r\nimage(1:nrow(bdp_transM_L$elas), 1:ncol(bdp_transM_L$elas), t(Mod(bdp_transM_L$elas)), ylim =c(ncol(transM)+0.5, 0.5))\r\n \r\n \r\n#############################################################################\r\n# let's now look at the reduced matrices\r\n\r\nreducedM <- matrix(nrow=3, ncol=3, byrow=TRUE, \r\n data<-c( 0, 0, 1.8929,\r\n 0.631, 0, 0,\r\n\t 0, 0.631, 0.6272))\r\n\r\nbasic_demographic_parameters(reducedM)\r\n\r\n############################################################################\r\n\r\nreduced2M <- matrix(nrow=2, ncol=2, byrow=TRUE, \r\n data<-c( 0.4104, 1.8929,\r\n 0.2206, 0.6272))\r\n\r\nbasic_demographic_parameters(reduced2M)\r\n", "meta": {"hexsha": "055d26449a857a3ee8a7577f16029a05b7d67bdf", "size": 2594, "ext": "r", "lang": "R", "max_stars_repo_path": "age_size/3_Mollet and Cailliet 2002. Mar Freshwater Res. Comparative.r", "max_stars_repo_name": "elahi/bio143", "max_stars_repo_head_hexsha": "b434984dd5a1d77d451264bee6d568de973a7c32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "age_size/3_Mollet and Cailliet 2002. Mar Freshwater Res. Comparative.r", "max_issues_repo_name": "elahi/bio143", "max_issues_repo_head_hexsha": "b434984dd5a1d77d451264bee6d568de973a7c32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "age_size/3_Mollet and Cailliet 2002. Mar Freshwater Res. Comparative.r", "max_forks_repo_name": "elahi/bio143", "max_forks_repo_head_hexsha": "b434984dd5a1d77d451264bee6d568de973a7c32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.425, "max_line_length": 119, "alphanum_fraction": 0.5898226677, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.720630255003904}} {"text": "#R version 3.3.2 \n\nfirstFibonacci <- 1\n\nsecondFibonacci <- 1\n\nsum_of_even_fibonacci <- 0\n\nhelper <- 0\n\n# O(n) solution\nwhile (secondFibonacci <= 4000000) {\n helper <- firstFibonacci\n firstFibonacci <- secondFibonacci\n secondFibonacci <- firstFibonacci + helper\n\n if (secondFibonacci %% 2 == 0) {\n sum_of_even_fibonacci <- sum_of_even_fibonacci + secondFibonacci \n }\n}\n\nprint(sum_of_even_fibonacci)\n", "meta": {"hexsha": "64a47513bfe6b87c4dadd72852e90895c73a211a", "size": 420, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Problem2.r", "max_stars_repo_name": "ditekunov/projectEuler-research", "max_stars_repo_head_hexsha": "e8f84388045cdc1391d1e363c7b55ff4f85be708", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-20T08:01:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-20T08:05:07.000Z", "max_issues_repo_path": "R/Problem2.r", "max_issues_repo_name": "ditekunov/ProjectEuler-asymptotics", "max_issues_repo_head_hexsha": "e8f84388045cdc1391d1e363c7b55ff4f85be708", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/Problem2.r", "max_forks_repo_name": "ditekunov/ProjectEuler-asymptotics", "max_forks_repo_head_hexsha": "e8f84388045cdc1391d1e363c7b55ff4f85be708", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2608695652, "max_line_length": 73, "alphanum_fraction": 0.7, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7203202539252916}} {"text": "## Dale W.R. Rosenthal, 2018\n## You are free to distribute and use this code so long as you attribute\n## it to me or cite the text.\n## The legal disclaimer in _A Quantitative Primer on Investments with R_\n## applies to this code. Use or distribution without these comment lines\n## is forbidden.\n\nalpha <- 0.05 # probability mass in the loss tail\nt.df <- 5 # degrees of freedom for the t-distribution\n\n# Calculate VaR (inverse CDF) and expected shortfall (numeric integration)\nvalue.at.risk <- qt(alpha, df=t.df)\nt5.mean.integrand <- function(x) { x*dt(x,t.df)}\nex.shortfall <- 1/alpha*integrate(t5.mean.integrand, lower=-Inf,\n upper=value.at.risk)[[\"value\"]]\n\ncurve(dt(x, t.df), xlim=c(-4,4), lwd=2) # plot the t-distribution\n\n# Setup for drawing a filled-in area under the curve\nx.seq <- seq(-5, value.at.risk, 0.01)\ny.seq <- dt(x.seq, t.df)\ncord.x <- c(-5, x.seq, value.at.risk)\ncord.y <- c(0, y.seq, 0)\npolygon(cord.x, cord.y, col=\"plum1\") # and draw the filled-in area\n\nabline(v=value.at.risk, lty=2, lwd=2, col=\"red\") # add a vertical line at the VaR\nabline(v=ex.shortfall, lty=4, lwd=2, col=\"deepskyblue\") # add a vertical line at the ES\nabline(h=0)\ntext(x=-2.015, y=0.05, \"5%-VaR\", pos=4) # Add text notes near...\ntext(x=-2.890, y=0.01, \"5%-ES\", pos=4) # ...the vertical lines\n", "meta": {"hexsha": "c6767e3fbf48fcea46153e1153027603825159ee", "size": 1332, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch8-var-vs-es-plot.r", "max_stars_repo_name": "bmoretz/Quantitative-Investments", "max_stars_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-26T05:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T21:50:54.000Z", "max_issues_repo_path": "Quantitative Primer/samples/ch8-var-vs-es-plot.r", "max_issues_repo_name": "bmoretz/Quantitative-Investments", "max_issues_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quantitative Primer/samples/ch8-var-vs-es-plot.r", "max_forks_repo_name": "bmoretz/Quantitative-Investments", "max_forks_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-03T09:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:50:55.000Z", "avg_line_length": 42.9677419355, "max_line_length": 89, "alphanum_fraction": 0.6606606607, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7202305641744319}} {"text": "#' Calculate settling velocity for a particle.\n#'\n#' \\code{settle} calculates the settling velocity for a particle, given some parameters.\n#' @param ws_mode Denotes whether to use a 'simple' equation, neglecting the shape and roundness of particles, or to use the more 'complex' formulation\n#' @param D The grain size you wish to calculate settling velocity for.\n#' @param constants A list of constants for calculation, need in order (g) gravitational constant, (rhos) sediment density, (rhof) fluid density, (nuu) kinematic viscosity, (csf) corey shape factor, and (PI) Powers roundness index. For the simple formulation, neglect the last two. Defaults to constants = list(g = 9.8, rhos = 2650, rhof = 1000, nuu = 1.004e-6, csf = 0.7, PI = 3.5)\n#' @return Returns a list with two values \\code{$ws} and \\code{$wstar} which are the settling velocity and dimensionless settling velocity, respectively. \n#' @export\n#' @examples\n#' settle('simple', 120e-6)\n#' settle('complex', 120e-6, list(g = 9.8, rhos = 2650, rhof = 1000, nuu = 1.004e-6, csf = 0.7, PI = 3.5)\n\n#\tfunction to replicate two implementations of Dietrich 1982 settling velocity measurement for a given grain size and density.\n#\tEric Barefoot\n#\tNov 2017\n\n#\ttakes constants as a list with names g, rhos, rhof, nuu, csf, PI with an option to leave off csf and PI for a simpler case\n\nsettle = function(ws_mode, D, constants) {\n\t\n\tif(missing(constants)) {\n\t\tg = 9.8\t\t\t# m/s^2\n\t\trhos = 2650\t\t# assuming ~quartz sand.\n\t\trhof = 1000\t\t# assuming water\n\t\tnuu = 1.004e-6\t# kinematic viscocity of water at 20C in Pa s\n\t\tcsf = 0.7\t\t# given csf for grains \n\t\tPI = 3.5\t\t# average for natural grains. Varies from 0-6.\n\t}\t\t\t\n\telse if (ws_mode == 'simple' & length(constants) != 4) {\n\t\twarning('incorrect number of constants; using defaults for the simple method')\n\t\tg = 9.8\t\t\t# *m/s^2\n\t\trhos = 2650\t\t# *assuming ~quartz sand.\n\t\trhof = 1000\t\t# *assuming water\n\t\tnuu = 1.004e-6}# *kinematic viscocity of water at 20C in Pa s}\n\telse if (ws_mode == 'complex' & length(constants) != 6) {\n\t\twarning('incorrect number of constants; using defaults for the complex method')\n\t\tg = 9.8\t\t\t# m/s^2\n\t\trhos = 2650\t\t# assuming ~quartz sand.\n\t\trhof = 1000\t\t# assuming water\n\t\tnuu = 1.004e-6\t# kinematic viscocity of water at 20C in Pa s\n\t\tcsf = 0.7\t\t# given csf for grains \n\t\tPI = 3.5}\t\t# average for natural grains. Varies from 0-6.\n\telse if (ws_mode == 'simple') {\n\t\tg = constants$g\t\t\t# m/s^2\n\t\trhos = constants$rhos\t# assuming ~quartz sand.\n\t\trhof = constants$rhof\t# assuming water\n\t\tnuu = constants$nuu\t# kinematic viscocity of water at 20C in Pa s\n\t}\t\n\telse if (ws_mode == 'complex') {\n\t\tg = constants$g\t\t\t# m/s^2\n\t\trhos = constants$rhos\t# assuming ~quartz sand.\n\t\trhof = constants$rhof\t# assuming water\n\t\tnuu = constants$nuu\t# kinematic viscocity of water at 20C in Pa s\n\t\tcsf = constants$csf\t\t# given csf for grains \n\t\tPI = constants$PI\t\t# average for natural grains. Varies from 0-6.\n\t}\t\t\n\n\t#\tcalculate dimensionless grain size\n\n\tDstar = (rhos - rhof) * ((g * D^3) / (rhof * nuu^2)) \n\n\t#\tsimple case\n\t\n\tif (ws_mode == 'simple') {\n\n\t\tDsl = log10(Dstar)\n\t\t\n\t\tR1 = -3.76715 + 1.92944*Dsl - 0.09815*Dsl^2 - 0.00575*Dsl^3 + 0.00056*Dsl^4\n\t\t\n\t\twstar = 10^(R1)\n\t\n\t}\n\t\n\tif (ws_mode == 'complex') {\n\t#\tsome simplifying common terms\n\t\t\n\t\tDsl = log10(Dstar)\n\t\ttantan = tanh(Dsl - 4.6)\n\t\tcsf_t = 1 - csf\n\t\t\n\t\t#\tnow the other parameters for settling velocity \n\t\t#\tNOTE: lynds et al neglect the other terms, so theres a switch, one with the shape factor and powers index, and one without. default is simple\n\n\t\tR1 = -3.76715 + 1.92944*Dsl - 0.09815*Dsl^2 - 0.00575*Dsl^3 + 0.00056*Dsl^4\n\n\t\tR2 = (log10(1 - (csf_t/0.85)) - csf_t^2.3*tantan + 0.3*(0.5 - csf)*csf_t^2*(Dsl - 4.6))\n\n\t\tR3 = (0.65 - ((csf/2.83)*tantan))^(1+(3.5-PI)/2.5)\n\t\t\n\t\twstar = R3 * 10^(R1 + R2)\n\t}\n\n\t#\tconversion back to dimensional settling velocity\n\n\tws = (wstar * (rhos - rhof) * g * nuu / rhof)^(1/3)\n\n\treturn(list(ws = ws, wstar = wstar))\n\n}", "meta": {"hexsha": "e36d1695287bf3eb2fcd50294e111b5998db41ae", "size": 3941, "ext": "r", "lang": "R", "max_stars_repo_path": "R/settle.r", "max_stars_repo_name": "ericbarefoot/barefootr", "max_stars_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/settle.r", "max_issues_repo_name": "ericbarefoot/barefootr", "max_issues_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-17T16:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-17T16:32:53.000Z", "max_forks_repo_path": "R/settle.r", "max_forks_repo_name": "ericbarefoot/barefootr", "max_forks_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8080808081, "max_line_length": 383, "alphanum_fraction": 0.6663283431, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7202305540210059}} {"text": "##### Chapter 5: Classification using Decision Trees and Rules -------------------\n\n# 트리에 다수의 명목 특징이 여러 레벨로 이루어져 있거나, 다수의 수치 특성이 있는 경우 tree overfit\n# 매개 변수(parameter) 조정으로 이러한 단점을 극복할 수 있다.\n# 트리 생성을 일찍 중단하거나(사전 가지치기 pre-prunning)\n# 트리를 만든 후 데이터 포인터가 적은 노드를 삭제하거나 병합하는 것(사후 가지치기 post-prunning)\n\n# 랜덤 포레스트와, 그래디언트 부스팅으로도 이러한 단점을 극복할 수 있다.\n\n# 트리의 C5.0 알고리즘은 트리 식별 방법으로 엔트로피를 이용한다.\n# 클래스가 n개인 경우 엔트로피의 범위는 0에서 log2(밑이 2)n이다.(클래스 값의 집합 내의 무작위성 또는 무질서를 정량화)\n\n#### Part 1: Decision Trees -------------------\n\n## Understanding Decision Trees ----\n# calculate entropy of a two-class segment\n-0.60 * log2(0.60) - 0.40 * log2(0.40) # 하나는 확률 0.6, 나머진 0.4인 경우\n\ncurve(-x * log2(x) - (1 - x) * log2(1 - x), # 클래스 2개일 때 모든 가능한 엔트로피 배열\n col = \"red\", xlab = \"x\", ylab = \"Entropy\", lwd = 4)\n# 분할을 하기 위한 최적의 특징을 결정하기 위해 엔트로피를 사용하려면\n# 알고리즘은, 각 특징별로, 분할로 인해 생기는 동질성의 변화를 계산한다.\n# 이것이 정보 획득량이라고 하는 척도이다.\n## 어떠한 특징 F의 정보 획득량은 분할 전 세그먼트 S1과 분할로 생성된 파티션들 S2의 엔트로피 차로 계산된다.\n# 그런데 문제는 분할 후에 데이터가 하나 이상의 파티션으로 나뉜다\n# -> S2 계산하는 함수는 모든 파티션의 전체 엔트로피 고려\n# -> n개 파티션에 대해, 각 파티션의 엔트로피에 파티션이 속하는 예시 비율로 가중치 부여하여 합산.\n\n# 정보 획득량 높음 -> 이 특징에 분할한 후 동질적 그룹을 생성하기 더 좋은 특징.\n# 수치 특성에 대해 분할할 때에도 정보 획득량 사용 -> 어떠한 임계값보다 큰지 작은지로 나눈다. 그 임계값은 다양하게 테스트한다.\n# 이러한 방식으로 수치적 특성을 2레벨 범주형 특성으로 나눈다.\n# 그리고 분할 시 최대 정보 획득량을 산출하는 수치 절단점을 선택한다.\n\n# 사전 가지치기를 하면, 감지하기는 힘들지만 트리가 크게 자랐다면 학습할 수도 있는 중요한 패턴을 놓칠 수도 있다.\n# 그 대안으로 사후 가지치기를 한다.\n# -> 먼저 overfit되는 큰 트리로 자라게 한 후, 나중에 분류 오류에 영향이 거의 없는 노드와 분기는 제거한다.\n# -> 어떤 때에는 전체 분기가 위쪽으로 옮겨지거나, 좀 더 간단한 의사결정으로 대체된다.\n\n# overfit과 underfit의 균형을 맞추는 것은 다소 기술적.\n# 하지만 모델의 정확도가 필수적이라면 다양한 가지치기 옵션으로 테스트 데이터에 대해 성능 향상이 되는지 투자해야! \n\n## Example: Identifying Risky Bank Loans ----\n## Step 2: Exploring and preparing the data ----\ngetwd()\nsetwd('D:/R_LAB/MLwR/Chapter 05')\n\ncredit <- read.csv(\"credit.csv\")\nstr(credit)\n\n# look at two characteristics of the applicant\ntable(credit$checking_balance)\ntable(credit$savings_balance)\n\n# look at two characteristics of the loan\nsummary(credit$months_loan_duration)\nsummary(credit$amount)\n\n# look at the class variable\ntable(credit$default)\n\n# create a random sample for training and test data\n# use set.seed to use the same random number sequence as the tutorial\n# 훈련에 데이터 90% 사용, 테스트에 10% 사용\n# 임의로 정렬되어 있지 않은 데이터를 다루는 방법 -> 랜덤 샘플\nset.seed(123) # 랜덤 샘플 수행하기 전에 시드값 설정\ntrain_sample <- sample(1000, 900)\n\nstr(train_sample)\n\n# split the data frames\ncredit_train <- credit[train_sample, ]\ncredit_test <- credit[-train_sample, ]\n\n# check the proportion of class variable\n# 잘 나뉘었다면 각 데이터셋은 약 30%의 채무불이행 대출을 갖는다.\nprop.table(table(credit_train$default)) # 잘 나뉘었다\nprop.table(table(credit_test$default)) # 잘 나뉘었다\n\n## Step 3: Training a model on the data ----\n# build the simplest decision tree\nif(!require(C50)) {\n install.packages(\"C50\")\n require(C50)\n}\n# ?C5.0Control 명령으로 알고리즘을 정교하게 조정하는 방법에 대한 더 자세한 사항을 확인할 것\n\n# credit_train의 17번째 열은 default 클래스 변수이므로 제외한다.\n# 그리고 분류를 하기 위한 목표 팩터 벡터로 제공해야 한다.\ncredit_model <- C5.0(credit_train[-17], credit_train$default)\n\n# display simple facts about the tree\ncredit_model # 트리 크기 57 -> 트리가 57개의 결정으로 이뤄진 깊이라는 뜻.\n\n# display detailed information about the tree\nsummary(credit_model)\n# 가끔 트리는 논리적으로 이해가 안 되는 결정을 만든다.\n# ex) 왜 대출 이력이 좋은 신청자가 채무불이행 가능성 있지? 왜 수표 계좌 잔고를 모르면 채무불이행 가능성 없지?\n# 그런 규칙들은 데이터의 실제 패턴을 반영한 결과일 수도 있고\n# 단지 통계적 이상치일 수도 있다.\n# 두 경우 모두, 트리의 논리가 비즈니스 용도로 합당한지 확인하기 위해\n# 이런 이상한 결정을 조사해보는 것이 중요하다.\n\n# 트리를 출력한 후 혼동 행렬을 보여준다.\n# 혼동 행렬은 모델이 훈련 데이터에서 부정확하게 분류한 레코드를 보여주는 교차표다.\n\n## Step 4: Evaluating model performance ----\n# create a factor vector of predictions on test data\ncredit_pred <- predict(credit_model, credit_test)\n\n# cross tabulation of predicted versus actual classes\nlibrary(gmodels)\n# gmodels 패키지에 있는 CrossTable() 함수를 통해, 이 벡터와 실제 클래스 값을 비교할 수 있다.\nCrossTable(credit_test$default, credit_pred,\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\n dnn = c('actual default', 'predicted default'))\n# prop.c = FALSE, prop.r = FALSE 하면 표에서 열과 행 비율을 제거한다.\n\n# 남은 백분율 prop.t는 전체 레코드 개수에서 셀의 레코드 비율을 나타낸다.\n\n\n## Step 5: Improving model performance ----\n# 실제 채무불이행 중 42%만 정확히 예측했다. 이는 매우 큰 비용이 될 수 있다.\n\n## Boosting the accuracy of decision trees\n# boosted decision tree with 10 trials(부스팅 팀에 사용할 독립적 트리의 갯수를 10개로 늘림)\ncredit_boost10 <- C5.0(credit_train[-17], credit_train$default,\n trials = 10)\n# rules = TRUE를 명시하면 분류 규칙을 이용해 모델을 생성하게 된다.\n\n\n\ncredit_boost10 # 트리의 크기가 57에서 47로 줄어들었다.\nsummary(credit_boost10)\n# 부스팅을 추가하기 전 오류율보다 매우 줄어들었다.\n\n# 테스트 데이터에서도 성능 향상이 될까?\ncredit_boost_pred10 <- predict(credit_boost10, credit_test)\nCrossTable(credit_test$default, credit_boost_pred10,\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\n dnn = c('actual default', 'predicted default'))\n# 오류율이 27에서 18로 줄었다. 채무불이행은 여전히 예측율이 낮다.\n# 더 크게 개선되지 않은 이유\n # 1. 상대적으로 작은 훈련 데이터셋과 함수 관계\n # 2. 이 문제 자체가 원래 해결하기 어려운 문제\n\n# 부스팅을 쓰지 않는 이유 -> 계산량 증가, 훈련 데이터에 잡음이 많으면 부스팅으로 개선되지 않음.\n\n\n## Making some mistakes more costly than others\n\n# create dimensions for a cost matrix\n# 트리가 좀 더 비용이 많이 드는 실수를 하지 못하도록\n# 여러 오류 유형에 페널티를 줄 수 있음.\nmatrix_dimensions <- list(c(\"no\", \"yes\"), c(\"no\", \"yes\"))\nnames(matrix_dimensions) <- c(\"predicted\", \"actual\")\nmatrix_dimensions\n\n# build the matrix\n# 행렬을 채울 때 열 단위로 위에서 아래로 채우기 때문에, 특정 순서대로 값을 제공해야 한다.\n# pre x act x\n# pre o act x\n# pre x act o\nerror_cost <- matrix(c(0, 1, 4, 0), nrow = 2, dimnames = matrix_dimensions)\nerror_cost\n\n# apply the cost matrix to the tree\ncredit_cost <- C5.0(credit_train[-17], credit_train$default,\n costs = error_cost)\ncredit_cost_pred <- predict(credit_cost, credit_test)\n\nCrossTable(credit_test$default, credit_cost_pred,\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\n dnn = c('actual default', 'predicted default'))\n# 거짓 긍정을 증가시킨 대가로 거짓 부정을 줄였다.\n# 전체적인 실수는 증가했지만, 이렇게 하는 편이 오히려 이익이 될 수도 있다.\n\n#### Part 2: Rule Learners -------------------\n\n# 분류 규칙은, 클래시를 레이블이 없는 예시에 할당하는 논리적인 if-else문으로 지식을 표현한다.\n# -> 이것이 발생하면, 저것이 발생한다.\n\n# 규칙은 tree로도 생성할 수 있는데 왜 별도의 규칙 학습자 알고리즘에 신경을 쓰는가?\n# -> 규칙 학습자가 규칙을 직접 찾음으로써 피할 수 있는 작업에 대해,\n# 의사 결정 트리는 특정 편향을 불러오기 때문이다.\n\n# 규칙 학습자는 일반적으로, 특징이 주로 또는 전체적으로 명목형인 문제에 적용된다.\n# 희소한 사건이, 특징 값 사이에 매우 특정한 상호작용에서 발생한다 하더라도, 규칙 학습자는 희소 사건을 잘 식별함.\n\n# 클래스 값을 식별하는 점점 더 구체적인 규칙을 생성해 데이터를 드릴 다운한다.\n# 규칙이 데이터의 부분을 커버하는 것 같아 보이기 때문에, 분리 정복 알고리즘은 커버링 알고리즘이라고도 한다.\n\n# ZeroR -> 아무 규칙도 학습하지 않는 규칙 학습자(ex. 셋 중에 하나 뽑기)\n## 1R 알고리즘 -> 하나의 규칙을 선택하는 방식.\n # 각 특징에 대해 유사한 값으로 데이터를 그룹으로 분리한다.\n # 그 다음 알고리즘은 각 세그먼트에 대해 대다수 클래스를 예측한다.\n # 각 특징에 기반을 두는 규칙의 오류율을 계산하고, 최소 오류를 갖는 규칙을 단일 규칙으로 선정한다.\n# 1R 알고리즘은 너무 느리고, 잡음이 섞이면 쉽게 부정확해진다.\n\n# RIPPER 알고리즘으로 규칙 학습자를 만들자.\n# RIPPER 알고리즘의 3단계\n # 1. 기르기\n # 규칙에 조건을 탐욕스럽게 추가하기 위해 분할 정복 기법 사용\n # 데이터의 부분집합을 완벽하게 분류하거나, 분할을 위한 속성이 없어질 때까지 진행\n # 정보 획득량 기준 사용 -> 규칙이 더 정교햐져도 엔트로피가 줄지 않으면, 그 규칙은 가지치기된다.\n #\n# 탐욕스러운 학습자 -> 선입 선처리 기반으로 데이터 사용\n # -> 한 번에 하나의 파티션을 만들고자 함. 먼저 가장 동질적인 파티션을 찾고 난 후에 차선을 찾고\n # -> 모든 예시가 다 분류될 때까지 계속해서 찾는다.\n # 단점 : 특정 데이터셋에 최적이고, 가장 정확하고, 최소 개수로 된 규칙을 생성한다는 보장이 없음\n # -> 데이터의 한 부분집합에 대해 정확한 한 개의 규칙은 계속해서 찾아낼 수 있지만\n # -> 전체 데이터셋에 대해 더 나은 전반적인 정확도를 갖는 좀 더 섬세한 규칙들을 개발할 기회 잃게 됨.\n\n# 트리와 규칙 모두 탐욕 학습 휴리스틱 사용. 차이는\n # 트리는 이전 결정의 이력에 의해 영원히 제한된다.\n # 규칙은 규칙의 모든 조건으로 커버되지 않는 어떤 예시든 다음 규칙에 의해 재정복 가능.\n\n## Example: Identifying Poisonous Mushrooms ----\n## Step 2: Exploring and preparing the data ---- \nmushrooms <- read.csv(\"mushrooms.csv\", stringsAsFactors = TRUE)\n\n# examine the structure of the data frame\nstr(mushrooms)\n\n# drop the veil_type feature(범주인데 하나밖에 없음 ->쓸모도없다)\nmushrooms$veil_type <- NULL\n\n# examine the class distribution\ntable(mushrooms$type)\n\n## Step 3: Training a model on the data ----\nlibrary(RWeka) # JAVA 설치 필요\n\n# train OneR() on the data\nmushroom_1R <- OneR(type ~ ., data = mushrooms) # 1R 만들어내는 함ㅅ\n# 규칙 학습자가 type ~. 을 통해 모든 특징을 고려하도록 만듦\n\n\n## Step 4: Evaluating model performance ----\nmushroom_1R\nsummary(mushroom_1R)\n\n## Step 5: Improving model performance ---- # RIPPER 규칙 사용\nmushroom_JRip <- JRip(type ~ ., data = mushrooms)\nmushroom_JRip # 전체 9개의 규칙(if-else문)을 학습함.\nsummary(mushroom_JRip)\n\n# Rule Learner Using C5.0 Decision Trees (not in text)\nlibrary(C50)\nmushroom_c5rules <- C5.0(type ~ odor + gill_size, data = mushrooms, rules = TRUE)\nsummary(mushroom_c5rules)\n", "meta": {"hexsha": "9c25ebebe54e06c0a1820fe9c3d86076fba676c8", "size": 8175, "ext": "r", "lang": "R", "max_stars_repo_path": "MLwR/Chapter 05/MLwR_v2_05(Tree,RuleBased).r", "max_stars_repo_name": "BeginnerJay/R_STUDYING", "max_stars_repo_head_hexsha": "4dcca5a781cf550c8c40edc636c247357c95a296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MLwR/Chapter 05/MLwR_v2_05(Tree,RuleBased).r", "max_issues_repo_name": "BeginnerJay/R_STUDYING", "max_issues_repo_head_hexsha": "4dcca5a781cf550c8c40edc636c247357c95a296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MLwR/Chapter 05/MLwR_v2_05(Tree,RuleBased).r", "max_forks_repo_name": "BeginnerJay/R_STUDYING", "max_forks_repo_head_hexsha": "4dcca5a781cf550c8c40edc636c247357c95a296", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5697211155, "max_line_length": 82, "alphanum_fraction": 0.6835474006, "num_tokens": 4657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7200157498588156}} {"text": "#' winddir\n#'\n#' @description Calculate meteorological wind direction from cartesian components u and v.\n#' \n#' @param u numeric U zonal component \n#' @param v numeric V meridian component \n#' \n#' @references \n#' Istituto di Biometeorologia Firenze Italy\n#' @author Alfonso crisci \\email{a.crisci@@ibimet.cnr.it} Marco Morabito \\email{m.morabito@@unifi.it} \n#' @keywords Meteorological Wind direction \n#' \n#' \n#' @export\n\nwinddir <- function(u, v) {\n (180 / pi) * atan(u/v) + ifelse(v>0,180,ifelse(u>0,360,0))\n}", "meta": {"hexsha": "5dcff31782078e17ce894c018c1113aa3a94461e", "size": 531, "ext": "r", "lang": "R", "max_stars_repo_path": "R/winddir.r", "max_stars_repo_name": "alfcrisci/biometeoR", "max_stars_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:46.000Z", "max_issues_repo_path": "R/winddir.r", "max_issues_repo_name": "alfcrisci/biometeoR", "max_issues_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/winddir.r", "max_forks_repo_name": "alfcrisci/biometeoR", "max_forks_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5, "max_line_length": 103, "alphanum_fraction": 0.670433145, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7199640028368233}} {"text": "library(\"magrittr\")\na <- 0.88\nb <- 1.55\n\ncostA <- function(lambda){\n\treturn(160 + (40 * (lambda + lambda^2)))\n}\n\ncostB <- function(lambda){\n\treturn(128 + (40 * (lambda + lambda^2)))\n}\n\nansa <- costA(a) #226.176\nansb <- costB(b) #286.1\ncat(sprintf(\"%.3f\\n\", ansa))\ncat(sprintf(\"%.3f\\n\", ansb))\n\ncat(round(ansa,3),'\\n')\ncat(round(ansb,3))\n\n#simulation:\nn <- 10^8\nasim <- rpois(n = n, lambda = a) \nbsim <- rpois(n = n, lambda = b)\n\namax <- asim %>% max\nbmax <- bsim %>% max\n\n\n\ncalc <- function(v, max){\n\tzeroToN = c()\n\tfor(i in 0:max)\n\t{\n\t\tbool <- ifelse(v == i, 1, 0)\n\t\tproportionI <- sum(bool)/n\n\t\tzeroToN = c(zeroToN, proportionI) \n\t}\n\treturn(zeroToN)\n}\n\ncosta <- function(X){\n\treturn(160 + (40 * X^2))\n}\ncostb <- function(Y){\n\treturn(128 + (40 * Y^2))\n}\n\n#apply cost functions to random variables x and y\n\nacost <- sapply(X = asim, FUN = costa)\nbcost <- sapply(X = bsim, FUN = costb) \n\nsum(acost)/n\nsum(bcost)/n\n\naans <- acost %>% sum()/n\nbans <- bcost %>% sum()/n\ncat(aans, \"\\n\")\ncat(bans)\n", "meta": {"hexsha": "6c727feebacc7eb55f3cdfd5d5373d6425aa23eb", "size": 993, "ext": "r", "lang": "R", "max_stars_repo_path": "HackerRankPoissonDistribution2.r", "max_stars_repo_name": "DU-ds/MiscRScripts", "max_stars_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HackerRankPoissonDistribution2.r", "max_issues_repo_name": "DU-ds/MiscRScripts", "max_issues_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HackerRankPoissonDistribution2.r", "max_forks_repo_name": "DU-ds/MiscRScripts", "max_forks_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2786885246, "max_line_length": 49, "alphanum_fraction": 0.583081571, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7199290870145244}} {"text": "require(Rdonlp2)\n\nfactors <- c(\n 0.02040000,-0.08672903,0.06208421,0.08537144,\n 0.08530000,0.01567469,0.08519883,0.13293438,\n 0.02570000,-0.03997748,0.04657237,0.04977169,\n 0.00760000,0.04163002,-0.00568537,-0.02547824,\n 0.04540000,0.11255746,0.05319682,0.04129890,\n -0.01830000,0.00805313,-0.00421743,-0.05443995,\n -0.03520000,-0.08656963,-0.05054419,-0.01769600,\n 0.07920000,0.16539408,0.05479713,0.06737632,\n 0.03190000,0.02451794,0.02632593,0.01820807,\n 0.07870000,0.05045111,0.07801389,0.09820405,\n 0.02140000,0.02911620,0.00553052,0.03437993,\n 0.08920000,0.16132008,0.09959438,0.09472788,\n -0.02850000,-0.02864671,-0.03634867,-0.04231819,\n 0.02810000,0.02976673,0.03965725,0.04903749,\n 0.08810000,0.07181523,0.07879099,0.06418204,\n 0.09070000,0.11896197,0.07516213,0.11833781,\n -0.02310000,-0.07499952,-0.00807299,-0.02992491,\n 0.06940000,0.09002753,0.09137129,0.09216098,\n 0.02640000,0.08124712,0.02024337,0.02541702,\n -0.04460000,0.01855777,-0.04992867,-0.04843952,\n 0.01530000,0.10141779,0.02720172,0.05258464,\n -0.00860000,-0.04908988,-0.00546264,-0.03273162,\n 0.05120000,0.05606888,0.08323532,0.08211691,\n 0.02090000,0.00249315,0.02060449,-0.00069403,\n 0.05400000,0.03418127,0.05196274,0.04239199\n)\n\nfactors <- matrix(data=factors, nrow=25, ncol=4, byrow=TRUE)\n\nfund_returns <- c(\n 0.07950000,\n 0.11440000,\n 0.04550000,\n 0.01010000,\n 0.03350000,\n -0.01470000,\n -0.02160000,\n 0.07120000,\n 0.02200000,\n 0.08970000,\n 0.02530000,\n 0.04560000,\n -0.01980000,\n 0.03100000,\n 0.06020000,\n 0.08530000,\n 0.00640000,\n 0.05500000,\n 0.02920000,\n -0.02150000,\n 0.00160000,\n 0.00830000,\n 0.04780000,\n 0.02280000,\n 0.04110000 \n)\n\nobjective <- function(weights) {\n\n # ASSERT: ncol(factors) == length(weights)\n \n # calculate the sum product of factors and weights\n sum_product <- factors %*% matrix(weights, ncol=1)\n sum_product_return <- cbind(sum_product, fund_returns)\n residuals <- sum_product_return[, 2] - sum_product_return[, 1]\n \n # ASSERT: nrow(factors) == length(residuals)\n \n # calculate (and return) the stdev of the residuals\n sd(residuals)\n}\n\nweights <- c(0.25, 0.25, 0.25, 0.25) # start weights\n\n# weight constraints\nweights.lower <- c(0, 0, 0, 0) # >= 0\nweights.upper <- c(1, 1, 1, 1) # <= 1\n\n# equality constraints\neqFun <- list(\n function(x) sum(x)\n)\neqFun.bound <- c(1)\n\n# note: no need for inequality and non-linear constraints\n\nx1 <- donlp2NLP( \n par = weights,\n par.lower = weights.lower,\n par.upper = weights.upper,\n fun = objective,\n eqFun = eqFun,\n eqFun.bound = eqFun.bound\n)\n\n#str(x1)\n\nfound_weights = x1$par\n\n\n# sanity check\nif (sum(found_weights) > 1.00000000000001 || sum(found_weights) < 1) \n cat('FAILED: Sum(W) = ', sum(found_weights), '\\n')\n\nif (sum(abs(found_weights)) > 1.00000000000001 || sum(abs(found_weights)) < 1) \n cat('FAILED: Sum(Abs(W)) = ', sum(abs(found_weights)), '\\n')\n\nif(any(found_weights < 0) || any(found_weights > 1))\n cat('FAILED: One or more factor weight <0 or >1\\n')\n\n# print out weights....\ncat(found_weights[1], '\\t', found_weights[2],'\\t', found_weights[3],'\\t', found_weights[4], '\\n')\n\n", "meta": {"hexsha": "9600b624a447e37e59bd6b3cd8720eaeb276a1db", "size": 3129, "ext": "r", "lang": "R", "max_stars_repo_path": "r-example/rdonlp2-optimizer.r", "max_stars_repo_name": "virtualstaticvoid/optimizer", "max_stars_repo_head_hexsha": "f9704d17e5d6dc322bcbfa0b33ffbcfae1244ca6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-30T18:34:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-30T18:34:15.000Z", "max_issues_repo_path": "r-example/rdonlp2-optimizer.r", "max_issues_repo_name": "virtualstaticvoid/optimizer", "max_issues_repo_head_hexsha": "f9704d17e5d6dc322bcbfa0b33ffbcfae1244ca6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r-example/rdonlp2-optimizer.r", "max_forks_repo_name": "virtualstaticvoid/optimizer", "max_forks_repo_head_hexsha": "f9704d17e5d6dc322bcbfa0b33ffbcfae1244ca6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7435897436, "max_line_length": 97, "alphanum_fraction": 0.6880792585, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7199011584545352}} {"text": "# R code for chapter 5 of Wood (2006) \"GAMs: An Introduction with R\"\n\n## 5.1 Cherry trees again\n\nlibrary(mgcv)\ndata(trees)\nct1<-gam(Volume~s(Height)+s(Girth),\n family=Gamma(link=log),data=trees)\nct1\npar(mfrow=c(1,2))\nplot(ct1,residuals=TRUE)\n\n## 5.1.1 Finer control of gam\n\nct2 <- gam(Volume~s(Height,bs=\"cr\")+s(Girth,bs=\"cr\"),\n family=Gamma(link=log),data=trees)\nct2\npar(mfrow=c(2,2))\nplot(ct1,residuals=TRUE)\nplot(ct2,residuals=TRUE)\n\nct3 <- gam(Volume ~ s(Height)+s(Girth,bs=\"cr\",k=20),\n family=Gamma(link=log),data=trees)\nct3\n\nct4 <- gam(Volume ~ s(Height) + s(Girth),\n family=Gamma(link=log),data=trees,gamma=1.4)\nct4\npar(mfrow=c(2,2))\nplot(ct1,residuals=TRUE)\nplot(ct4,residuals=TRUE)\n\n## 5.1.2 Smooths of several variables\n\nct5 <- gam(Volume ~ s(Height,Girth,k=25),\n family=Gamma(link=log),data=trees)\nct5\nplot(ct5,too.far=0.15)\n\nct6 <- gam(Volume ~ te(Height,Girth,k=5),\n family=Gamma(link=log),data=trees)\nct6\nplot(ct6,too.far=0.15)\n\n## 5.1.3 Parametric model terms\n\ngam(Volume~Height+s(Girth),family=Gamma(link=log),data=trees)\ntrees$Hclass <- factor(floor(trees$Height/10)-5,\n labels=c(\"small\",\"medium\",\"large\"))\n\nct7 <- gam(Volume ~ Hclass+s(Girth),\n family=Gamma(link=log),data=trees)\npar(mfrow=c(1,2))\nplot(ct7,all.terms=T)\n\nanova(ct7)\nAIC(ct7)\nsummary(ct7)\n\n## 5.2 Brain imaging example\n## 5.2.1 Preliminary modeling\nlibrary(gamair)\ndata(brain)\nbrain\n\n## Each row corresponds to one voxel\n\nbrain <- brain[brain$medFPQ>=3e-5,] # exclude 2 outliers\nm0 <- gam(medFPQ~s(Y,X,k=100),data=brain)\ngam.check(m0) \n\ne <- residuals(m0); fv <- fitted(m0)\nlm(log(e^2)~log(fv))\n\nm1<-gam(medFPQ^.25~s(Y,X,k=100),data=brain)\ngam.check(m1)\n\nm2<-gam(medFPQ~s(Y,X,k=100),data=brain,family=Gamma(link=log),optimizer=\"perf\")\n\nmean(fitted(m1)^4);mean(fitted(m2));mean(brain$medFPQ)\nm2\n\nvis.gam(m2,plot.type=\"contour\",too.far=0.03,\n color=\"gray\",n.grid=60,zlim=c(-1,2),main=\"model m2 image plot and overlaid contours on scale of linear predictor\")\n\n## 5.2.2 Would an additive structure be better?\nm3 <- gam(medFPQ~s(Y,k=30)+s(X,k=30),data=brain,\n family=Gamma(link=log),optimizer=\"perf\")\nm3\nsummary(m2)\nsummary(m3)\n# Compare models m2 and m3\nanova(m3,m2,test=\"F\")\n\nm4 <- gam(medFPQ~s(Y,k=30)+s(X,k=30)+s(Y,X,k=100),data=brain,\n family=Gamma(link=log),optimizer=\"perf\")\n\n## 5.2.3 Isotropic or tensor product smooths?\n\ntm<-gam(medFPQ~te(Y,X,k=10),data=brain,family=Gamma(link=log),\n optimizer=\"perf\")\ntm1<-gam(medFPQ~s(Y,k=10,bs=\"cr\")+s(X,bs=\"cr\",k=10),\n data=brain,family=Gamma(link=log),optimizer=\"perf\")\n\ntm1\ntm\nanova(tm1,tm,test=\"F\")\n\n## So we plot them again\nvis.gam(tm1,plot.type=\"contour\",too.far=0.03,\n color=\"gray\",n.grid=60,zlim=c(-1,2),main=\"model tm1 image plot and overlaid contours\")\n\nvis.gam(tm,plot.type=\"contour\",too.far=0.03,\n color=\"gray\",n.grid=60,zlim=c(-1,2),main=\"model tm image plot and overlaid contours\")\n\n## 5.3 Air pollution in Chicago example\nlibrary(mgcv)\nlibrary(gamair)\ndata(chicago)\nap0 <- gam(death~s(time,bs=\"cr\",k=200)+pm10median+so2median+\n o3median+tmpd,data=chicago,family=poisson)\ngam.check(ap0)\n\npar(mfrow=c(2,1))\nplot(ap0,n=1000) # n increased to make plot smooth\nplot(ap0,residuals=TRUE,n=1000)\n\nchicago$death[3111:3123]\n\nap1<-gam(death~s(time,bs=\"cr\",k=200)+s(pm10median,bs=\"cr\")+\n s(so2median,bs=\"cr\")+s(o3median,bs=\"cr\")+s(tmpd,bs=\"cr\"),\n data=chicago,family=poisson)\ngam.check(ap1)\n\npar(mfrow=c(3,2))\nplot(ap1,n=1000)\n\nlag.sum <- function(a,l0,l1)\n## l0 is the smallest lag, l1 the largest\n{ n<-length(a)\n b<-rep(0,n-l1)\n for (i in 0:(l1-l0)) b <- b + a[(i+1):(n-l1+i)]\n b\n}\ndeath<-chicago$death[4:5114]\ntime<-chicago$time[4:5114]\no3 <- lag.sum(chicago$o3median,0,3)\ntmp <- lag.sum(chicago$tmpd,0,3)\npm10 <- lag.sum(log(chicago$pm10median+40),0,3)\nso2 <- lag.sum(log(chicago$so2median+10),0,3)\n\nap2 <- gam(death ~ s(time,bs=\"cr\",k=200) +\n te(o3,tmp,pm10,k=c(8,8,6)),family=poisson)\ngam.check(ap2)\n\nap3 <- gam(death ~ s(time,bs=\"cr\",k=200) + te(o3,tmp,k=8) +\n s(pm10,bs=\"cr\",k=6),family=poisson)\npar(mfrow=c(3,1))\nplot(ap3)\n\n## 5.6.1 Package 'gam' (note need to run chicago pre-proc first)\n\ndetach(package:mgcv) \nlibrary(gam)\ninstall.packages(\"akima\")\nlibrary(akima) # needed for plotting\nbfm <- gam(death~s(time,df=140)+lo(o3,tmp,span=.1),\n family=poisson,control=gam.control(bf.maxit=150))\nsummary(bfm)\n\n## 5.6.2 Package 'gss'\ninstall.packages(\"gss\")\nlibrary(gss)\nssm <- gssanova1(death~time+o3*tmp,family=\"poisson\",nbasis=200)\n\nsummary(ssm)\n\ntp <- seq(min(time),max(time),length=500)\nfvt <- predict(ssm,newdata=data.frame(time=tp,\n o3=rep(mean(o3),500),tmp=rep(mean(tmp),500)),\n include=list(\"time\"))\nplot(tp,fvt,type=\"l\",xlab=\"time\",ylab=\"time effect\")\n\nm <- 40\no3m <- seq(min(o3),max(o3),length=m)\ntmpm <- seq(min(tmp),max(tmp),length=m)\ntmpp <- rep(tmpm,rep(m,m))\no3p <- rep(o3m,m)\npd <- data.frame(time=rep(0,m*m),o3=o3p,tmp=tmpp)\nfv <- predict(ssm,newdata=pd,include=list(\"o3\",\"tmp\",\"o3:tmp\"))\nlibrary(mgcv)\nind <- exclude.too.far(o3p,tmpp,o3,tmp,dist=0.04)\nfv[ind] <- 0\npersp(o3m,tmpm,matrix(fv,m,m),phi=30,theta=-30,zlab=\"o3*tmp\",\n xlab=\"o3\",ylab=\"tmp\")\n", "meta": {"hexsha": "b80fbab40dc4c508b5efd9bb30aa5a59b0199ed7", "size": 5234, "ext": "r", "lang": "R", "max_stars_repo_path": "Linear Regression GLMs and GAMs with R/scripts/Ch-5-Day-4.r", "max_stars_repo_name": "EdwardHill15/Udemy_GAM", "max_stars_repo_head_hexsha": "e31e1b95e84f5867c8d47705fb75c4a4878772de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linear Regression GLMs and GAMs with R/scripts/Ch-5-Day-4.r", "max_issues_repo_name": "EdwardHill15/Udemy_GAM", "max_issues_repo_head_hexsha": "e31e1b95e84f5867c8d47705fb75c4a4878772de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Linear Regression GLMs and GAMs with R/scripts/Ch-5-Day-4.r", "max_forks_repo_name": "EdwardHill15/Udemy_GAM", "max_forks_repo_head_hexsha": "e31e1b95e84f5867c8d47705fb75c4a4878772de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7040816327, "max_line_length": 122, "alphanum_fraction": 0.6555215896, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.7197697108025639}} {"text": "\n\n#Tratamientos\nA <- c(62,60,63,59)\nB <- c(63,67,71,64,65,66)\nC <- c(68,66,71,67,68,68)\nD <- c(56,62,60,61,63,64,63,59)\n\n#Tabla de resultados\nresultado <- c(A,B,C,D)\n\n\ndietas <- c(rep(\"A\",length(A)),\n rep(\"B\",length(B)),\n rep(\"C\",length(C)),\n rep(\"D\",length(D)))\n\nmisdatos <- data.frame(dietas,resultado)\n\nboxplot(resultado~dietas,misdatos, main=\"Tiempo de coagulación de la sangre segun dieta\", ylab=\"Tiempo (segundos)\")\n\n# ANOVA\nanova1 <- aov(resultado~dietas,misdatos)\nsummary(anova1)\n\n# global Effect and Treatment Effect\nmu.est <- mean(misdatos$resultado)\nmu.est\n#aplicar media por grupos\nmean_treatment <- aggregate(resultado~dietas,misdatos,mean)\nmean_treatment\n#diferencia media por gruposy media global\neffect_treatment <- aggregate(resultado~dietas,misdatos,function(x){mean(x)-mu.est})\nmu.est\neffect_treatment\n\n# Treatment Effect with a reference Level\nround(coefficients(anova1),2)\n\n# Changing Reference Level\nmisdatos$dietas <- relevel(misdatos$dietas,ref=\"B\")\nmisdatos$dietas\nanova1 <- aov(resultado~dietas,misdatos)\nsummary(anova1)\nround(coefficients(anova1),2)\n\n#================================================\n# DBCA\n#================================================\n res <- c(13,16,5,22,24,4,18,17,1,39,44,22)\n factor <- c(1,2,3,1,2,3,1,2,3,1,2,3)\n bloque <- c(1,1,1,2,2,2,3,3,3,4,4,4)\n \n midata <- data.frame(factor,bloque,res)\n\n length(res)\n length(factor)\n length(bloque)\n\n boxplot(res~factor,midata, main=\"Retardo en el crecimiento de bacterias\",\n ylab=\"Tiempo (segundos)\",\n xlab=\"Factor: Soluciones de lavado\")\n boxplot(res~bloque,midata, main=\"Retardo en el crecimiento de bacterias\",\n ylab=\"Tiempo (segundos)\",\n xlab=\"Bloques: Días\")\n\n # Interacciones\n interaction.plot(midata$factor,midata$bloque,midata$res,\n xlab=\"Factor: Soluciones de lavado\",\n ylab=\"Tiempo (segundos)\",\n leg.legend=\"Bloque\")\n\n #Opt1\n anova1 <- aov(res~as.factor(factor)+as.factor(bloque),midata)\n summary(anova1)\n\n #Opt2\n midata <- data.frame(factor=as.factor(factor),bloque=as.factor(bloque),res)\n anova1 <- aov(res~factor+bloque,midata)\n summary(anova1)\n\n # global Effect and Treatment Effect\n mu.est <- mean(midata$res)\n mean_treatment <- aggregate(res~factor,midata,mean)\n effect_treatment <- aggregate(res~factor,midata,function(x){mean(x)-mu.est})\n effect_block <- aggregate(res~bloque,midata,function(x){mean(x)-mu.est})\n mu.est\n effect_treatment\n effect_block\n\n #Effects with control treatment\n round(coefficients(anova1),4)\n", "meta": {"hexsha": "cabf8a5a3e1c9cba38ace73e6c9f323e1475fb90", "size": 2552, "ext": "r", "lang": "R", "max_stars_repo_path": "Final/Clases/codigo_clase11_1dietas.r", "max_stars_repo_name": "jchudb93/Exp-Numerica", "max_stars_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Final/Clases/codigo_clase11_1dietas.r", "max_issues_repo_name": "jchudb93/Exp-Numerica", "max_issues_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Final/Clases/codigo_clase11_1dietas.r", "max_forks_repo_name": "jchudb93/Exp-Numerica", "max_forks_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4408602151, "max_line_length": 115, "alphanum_fraction": 0.6661442006, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807406, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7197330361473674}} {"text": "# Rate of return data\n\n#########################################################################\n# Get CSV of return data\np <- read.csv(\"jstdatasetr4.csv\", header=TRUE)\n\n#########################################################################\n# Calculate returns\n#########################################################################\np <- # create lagged CPI\n p %>%\n group_by(iso) %>%\n mutate(lag.cpi = dplyr::lag(cpi, n = 1, default = NA))\np$inf <- (p$cpi - p$lag.cpi)/p$lag.cpi # inflation\np$housing_real <- (1+p$housing_tr)/(1+p$inf) - 1 # housing return\np$eq_real <- (1+p$eq_tr)/(1+p$inf) - 1 # equities\np$safe_real <- (1+p$safe_tr)/(1+p$inf) - 1 # safe assets\np$risky_real <- (1+p$risky_tr)/(1+p$inf) - 1 # risky assets\np$capital_real <- (1+p$capital_tr)/(1+p$inf) - 1 # capital in total\n\n# Lagged values\np <- p %>% group_by(iso) %>% mutate(lag1.capital_real = dplyr::lag(capital_real, n = 1, default = NA))\np <- p %>% group_by(iso) %>% mutate(lag2.capital_real = dplyr::lag(capital_real, n = 2, default = NA))\np <- p %>% group_by(iso) %>% mutate(lag3.capital_real = dplyr::lag(capital_real, n = 3, default = NA))\np <- p %>% group_by(iso) %>% mutate(lag4.capital_real = dplyr::lag(capital_real, n = 4, default = NA))\np <- p %>% group_by(iso) %>% mutate(lag5.capital_real = dplyr::lag(capital_real, n = 5, default = NA))\n\n# 5-year moving average\np$ma5.capital_real = round(((1+p$lag4.capital_real)*(1+p$lag3.capital_real)*(1+p$lag2.capital_real)*(1+p$lag1.capital_real)*(1+p$capital_real))^(1/5) - 1,digits=2)\n\n# Subset of countries and time period\nstable <- p[ which(p$iso %in% c(\"USA\", \"DEU\", \"JPN\", \"GBR\", \"AUS\")),]\nstable <- stable[which(p$year > 1949),]\n\n#########################################################################\n# Figure of 5-year rates of return\n#########################################################################\nfig <- plot_ly(stable, x = ~year, y = ~ma5.capital_real, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Return to capital over time', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = '5-year annualized return',range = c(-.1,.2)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"jst-stable-return\")\n", "meta": {"hexsha": "778f0fe2a64805d43ce7d9c4c20f65849c733610", "size": 2262, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Guide_JST_Facts.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/Guide_JST_Facts.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Guide_JST_Facts.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 51.4090909091, "max_line_length": 163, "alphanum_fraction": 0.5318302387, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7195947252538849}} {"text": "x = c(-1, 0, 3, 7)\ny = c(2, 0, 4, 7)\n\nn = length(x)\n\nnum = sum(x * y) - sum(x) * sum(y) / n\nden = sum(x * x) - sum(x) * sum(x) / n\n\nB1 = num / den\nB0 = (sum(y) - (B1 * sum(x))) / n\n\npng('images/disp_diagram.png')\n\nplot(x, y)\n\ndev.off()\n\nB0\nB1\n\nprint('For x = 1 predicted value is')\nprint(B1 * 1 + B0)", "meta": {"hexsha": "cd1c33a2cebd5b29f80f3ba00331b939183e21a3", "size": 300, "ext": "r", "lang": "R", "max_stars_repo_path": "Tasks/CP6-Ex1/CP6-Ex1.r", "max_stars_repo_name": "2kodevs/Statistics-Tasks", "max_stars_repo_head_hexsha": "264dc6287c9a2d1b7118fd48c40f54e26fc18b42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tasks/CP6-Ex1/CP6-Ex1.r", "max_issues_repo_name": "2kodevs/Statistics-Tasks", "max_issues_repo_head_hexsha": "264dc6287c9a2d1b7118fd48c40f54e26fc18b42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-04-09T14:27:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-16T18:31:14.000Z", "max_forks_repo_path": "Tasks/CP6-Ex1/CP6-Ex1.r", "max_forks_repo_name": "2kodevs/Statistics-Tasks", "max_forks_repo_head_hexsha": "264dc6287c9a2d1b7118fd48c40f54e26fc18b42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.6363636364, "max_line_length": 38, "alphanum_fraction": 0.5033333333, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7195885748374766}} {"text": "# Estat�stica B�sica\n\n# Exerc�cio\n\n# Cuidado: A Linguagem R � case sensitive!\n\n# Definindo a pasta de trabalho\n# Substitua o caminho abaixo pela pasta no seu computador\nsetwd(\"C:/Users/dmpm/Documents/PowerBI/Cap12\")\ngetwd()\n\n# Carregando o dataset\nnotas <- read.csv(\"Notas.csv\", fileEncoding = \"windows-1252\")\n\n# Exerc�cio 1: Apresente um resumo de tipos de dados e estat�sticas do dataset.\nView(notas)\nstr(notas)\nsummary(notas$TurmaA)\nsummary(notas$TurmaB)\n\n# Exerc�cio 2: Qual a m�dia de cada turma?\nmean(notas$TurmaA)\nmean(notas$TurmaB)\n\n# Exerc�cio 3: Qual turma apresentou maior variabilidade de notas? Justifique sua resposta.\nsd(notas$TurmaA)\nsd(notas$TurmaB)\n\n# Exerc�cio 4 - Calcule o coeficiente de varia��o das 2 turmas.\nmedia_ta <- mean(notas$TurmaA)\nmedia_tb <- mean(notas$TurmaB)\n\nsd_ta <- sd(notas$TurmaA)\nsd_tb <- sd(notas$TurmaB)\n\ncvA <- sd_ta / media_ta * 100\ncvB <- sd_tb / media_tb * 100\n\ncvA\ncvB\n\n# Exerc�cio 5 - Qual nota apareceu mais vezes em cada turma?\ncalculaModa <- function(v) {\n uniqv <- unique(v)\n uniqv[which.max(tabulate(match(v, uniqv)))]\n}\n\ncalculaModa(notas$TurmaA)\ncalculaModa(notas$TurmaB)\n\n", "meta": {"hexsha": "affa9a5ecfdd251a0b5d48e0180a54db52f9ac23", "size": 1131, "ext": "r", "lang": "R", "max_stars_repo_path": "DSA_Projects/exercicio.r", "max_stars_repo_name": "MaltaIgor/R", "max_stars_repo_head_hexsha": "dd063738e22110c32474063696a389b17c24680d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DSA_Projects/exercicio.r", "max_issues_repo_name": "MaltaIgor/R", "max_issues_repo_head_hexsha": "dd063738e22110c32474063696a389b17c24680d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DSA_Projects/exercicio.r", "max_forks_repo_name": "MaltaIgor/R", "max_forks_repo_head_hexsha": "dd063738e22110c32474063696a389b17c24680d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1764705882, "max_line_length": 91, "alphanum_fraction": 0.7303271441, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7193838673233118}} {"text": " ZGELS Example Program Results\n\n Least squares solution\n (-0.5044,-1.2179) (-2.4281, 2.8574) ( 1.4872,-2.1955) ( 0.4537, 2.6904)\n\n Square root of the residual sum of squares\n 6.88E-02\n", "meta": {"hexsha": "ff521550752fce74e8a81e3fe414a9b737f40498", "size": 186, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/zgels_example.r", "max_stars_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_stars_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-01-28T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:26:43.000Z", "max_issues_repo_path": "examples/baseresults/zgels_example.r", "max_issues_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_issues_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/baseresults/zgels_example.r", "max_forks_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_forks_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-04-19T12:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:32:12.000Z", "avg_line_length": 23.25, "max_line_length": 72, "alphanum_fraction": 0.6827956989, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7193090786779321}} {"text": "library(MASS)\ngetPriorProbabilities <- function (dset, column) {\n dsetLength <- dim(dset)[1]\n return (table(dset[, column]) / dsetLength)\n}\n\nlikelihood <- function(feature, expectation, deviation) {\n return ((1 / (deviation * sqrt(2 * pi))) * exp(-((feature - expectation) ^ 2) / (2 * deviation ^ 2)))\n}\n\n# returns a probability of a given point to be in a given class\ngetProbability <- function(dset, classesColumn, className, point, lambda) {\n classesCount <- 0\n featuresCount <- length(point)\n dsetLength <- dim(dset)[1]\n \n prior <- getPriorProbabilities(dset, classesColumn)[className]\n # lambda <- 1 # rep(1, classesCount)\n \n expectations <- array(dim = featuresCount)\n for (i in 1:featuresCount) {\n expectations[i] <- mean(dset[which(dset[, classesColumn] == className), i])\n }\n \n matr <- matrix(0, featuresCount, featuresCount)\n for (i in 1:featuresCount) {\n matr[i, ] <- sum((dset[which(dset[, classesColumn] == className), i] - expectations[i]) ^ 2) / dsetLength\n }\n deviations <- array(dim = featuresCount)\n for (i in 1:featuresCount) {\n deviations[i] <- matr[i, i]\n }\n \n # print(log(lambda * prior))\n # print(expectations)\n # print('separator')\n # print(featuresCount)\n # print(deviations)\n # print(lambda * prior)\n # print(sum(log(likelihood(point, expectations, deviations))))\n \n logOfLikelihood <- sum(log(likelihood(point, expectations, deviations)))\n \n return (log(lambda * prior) + logOfLikelihood)\n}\n\nclassify <- function(point, lambdas) {\n classes <- unique(dset[, 3])\n classesCount <- length(classes)\n scores <- array(dim = classesCount)\n for (i in 1:classesCount) {\n scores[i] <- getProbability(dset, 3, classes[i], point, lambdas[i])\n }\n return(classes[which.max(scores)])\n}\n\nmu1 <- c(0, 0)\nmu2 <- c(4, 4)\nsig1 <- matrix(c(2, 0.9, 0.9, 2), 2, 2)\nsig2 <- matrix(c(0.5, 0, 0, 2), 2, 2)\ndset1 <- mvrnorm(250, mu1, sig1)\ndset2 <- mvrnorm(250, mu2, sig2)\ndset <- rbind(cbind(dset1, 1),cbind(dset2, 2))\nplot(dset[ ,1], dset[ ,2], pch=21, bg=c(\"green\",\"blue\")[dset[ ,3]])\n\n\n# generating map\ncolors <- c(\"1\" = \"green\", \"2\" = \"blue\")\nxs <- seq(from = -5, to = 6.2, by = 0.1)\nys <- seq(from = -4.2, to = 8, by = 0.1)\nlambdas <- runif(2, min=1, max=100)\nprint(lambdas)\n\nall <- length(xs) * length(ys)\nprogress = 1\nfor (i in xs) {\n for (j in ys) {\n cat(\"\\rProcessing point\", progress, \"of\", all)\n progress <- progress + 1\n result <- classify(c(i, j), lambdas)\n points(i, j, col = colors[result], pch = 21)\n }\n}\ncat(\"\\rDone. \\n\")\n\n", "meta": {"hexsha": "386d73b67b1c1cb96b21ccbd2cde40af3965df56", "size": 2525, "ext": "r", "lang": "R", "max_stars_repo_path": "6 - Naive Bayes Classifier/naive-bayes.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "6 - Naive Bayes Classifier/naive-bayes.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6 - Naive Bayes Classifier/naive-bayes.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3604651163, "max_line_length": 109, "alphanum_fraction": 0.6269306931, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.7191124907094654}} {"text": "#' Numeric correlation\n#'\n#' @description Compute pearson, kendall and spearman correlation coefficient\n#'\n#' @param x numeric vector\n#' @param y numeric vector\n#'\n#'\n#' @return Numeric vector\n#' @export\n#'\n#' @examples\n#'\n#' x <- rnorm(100)\n#'\n#' y <- rnorm(100)\n#'\n#' plot(x,y)\n#'\n#' num_corr(x,y)\n#'\n#'\n\nnum_corr <- function(x,y){\n\n if(is.numeric(x) == F){\n stop(\"x must be numeric\")\n }\n\n if(is.numeric(y) == F){\n stop(\"y must be numeric\")\n }\n\n out <-\n dplyr::tibble(\n pearson = cor.test(x,y,method = \"pearson\",na.rm = T)$estimate,\n kendall = cor.test(x,y,method = \"kendall\",na.rm = T)$estimate,\n spearman = cor.test(x,y,method = \"spearman\",na.rm = T)$estimate\n )\n\n return(out)\n\n}\n", "meta": {"hexsha": "3826f88ad8f4f8c60acafadbb11c24f760409aa1", "size": 712, "ext": "r", "lang": "R", "max_stars_repo_path": "R/num_corr.r", "max_stars_repo_name": "larissabf/relper", "max_stars_repo_head_hexsha": "fc6ed8006190fdb829ebbf8b2f24b3c8ef39c3a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/num_corr.r", "max_issues_repo_name": "larissabf/relper", "max_issues_repo_head_hexsha": "fc6ed8006190fdb829ebbf8b2f24b3c8ef39c3a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/num_corr.r", "max_forks_repo_name": "larissabf/relper", "max_forks_repo_head_hexsha": "fc6ed8006190fdb829ebbf8b2f24b3c8ef39c3a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.1818181818, "max_line_length": 77, "alphanum_fraction": 0.5884831461, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7190924810612875}} {"text": "##### 医学統計勉強会18 第4回 回帰分析 R code #####\n\ninstall.packages(\"ISwR\")\t# ISwRパッケージのインストール。最初の一回のみ実行\nlibrary(ISwR)\n\n# 散布図 #\nthuesen <- na.omit(thuesen)\t# 欠測値を除く #\nattach(thuesen)\n\nplot(blood.glucose, short.velocity)\nplot(thuesen)\t\t\t# 上と同じ\n\n# 数量的データの要約(二変量) #\ncov(blood.glucose, short.velocity)\t\t# 共分散\ncov(thuesen)\t\t\t\t# 分散共分散行列\ncor(blood.glucose, short.velocity)\t\t# 相関係数\ncor(thuesen)\t\t\t\t# 相関行列\n\n# 単回帰分析 #\nfit <- lm(short.velocity ~ blood.glucose, data=thuesen)\nsummary(fit)\t\t# 回帰分析の結果表示\nplot(thuesen)\t\t# 散布図\nabline(fit)\t\t\t# 推定された回帰直線の描画\nconfint(fit)\t\t# 回帰パラメターの信頼区間\n\n# 回帰診断 #\npar(mfrow=c(2,2))\nplot(fit)\npar(mfrow=c(1,1))\n\n# 重回帰 (CPUデータ) #\nlibrary(MASS)\nhead(cpus, n=2)\ndim(cpus)\t\t\t# cpusの行と列の数を確認\n?cpus\t\t\t\t# cpusのオンラインヘルプ起動\n\ncpus2 <- cpus[, c(8, 2:7)]\nhead(cpus2, n=2)\n\npairs(cpus2)\t\t# cpus2の散布図行列\n\ncpus2.lm <- lm(perf ~ syct + mmin + mmax + cach + chmin + chmax, data=cpus2)\t\t\t\t# 回帰モデルの当てはめ\ncpus2.lm <- lm(perf ~ ., data=cpus2)\t# 上と同じ\n\nsummary(cpus2.lm)\t# 回帰分析の結果表示\nconfint(cpus2.lm)\t# 回帰パラメターの信頼区間\n\n# 回帰診断 #\npar(mfrow=c(2,2))\t# グラフィックスウィンドウを2行2列の4つの領域に分割する\nplot(cpus2.lm)\npar(mfrow=c(1,1))\t# グラフィックスウィンドウを元に戻す\n\n# Box-Cox変換 #\nlibrary(MASS)\nbxcx <- boxcox(perf ~ ., data=cpus2, lambda=seq(0, 0.5, .01))\nlambda <- bxcx$x[which.max(bxcx$y)]\nlambda\n\nperf.new <- (cpus2$perf^lambda -1)/lambda\ncpus3 <- cpus2[, -1]\ncpus3 <- cbind.data.frame(perf.new, cpus3)\n\ncpus2.bxcx.lm <- lm(perf.new ~ ., data=cpus3)\nsummary(cpus2.bxcx.lm)\t# 回帰分析の結果表示\nconfint(cpus2.bxcx.lm)\t# 回帰パラメターの信頼区間\n\n# 回帰診断 #\npar(mfrow=c(2,2))\t# グラフィックスウィンドウを2行2列の4つの領域に分割する\nplot(cpus2.bxcx.lm)\npar(mfrow=c(1,1))\t# グラフィックスウィンドウを元に戻す", "meta": {"hexsha": "970e7cd75298628410e53fbef501a0c804c5605c", "size": 1581, "ext": "r", "lang": "R", "max_stars_repo_path": "MedicalStatisticsClass/2019/4/code.r", "max_stars_repo_name": "shumez/stat", "max_stars_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MedicalStatisticsClass/2019/4/code.r", "max_issues_repo_name": "shumez/stat", "max_issues_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MedicalStatisticsClass/2019/4/code.r", "max_forks_repo_name": "shumez/stat", "max_forks_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5857142857, "max_line_length": 92, "alphanum_fraction": 0.6837444655, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.719084162645674}} {"text": "# Dexter Barrows\r\n#\r\n# run: Rscript sc2-multi.r > sc2-multi.log 2>&1\r\n\r\n\r\nlibrary(reshape2)\r\nlibrary(foreach)\r\nlibrary(parallel)\r\nlibrary(doParallel)\r\nlibrary(rstan)\r\n\r\n## Stochastic SIR functions\r\n##############################################################################################\r\n\r\nsource(paste(getwd(),\"../../sir-functions\", \"StocSIR.r\", sep = \"/\"))\r\nsource(paste(getwd(),\"../../sir-functions\", \"StocSIRstan.r\", sep = \"/\"))\r\n\r\n\r\n\r\n## Setup\r\n##############################################################################################\r\n\r\nset.seed(1004)\r\n\r\nT <- 60\r\ni_infec <- 5\r\nsteps <- 7\r\nN <- 500\r\nsigma <- 10\r\nTlim <- T\r\n\r\n## Generate true trajecory and synthetic data\r\n##\r\n\r\npars_true <- c(R0 = 3.0, # new infected people per infected person\r\n r = 0.1, # recovery rate\r\n N = 500, # population size\r\n eta = 0.5, # geometric random walk\r\n berr = 0.5) # Beta geometric walk noise\r\n\r\ntrue_init_cond <- c(S = N - i_infec,\r\n I = i_infec,\r\n R = 0)\r\n\r\nnTrials <- 10\r\nmaxTrunc <- 40\r\nnTraj <- 200\r\n\r\nnumCores <- detectCores()\r\ncl <- makeCluster(numCores)\r\nregisterDoParallel(cl)\r\n\r\n## external files\r\n\r\n# R source files\r\nstoc_sir_file \t\t<- paste(getwd(),\"../../sir-functions\", \"StocSIR.r\", sep = \"/\")\r\nif2_paraboot_file \t<- paste(getwd(), \"if2-paraboot.r\", sep = \"/\")\r\nsource(stoc_sir_file)\r\nsource(if2_paraboot_file)\r\n\r\n# C++ source files\r\nif2file \t<- paste(getwd(), \"../../if2\", \"if2.cpp\", sep=\"/\")\r\nif2_s_file \t<- paste(getwd(), \"../../if2\", \"if2-s.cpp\", sep=\"/\")\r\nhmcfile \t<- paste(getwd(), \"../../hmc\", \"sirode_euler.stan\", sep=\"/\")\r\n\r\n## IF2 settings\r\n\r\nNP <- 2500\r\nnPasses <- 50\r\ncoolrate <- 0.975\r\n\r\n\r\n## fit once to compile\r\n##\r\n\r\n# get raw data\r\nsdeout_true <- StocSIR(true_init_cond, pars_true, T, steps)\r\ncolnames(sdeout_true) <- c('S','I','R','B')\r\n\r\ninfec_counts_raw <- sdeout_true[,'I'] + rnorm(T+1, 0, sigma)\r\ninfec_counts <- ifelse(infec_counts_raw < 0, 0, infec_counts_raw)\r\n\r\n# conform data to stan's required format\r\ndatlen <- T*7 + 1\r\n\r\ndata <- matrix(data = -1, nrow = T+1, ncol = steps)\r\ndata[,1] <- infec_counts\r\nstandata <- as.vector(t(data))[1:datlen]\r\n\r\n#options\r\nrstan_options(auto_write = TRUE)\r\n\r\nstan_options <- list( chains = 1, \t\t# number of chains\r\n iter = 2000, \t\t# iterations per chain\r\n warmup = 1000, \t\t# warmup interations\r\n thin = 1) \t\t# thinning number\r\n\r\n# data\r\nsir_data <- list( T = datlen, # simulation time\r\n y = standata, # infection count data\r\n N = 500, # population size\r\n h = 1/steps ) # step size per day\r\n\r\n# fit!\r\ninitialfit <- with(stan_options,\r\n stan(file = hmcfile,\r\n data = sir_data,\r\n chains = chains,\r\n iter = iter,\r\n warmup = warmup,\r\n thin = thin)\r\n )\r\n\r\n\r\n## Run multiple trajectories\r\n#########################################################################################################\r\n\r\nSSEmat <- foreach ( trunc = seq(4,maxTrunc,4), .combine = rbind, .packages = c(\"Rcpp\",\"rstan\",\"reshape2\",\"foreach\") ) %dopar% {\r\n\r\n\tTlim <- T - trunc\r\n\r\n\tif2SSEs <- numeric(nTrials)\r\n\thmcSSEs <- numeric(nTrials)\r\n\r\n\tfor(trial in 1:nTrials) {\r\n\r\n\t\t# get true trajectory\r\n\t sdeout_true <- StocSIR(true_init_cond, pars_true, T, steps)\r\n\t colnames(sdeout_true) <- c('S','I','R','B')\r\n\r\n\t # get full data\r\n\t infec_counts_raw <- sdeout_true[,'I'] + rnorm(T+1, 0, sigma)\r\n\t infec_counts <- ifelse(infec_counts_raw < 0, 0, infec_counts_raw)\r\n\r\n\t # truncate data\r\n\t datapart <- c(infec_counts[1:(Tlim+1)],rep(NA,T-Tlim))\r\n\r\n\t ## IF2\r\n\t ##\r\n\r\n\t # initial fit\r\n\t sourceCpp(if2file)\r\n\t if2time <- system.time( if2data <- if2(datapart, Tlim+1, N, NP, nPasses, coolrate) )\r\n\r\n\t # IF2 parametric bootstrap\r\n\t if2_paraboot_data <- if2_paraboot(if2data,\r\n T, Tlim, steps, N, nTraj,\r\n if2file, if2_s_file, stoc_sir_file,\r\n NP, nPasses, coolrate)\r\n\r\n\t # get mean of trajectories\r\n\t\tparabootdata <- data.frame(if2_paraboot_data)\r\n\t\tcountnames <- paste(\"counts\",1:(dim(parabootdata)[2]-9), sep = \"\")\r\n\t\tcountdata <- parabootdata[,countnames]\r\n\t\tcountmeans <- colMeans(countdata)\r\n\r\n\t\t# get SSE, save\r\n\t\ttruefuture <- sdeout_true[(Tlim+2):(T+1),'I']\r\n \testfuture <- countmeans[-1]\r\n \terr <- estfuture - truefuture\r\n \tsse <- sum(err^2)\r\n \tif2SSEs[trial] <- sse\r\n\r\n\r\n\t ## HMC fitting with stan\r\n\t ##\r\n\r\n\t datlen <- Tlim*7 + 1\r\n\r\n\t data <- matrix(data = -1, nrow = T+1, ncol = steps)\r\n\t data[,1] <- datapart\r\n\t standata <- as.vector(t(data))[1:datlen]\r\n\r\n\t sir_data <- list( T = datlen, # simulation time\r\n\t y = standata, # infection count data\r\n\t N = 500, # population size\r\n\t h = 1/steps ) # step size per day\r\n\r\n\t hmctime <- system.time(fit <- with(stan_options,\r\n\t stan( fit = initialfit,\r\n\t data = sir_data,\r\n\t chains = chains,\r\n\t iter = iter,\r\n\t warmup = warmup,\r\n\t thin = thin)\r\n\t )\r\n\t )\r\n\r\n\t exfit <- extract(fit, permuted = FALSE, inc_warmup = FALSE)\r\n\r\n\t paramdata <- data.frame(R0 = melt(exfit[,,'R0'])$value,\r\n\t r = melt(exfit[,,'r'])$value,\r\n\t sigma = melt(exfit[,,'sigma'])$value,\r\n\t eta = melt(exfit[,,'eta'])$value,\r\n\t berr = melt(exfit[,,'berr'])$value,\r\n\t Sinit = melt(exfit[,,'y0[1]'])$value,\r\n\t Iinit = melt(exfit[,,'y0[2]'])$value,\r\n\t Rinit = melt(exfit[,,'y0[3]'])$value )\r\n\r\n\t for (j in 1:datlen) {\r\n\t\t\tvarname <- paste('Bnoise[', j, ']', sep = '')\r\n\t\t\tparamdata[[varname]] <- melt( exfit[,,varname] )$value\r\n\t\t}\r\n\r\n\t parnames <- c(\"R0\",\"r\",\"sigma\",\"eta\",\"berr\",\"Iinit\")\r\n\t parvars <- var(paramdata[parnames])\r\n\t hmcparmeans <- colMeans(paramdata[parnames])\r\n\t names(hmcparmeans) <- c(\"hmc.R0\",\"hmc.r\",\"hmc.sigma\",\"hmc.eta\",\"hmc.berr\",\"hmc.Iinit\")\r\n\r\n\t bootstrapdata <- matrix(NA, nrow = nTraj, ncol = (T+1) )\r\n \r\n \tpardatlen \t<- dim(paramdata)[1]\r\n \tinds \t <- sample.int(pardatlen,nTraj,replace = TRUE)\r\n \tparams \t <- paramdata[inds,]\r\n \r\n \tfor (i in 1:nTraj) {\r\n \r\n \t\tparamset <- params[i,]\r\n\r\n \tinit_cond <- c(S = paramset$Sinit,\r\n \t I = paramset$Iinit,\r\n \t R = paramset$Rinit)\r\n \tpars <- c(R0 = paramset$R0,\r\n \t r = paramset$r,\r\n \t N = 500.0,\r\n \t eta = paramset$eta,\r\n \t berr = paramset$berr)\r\n \r\n \tberrvec <- numeric(datlen)\r\n \tfor (j in 1:datlen) {\r\n \t\tvarname <- paste(\"Bnoise[\", j, \"]\", sep = \"\")\r\n \t\tberrvec[j] <- paramset[[varname]]\r\n \t}\r\n \r\n \tsdeout <- StocSIRstan(init_cond, pars, T, steps, berrvec, datlen)\r\n \tcolnames(sdeout) <- c('S','I','R','B')\r\n \r\n \tbootstrapdata[i,] <- sdeout[,'I']\r\n \r\n \t}\r\n \r\n \t# in case of explosion\r\n \tbootstrapdata <- bootstrapdata[complete.cases(bootstrapdata),]\r\n \tgoodbootsize <- dim(bootstrapdata)[1]\r\n \r\n \tmeanTraj \t<- colMeans(bootstrapdata)\r\n \r\n \ttruefuture <- sdeout_true[(Tlim+2):(T+1),'I']\r\n\t\testfuture <- meanTraj[(Tlim+2):(T+1)]\r\n \terr <- estfuture - truefuture\r\n \tsse <- sum(err^2)\r\n \thmcSSEs[trial] <- sse\r\n\r\n\t}\r\n\r\n\treturn( c(if2SSEs, hmcSSEs) )\r\n\r\n}\r\n\r\n\r\nstopCluster(cl)\r\n\r\nsave.image(file = \"sc2-multi.RData\")\r\n", "meta": {"hexsha": "008565c46866e1ba8b0a2a8a98b001e83f34f84a", "size": 8060, "ext": "r", "lang": "R", "max_stars_repo_path": "code/stochastic-comparison/paraboot-parallel/sc2-multi.r", "max_stars_repo_name": "dbarrows/epidemic-forecasting", "max_stars_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/stochastic-comparison/paraboot-parallel/sc2-multi.r", "max_issues_repo_name": "dbarrows/epidemic-forecasting", "max_issues_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/stochastic-comparison/paraboot-parallel/sc2-multi.r", "max_forks_repo_name": "dbarrows/epidemic-forecasting", "max_forks_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5303030303, "max_line_length": 128, "alphanum_fraction": 0.479528536, "num_tokens": 2248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7187774384044876}} {"text": "# Calc connectivity clustering coeficient and path length \n#\n#\ncalc_topological_indices <- function(red.e)\n{\n size.e <- vcount(red.e)\n links.e <- ecount(red.e)\n link.den <- links.e/size.e\n conn.e <- links.e/size.e^2\n cha.path.e <- average.path.length(red.e)\n clus.coef.e <- transitivity(red.e, type = \"global\") \n #degree.e <- degree(red.e)\n return(data.frame(Size=size.e,Links=links.e, LD=link.den,Connectance=conn.e,PathLength=cha.path.e,Clustering=clus.coef.e))\n}\n\n\n# Calculation of the clustering coefficients and average path for random network simulations\n#\n#\ncalc_cpl_cc <- function(size,links,CPL,CC, nsim=1000){\n redes.r <- lapply(1:nsim, function (x) erdos.renyi.game(size, links, type=\"gnm\")) \n \n cha.path.r <- c() \n for (i in 1:nsim){\n cha.path.r <- c(cha.path.r,average.path.length(redes.r[[i]]))\n }\n \n clus.coef.r <- c() \n for (i in 1:nsim){\n clus.coef.r <- c(clus.coef.r,transitivity(redes.r[[i]], type=\"Global\"))\n }\n qcc <- quantile(clus.coef.r,c(0.005,0.995))\n qcp <- quantile(cha.path.r,c(0.005,0.995))\n mcc <- mean(clus.coef.r)\n mcp <- mean(cha.path.r)\n gamma <- CC/clus.coef.r\n lambda <- CPL/cha.path.r\n SWness <- gamma/lambda \n qSW <- quantile(SWness,c(0.005,0.995))\n mCI <- 1+(qSW[2]-qSW[1])/2 \n mSW <- CC/mcc*mcp/CPL\n \n return(data_frame(cha.pathMean= mcp,clus.coefMean=mcc,cha.pathLow=qcp[1],cha.pathUp=qcp[2], clus.coefLow=qcc[1],clus.coefHigh=qcc[2],SWness=mSW,SWnessCI=mCI)) \n}\n\n# Generate a data.frame with all simulations\n#\ngenrnd_cpl_cc <- function(size,links, nsim=1000){\n redes.r <- lapply(1:nsim, function (x) erdos.renyi.game(size, links, type=\"gnm\")) \n \n cha.path.r <- c() \n for (i in 1:nsim){\n cha.path.r <- c(cha.path.r,average.path.length(redes.r[[i]]))\n }\n \n clus.coef.r <- c() \n for (i in 1:nsim){\n clus.coef.r <- c(clus.coef.r,transitivity(redes.r[[i]], type=\"Global\"))\n }\n return(data_frame(cha.path=cha.path.r, clus.coef=clus.coef.r)) \n}\n\n\n# Test SW in Watts Strogatz model against random\n#\ngenWattsStrogatz_cpl_cc <- function(size,links, ratio=1.1,nsim=100){\n\n redes.r <- lapply(1:nsim, function (x) { \n sw <- sample_smallworld(1,size, links/(size*runif(1,0.8,1.2)), 0.5)\n sw <- simplify(sw,remove.loops = FALSE)})\n\n swr <- data_frame()\n \n for (i in 1:nsim){\n sw1 <- redes.r[[i]]\n swr <- bind_rows(swr, calc_cpl_cc(gorder(sw1),gsize(sw1)) %>% \n mutate(Size=gorder(sw1),Links=gsize(sw1),CPL=average.path.length(sw1),CC=transitivity(sw1,type=\"global\")) %>% \n mutate(isInsideCPL = (CPL >= cha.pathLow*(1/ratio) & CPL<=cha.pathUp*ratio), isGreaterCC =( CC>clus.coefHigh)))\n }\n\n return(swr)\n \n}", "meta": {"hexsha": "78158429345be5863a6dad0717c008b03d51bfc3", "size": 2657, "ext": "r", "lang": "R", "max_stars_repo_path": "R/small_world_fun.r", "max_stars_repo_name": "lsaravia/MarineFoodWebsSmallWorld", "max_stars_repo_head_hexsha": "b045b92d97e624b8ad2a780d208b02a0309cfb27", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/small_world_fun.r", "max_issues_repo_name": "lsaravia/MarineFoodWebsSmallWorld", "max_issues_repo_head_hexsha": "b045b92d97e624b8ad2a780d208b02a0309cfb27", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/small_world_fun.r", "max_forks_repo_name": "lsaravia/MarineFoodWebsSmallWorld", "max_forks_repo_head_hexsha": "b045b92d97e624b8ad2a780d208b02a0309cfb27", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-20T21:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T17:05:54.000Z", "avg_line_length": 32.0120481928, "max_line_length": 169, "alphanum_fraction": 0.6379375235, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7187133567979876}} {"text": "# Takes one dimensional time series, performs delay embedding\r\none_d <-function(data, embed_dim = 4)\r\n{\r\n edata <- embed(data, embed_dim)\r\n return(edata)\r\n}\r\n\r\n#Takes time series and scales, either using max values or taking log\r\npre_process <- function(data, scaling_method)\r\n{\r\n tmp <- data\r\n if (scaling_method == \"max\") {\r\n for (i in 1: ncol(tmp)) {\r\n tmp[,i] <- tmp[,i]/max(abs(tmp[,i]))\r\n }\r\n }\r\n return(tmp)\r\n}\r\n\r\nlog_r <- function(tmp)\r\n{\r\n for(i in 1:ncol(tmp)) {\r\n #replace each column in the data set with the log return\r\n #replace corresponding column in dat with new log return value\r\n tmp[,i] <- Delt(tmp[,i])\r\n }\r\n #Since first vale will always be N/A, remove it\r\n tmp <- tmp[-1,]\r\n return(tmp)\r\n}\r\n\r\n#Finds upper bound of diameter of the data \r\n#to use for max_scale\r\nfind_diam <- function(time) \r\n{\r\n dim <- ncol(time)\r\n diam_list = vector(length = dim)\r\n for (i in 1:dim) {\r\n high <- max(time[,i])\r\n low <- min(time[,i])\r\n diam_list[i] <- (high-low)\r\n }\r\n diam <- norm(diam_list, type = \"2\")\r\n return(diam)\r\n}\r\n\r\n#Takes time series and finds persistence diagrams\r\nnd_diag <- function(time, max_scale = 0.1, K_max = 10, window = 100) \r\n{\r\n tmp <- time\r\n \r\n #TDA\r\n maxdimension =1\r\n Diags1.rips.ls = list()\r\n total <- dim(tmp)[1]\r\n step <- 1\r\n spot <- seq(from=1, to=(total-window+1), by=step)\r\n \r\n #Persistence diagrams\r\n print(\"Computing persistence diagrams...\")\r\n pb <- txtProgressBar(min = 0, max = length(spot), style = 3)\r\n for(i in 1:length(spot)){\r\n Diags1.rips.ls[[i]] = \r\n ripsDiag(tmp[spot[i]:(spot[i]+window-1), ], maxdimension=1, max_scale, library = \"Dionysus\")\r\n \r\n # update progress bar\r\n setTxtProgressBar(pb,i)\r\n }\r\n plot(Diags1.rips.ls[[2]]$diagram)\r\n return(Diags1.rips.ls)\r\n}\r\n\r\n#Takes the diagrams from nd_diag and calculates the norm\r\nnd_norm <- function(diag, max_scale, K_max = 10, scaling_method = \"log\"){\r\n step <- 1\r\n spot <- seq(from =1, to = length(diag), by = step)\r\n \r\n Lands1.ls = list() # collects landscapes (in 2D) at particular date i per k \r\n AUC_Land.m = matrix(0,length(spot),K_max) #collects values of lambda_k at particular date i per k \r\n AUC_Land.v = vector(length=length(spot)) #collects values of L^1 at particular date\r\n #Compute L^1\r\n print(\"Computing the L1 norm of persistence landscapes...\")\r\n pb <- txtProgressBar(min = 0, max = length(spot), style = 3)\r\n for (i in 1:length(spot)){\r\n diagram <- diag[[i]]$diagram\r\n \r\n # print(diagram)\r\n # Look at persistence diagrams on a logarithmic scale\r\n if(scaling_method==\"log\") {\r\n # Only take logarithm of nonzero entries\r\n for(j in 1:nrow(diagram)) {\r\n if(diagram[j,1]==1) {\r\n diagram[j,2] = log(diagram[j,2])\r\n diagram[j,3] = log(diagram[j,3])\r\n }\r\n }\r\n }\r\n \r\n minim=Inf\r\n maxim=-Inf\r\n for(j in 1:nrow(diagram)) {\r\n # print(diagram[j,1])\r\n if(diagram[j,1]==1) {\r\n minim = min(minim,diagram[j,2])\r\n maxim = max(maxim,diagram[j,3])\r\n }\r\n }\r\n #print(minim)\r\n #print(maxim)\r\n \r\n if(minim==Inf) # There is no 1-dimensional homology feature in this window\r\n {\r\n AUC_Land.v[i]=0\r\n }\r\n else \r\n {\r\n tseq <- seq(minim, maxim, length=500)\r\n \r\n for (KK in 1:K_max){\r\n Lands1.ls[[i]]=landscape(diagram, dimension=1, KK, tseq)\r\n AUC_Land.m[i,KK]= pk.calc.auc.all(Lands1.ls[[i]],tseq, interval=c(minim,maxim))\r\n AUC_Land.v[i]= AUC_Land.v[i]+AUC_Land.m[i,KK]\r\n }\r\n plot(Lands1.ls[[2]])\r\n }\r\n # update progress bar\r\n setTxtProgressBar(pb,i)\r\n }\r\n return(AUC_Land.v)\r\n}\r\n\r\n#End line method - takes multi-D time series, processes, \r\n#and finds the norm\r\n#Default max_scale of 0 leads to find_diam being called\r\nanalyze_nd <- function(time, scaling_method = \"log\", returns = FALSE, \r\n max_scale = 0, K_max = 10, window = 50) {\r\n dates <- index(time)\r\n if (returns) {\r\n #Taking log-returns of the log of the data can lead to errors, \r\n #so if returns are desired, we deactivate the log scaling\r\n if (scaling_method ==\"log\") {\r\n scaling_method <- \"none\"\r\n }\r\n time <- log_r(time)\r\n }\r\n \r\n data <- pre_process(time, scaling_method)\r\n if(max_scale == 0) {\r\n max_scale <- find_diam(data)\r\n }\r\n diag <- nd_diag(data, max_scale, K_max, window)\r\n norm <- nd_norm(diag, max_scale, K_max, scaling_method)\r\n new_dates <- tail(dates, length(norm))\r\n norm.xts <- xts(norm, order.by = new_dates)\r\n \r\n \r\n return(norm.xts)\r\n}\r\n\r\n#End line method - takes one-D time series \r\n#finds delay embedding, calls analyze_nd\r\nanalyze_1d <- function(time, dim = 4, scaling_method = \"log\", max_scale = 0, K_max = 10, window = 50, returns = FALSE) {\r\n if (returns) {\r\n #Taking log-returns of the log of the data can lead to errors, \r\n #so if returns are desired, we deactivate the log scaling\r\n if (scaling_method == \"log\") {\r\n scaling_method <- \"none\"\r\n }\r\n \r\n time <- log_r(time)\r\n }\r\n dates <- index(time)\r\n \r\n delay_data <- one_d(time, dim)\r\n delay_data.xts <- xts(delay_data, order.by = tail(dates, length(delay_data[,1])))\r\n analyze_nd(delay_data.xts, scaling_method, returns = FALSE, max_scale, K_max, window)\r\n}\r\n\r\noutput <- function(tmp, filename , plot = \"FALSE\") \r\n{\r\n write.zoo(tmp, file = filename)\r\n if (plot == \"TRUE\") {\r\n plot(tmp, type = 'l')\r\n }\r\n}\r\n\r\n\r\nget_impact_window <- function(data, index, window_length)\r\n{\r\n data[index:(index+window_length-1)]\r\n}\r\n", "meta": {"hexsha": "57ecd679c85292cef58a7d54ceae8d8321665b6b", "size": 5523, "ext": "r", "lang": "R", "max_stars_repo_path": "Minor Project/TDA_Finance.r", "max_stars_repo_name": "sakshi-vats/tda-for-crypto", "max_stars_repo_head_hexsha": "8ffb690587f985b829ed507d0251715cd86bd265", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Minor Project/TDA_Finance.r", "max_issues_repo_name": "sakshi-vats/tda-for-crypto", "max_issues_repo_head_hexsha": "8ffb690587f985b829ed507d0251715cd86bd265", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Minor Project/TDA_Finance.r", "max_forks_repo_name": "sakshi-vats/tda-for-crypto", "max_forks_repo_head_hexsha": "8ffb690587f985b829ed507d0251715cd86bd265", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.765625, "max_line_length": 121, "alphanum_fraction": 0.6051059207, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7186066427789858}} {"text": "require(mgcv)\n# first an un-penalized example - fit E(y)=a+bx subject to a>0\nset.seed(0)\n\n# Penalized example: monotonic penalized regression spline .....\nn <- 100\n# Generate data from a monotonic truth.\nx <- runif(100) * 4 - 1\nx <- sort(x)\nf <- exp(4 * x) / (1 + exp(4 * x))\ny <- f + rnorm(100) * 0.1\nplot(x, y)\ndat <- data.frame(x = x, y = y)\n# Show regular spline fit (and save fitted object)\nf.ug <- gam(y ~ s(x, k = 10, bs = \"cr\"))\nlines(x, fitted(f.ug))\n# Create Design matrix, constraints etc. for monotonic spline....\nsm <- smoothCon(s(x, k = 10, bs = \"cr\"), dat, knots = NULL)[[1]]\nF <- mono.con(sm$xp)\n# get constraints\nG <- list(X = sm$X, C = matrix(0, 0, 0), sp = f.ug$sp, p = sm$xp, y = y, w = y * 0 + 1)\nG$Ain <- F$A\nG$bin <- F$b\nG$S <- sm$S\nG$off <- 0\n\np <- pcls(G)\n# fit spline (using s.p. from unconstrained fit)\n\nfv <- Predict.matrix(sm, data.frame(x = x)) %*% p\nlines(x, fv, col = 2)\n", "meta": {"hexsha": "1d9643d200a6647b275d96030754028255d7105c", "size": 903, "ext": "r", "lang": "R", "max_stars_repo_path": "simulation/learn_mgcv.r", "max_stars_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_stars_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation/learn_mgcv.r", "max_issues_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_issues_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation/learn_mgcv.r", "max_forks_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_forks_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.21875, "max_line_length": 87, "alphanum_fraction": 0.5891472868, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102523, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7185061729120297}} {"text": "# Mean and Standard Deviation of the Binomial Probability Distribution \r\n#number of trials\r\nn<-20\r\n# the probability of success of single event is\r\nz<-0.85\r\nMean<-n*z\r\nprint(Mean)\r\nstandard_deviation=sqrt(n*z*(1-z))\r\nprint(standard_deviation)\r\n\r\n", "meta": {"hexsha": "92869a9070a76130eb6d2ee710b1ef6d6bfa9105", "size": 248, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.10/Ex4_10.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.10/Ex4_10.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.10/Ex4_10.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 22.5454545455, "max_line_length": 72, "alphanum_fraction": 0.7379032258, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7182094017222568}} {"text": "# Date: 2022-01-21\n# Author: Gustav Collin Rasmussen\n# Purpose: Definition and exploration of popular 1-repetition-maximum formulas\n\nlibrary(tidyverse)\nlibrary(cowplot)\n\n\nepley <- function(w, r) {\n stopifnot(r > 1)\n return (w * (1 + r / 30))\n}\n\n\nbrzycki <- function(w, r) {\n return (w * 36 / (37 - r))\n}\n\n\nepley_inverted <- function(one_rm, r, progression) {\n stopifnot(r > 1)\n return (log10(progression) * one_rm / (1 + r / 30))\n}\n\n\nbrzycki_inverted <- function(one_rm, r, progression) {\n return (log10(progression) * one_rm * (37 - r) / 36)\n}\n\n\n###### evaluate 1rm formulas at 5 reps for varying weights ######\nweight = seq(10, 60, by=10)\n\none_rm_constant_reps_df <- data.frame(weight = weight,\n epley_1rm = epley(weight, 5),\n brzycki_1rm = brzycki(weight, 5)\n )\n\ndf1 <- one_rm_constant_reps_df %>%\n select(weight, epley_1rm, brzycki_1rm) %>%\n gather(key = \"variable\", value = \"one_rep_max\", -weight)\n\n###### evaluate 1rm formulas at weight: 70 kg for varying reps ######\nreps = 2:10\none_rm_constant_weight_df <- data.frame(reps = reps,\n epley_1rm = epley(70, reps),\n brzycki_1rm = brzycki(70, reps)\n)\n\ndf2 <- one_rm_constant_weight_df %>%\n select(reps, epley_1rm, brzycki_1rm) %>%\n gather(key = \"variable\", value = \"one_rep_max\", -reps)\n\n###### evaluate inverse 1rm formulas at 5 reps for varying weights ######\ninverse_one_rm_constant_reps_df <- data.frame(weight = weight,\n epley_inverted = epley_inverted(weight, 5, 10),\n brzycki_inverted = brzycki_inverted(weight, 5, 10)\n )\n\ndf3 <- inverse_one_rm_constant_reps_df %>%\n select(weight, epley_inverted, brzycki_inverted) %>%\n gather(key = \"variable\", value = \"inverse_one_rep_max\", -weight)\n\n###### evaluate inverse 1rm formulas at weight: 70 kg for varying reps ######\ninverse_one_rm_constant_weight_df <- data.frame(reps = reps,\n epley_inverted = epley_inverted(70, reps, 10),\n brzycki_inverted = brzycki_inverted(70, reps, 10)\n)\n\ndf4 <- inverse_one_rm_constant_weight_df %>%\n select(reps, epley_inverted, brzycki_inverted) %>%\n gather(key = \"variable\", value = \"inverse_one_rep_max\", -reps)\n\n################## prepare plots ##################\nsp1 <- ggplot(df1, aes(weight, one_rep_max)) +\n geom_point(aes(color = variable)) +\n scale_color_manual(values = c(\"darkred\", \"steelblue\"))\n\nsp2 <- ggplot(df2, aes(reps, one_rep_max)) +\n geom_point(aes(color = variable)) +\n scale_color_manual(values = c(\"darkred\", \"steelblue\"))\n\nsp3 <- ggplot(df3, aes(weight, inverse_one_rep_max)) + \n geom_point(aes(color = variable)) +\n scale_color_manual(values = c(\"darkred\", \"steelblue\"))\n\nsp4 <- ggplot(df4, aes(reps, inverse_one_rep_max)) + \n geom_point(aes(color = variable)) +\n scale_color_manual(values = c(\"darkred\", \"steelblue\"))\n\n################## show figure ##################\nplot_grid(sp1, sp2, sp3, sp4,\n labels = rep(c(\"constant reps (5)\", \"constant weight (70 kg)\"), times=2),\n ncol = 2, nrow = 2)\n", "meta": {"hexsha": "aebfb3f6234ed9926fecbf53437fc02f9da5df3b", "size": 3194, "ext": "r", "lang": "R", "max_stars_repo_path": "src/1rm.r", "max_stars_repo_name": "TheNewThinkTank/Fitness-Tracker", "max_stars_repo_head_hexsha": "a1e9996f222017ea1da287075607f7da44153bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-20T14:15:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T09:11:55.000Z", "max_issues_repo_path": "src/1rm.r", "max_issues_repo_name": "TheNewThinkTank/Fitness-Tracker", "max_issues_repo_head_hexsha": "a1e9996f222017ea1da287075607f7da44153bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/1rm.r", "max_forks_repo_name": "TheNewThinkTank/Fitness-Tracker", "max_forks_repo_head_hexsha": "a1e9996f222017ea1da287075607f7da44153bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6210526316, "max_line_length": 87, "alphanum_fraction": 0.6102066374, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7179469312310984}} {"text": "for (n in c(3030, 1000, 500, 200, 100, 50, 10)) {\n p = dbinom(n/2, n, 0.5)\n cat(n, \" : \", round(100*p, 2), \" %\\n\")\n}\n", "meta": {"hexsha": "4f4d7ee6373030efeda0f512f0b4ceaba607674f", "size": 119, "ext": "r", "lang": "R", "max_stars_repo_path": "r/tie.r", "max_stars_repo_name": "jgoizueta/binomial-techniques", "max_stars_repo_head_hexsha": "0c559e481e719dda6184fa17de83003e0f6d0c20", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r/tie.r", "max_issues_repo_name": "jgoizueta/binomial-techniques", "max_issues_repo_head_hexsha": "0c559e481e719dda6184fa17de83003e0f6d0c20", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r/tie.r", "max_forks_repo_name": "jgoizueta/binomial-techniques", "max_forks_repo_head_hexsha": "0c559e481e719dda6184fa17de83003e0f6d0c20", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8, "max_line_length": 49, "alphanum_fraction": 0.4621848739, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7176667819730739}} {"text": "#' Set outlier critical value\n#'\n#' Set outlier critical value using the Ljung algorithm as given in\n#' Ljung, G. M. (1993). On outlier detection in time series. \n#' Journal of Royal Statistical Society B 55, 559-567.\n#' \n#'\n#' @param number_observations number of observations tested for outliers \n#' @param cv_alpha alpha for critical value\n#' @return outlier critical value generated by the algorithm given in Ljung (1993). \n#' The critical value in X-13 is different as it is adjusted to allow for smaller values \n#' to approximate the normal distribution.\n#' @examples\n#' this_critical_value <- set_critical_value(12, 0.025)\n#' @export\nset_critical_value <- function(number_observations, cv_alpha = 0.01) {\n # Brian Monsell Version 1.4 3/29/2021\n pmod <- 2 - sqrt(1 + cv_alpha)\n acv <- sqrt(2 * log(number_observations))\n bcv <- acv - (log(log(number_observations)) + log(2 * 2 * pi))/(2 * acv)\n xcv <- -log(-0.5 * log(pmod))\n setcvl <- (xcv/acv) + bcv\n return(setcvl)\n}\n", "meta": {"hexsha": "f9e4a6675a829247c497aeecfbb8bde8656372c9", "size": 1014, "ext": "r", "lang": "R", "max_stars_repo_path": "R/set_critical_value.r", "max_stars_repo_name": "bcmonsell/airutilities", "max_stars_repo_head_hexsha": "278d52b6accf576fea1f21801564664e15d5f2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/set_critical_value.r", "max_issues_repo_name": "bcmonsell/airutilities", "max_issues_repo_head_hexsha": "278d52b6accf576fea1f21801564664e15d5f2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/set_critical_value.r", "max_forks_repo_name": "bcmonsell/airutilities", "max_forks_repo_head_hexsha": "278d52b6accf576fea1f21801564664e15d5f2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.56, "max_line_length": 97, "alphanum_fraction": 0.6854043393, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7176204984504843}} {"text": "# Jose.M.Pavia@uv.es\nrequire(Hmisc)\nPerCapita <- c(10, 20, 30, 20, 20, 40)\nGroup <- c( \"A\", \"B\", \"B\", \"A\", \"A\", \"B\")\nW <- c(1.5, 2.3, 4.5, 2.6, 1.7, 3.9)\n\n## Works\nwtd.mean(PerCapita, weights=W)\nwtd.quantile(PerCapita, weights=W)\nwtd.mean(PerCapita[Group==\"A\"], weights=W[Group==\"A\"])\nwtd.mean(PerCapita[Group==\"B\"], weights=W[Group==\"B\"])\n\ng <- function(y) wtd.mean(y[,1],y[,2])\nsummarize(cbind(PerCapita, W), llist(Group), g, stat.name='y')\n\n\n## davharris https://github.com/harrelfe/Hmisc/issues/69\n\nx <- c(3.7,3.3,3.5,2.8)\nwt <- c(5, 5, 4, 1)/15\nwtd.mean(x, wt)\nwtd.var(x, wt)\n", "meta": {"hexsha": "68739f7a7b209499fb0f0bc64f07bc56abc5a9a4", "size": 584, "ext": "r", "lang": "R", "max_stars_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/wtd.r", "max_stars_repo_name": "klodzikowski/phongames", "max_stars_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-27T10:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:57:34.000Z", "max_issues_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/wtd.r", "max_issues_repo_name": "klodzikowski/phongames", "max_issues_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-12-28T07:09:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:33:50.000Z", "max_forks_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/wtd.r", "max_forks_repo_name": "klodzikowski/phongames", "max_forks_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-03-05T05:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T07:52:04.000Z", "avg_line_length": 25.3913043478, "max_line_length": 62, "alphanum_fraction": 0.5993150685, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7174827157533215}} {"text": "#Copyright (c) 2016 Riccardo Francescato\na <- c(108,124,124,106,115,138,163,159,134,139)\n#confidency level\nalpha = .01 \n#type of test: 0 left tail 1 double tail 2 right tail\ntype = 1\n#calculations....\nn0 = length(a)\t\t# number of reps for sample 0\nxbar0 = mean(a)\t\t# sample 0 mean \nSigma0 = 2\t\t\t# given variance \ns0 = sd(a)\t\t\t# sample 0 standard deviation \nX0 = ((n0-1)*s0^2)/Sigma0\nif(type == 0){\n\tx.alpha = qchisq(1−alpha, df=n0−1) \n\tcat(\"Results of lower tail\\n\")\n\tcat(\"Sample\\n\")\n\tcat(paste(\"# of elements: \", n0, \" Mean: \", xbar0, \" St Dev: \",s0))\n\tcat(paste(\"\\nx0: \",X0))\n\tcat(paste(\"\\nxalpha: \",x.alpha))\n\tif(X0x.top.alpha) cat(\"\\nREJECT H0\\n\") else cat(\"\\nACCEPT H0\\n\")\n\n}else if(type == 2){\n\tx.alpha = qchisq(alpha, df=n0−1) \n\tcat(\"Results of upper tail\\n\")\n\tcat(\"Sample\\n\")\n\tcat(paste(\"# of elements: \", n0, \" Mean: \", xbar0, \" St Dev: \",s0))\n\tcat(paste(\"\\nx0: \",X0))\n\tcat(paste(\"\\nxalpha: \",x.alpha))\n\tif(X0>x.alpha) cat(\"\\nREJECT H0\\n\") else cat(\"\\nACCEPT H0\\n\")\n}\n", "meta": {"hexsha": "ac731b54c8b37e64c8f61bc326867e931ab7fa1f", "size": 1397, "ext": "r", "lang": "R", "max_stars_repo_path": "Test_of_hp_1_serie_and_one_mu_VARIANCE.r", "max_stars_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_stars_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Test_of_hp_1_serie_and_one_mu_VARIANCE.r", "max_issues_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_issues_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test_of_hp_1_serie_and_one_mu_VARIANCE.r", "max_forks_repo_name": "RiccardoFrancescato/DataDesignScrips", "max_forks_repo_head_hexsha": "92d19d1cd5da9fb1486d53bc97c444714a3e5aa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0731707317, "max_line_length": 87, "alphanum_fraction": 0.6170365068, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7174782096853515}} {"text": "### functions for QR or sparseQR class\nqrrank<-function(QR, tol=1e-8){\n if(class(QR)==\"sparseQR\")\n return(sum(abs(diag(QR@R))>tol))\n else\n return(QR$rank)\n}\nqrRM<-function(QR){\n if(class(QR)==\"sparseQR\")\n return(qrR(QR))\n else\n return(qr.R(QR))\n}\n\n# invTwobyTwoSymMatrix: inverts two-by-two symmetric matrices\n# M: symmetric matrix\n# OUTPUT: a two-by-two symmetric matrix\ninvTwobyTwoSymMatrix <- function(M) {\n if(missing(M)) stop(\"invTwobyTwoSymMatrix: Supply M!\") \n if(nrow(M) != 2 || ncol(M) != 2) stop(\"invTwobyTwoSymMatrix: The matrix is not 2 by 2\")\n if(M[1,2] != M[2,1]) stop(\"invTwobyTwoSymMatrix: The matrix is not symmetric!\")\n detM = M[1,1] * M[2,2] - M[1,2]^2\n Minverse = M\n Minverse[2,2] = M[1,1]\n Minverse[1,1] = M[2,2]\n Minverse[1,2] = Minverse[2,1] = -1 * M[1,2]\n return(1/detM * Minverse)\n}\n\n# quadSolver: solves the quadratic equation ax^2 + bx + c = 0\n# Can also be used to solve eigenvalues of two-by-two matrices\n# E.x. if [d,e; f,g] is the two-by-two matrix\n# eigenvalues are defined as the solution to det( [d,e; f,g] - lambda * I) = 0\n# Or det([d - lambda, e; f, g - lambda]) = 0\n# Or (d-lambda) * (g -lambda) - e*f = 0\n# Or lambda^2 - (d +g) *lambda + d*g - e*f = 0\nquadSolver = function(a,b,c) {\n if(missing(a) || missing(b) || missing(c)) stop(\"Supply the coefficients!\")\n if(length(a) != 1 || length(b) != 1 || length(c) != 1) stop(\"Supply only scalar values to a,b, and c\")\n if(a == 0) stop(\"Something is wrong! Leading coefficient is zero\")\n \n discriminant = b^2 - 4 * a * c\n if(discriminant < 0) return(c(NA,NA))\n if(discriminant == 0) return( rep(-b/(2*a),2))\n if(discriminant > 0) {\n if(a > 0) {\n\t lowerRoot = -b / (2*a) - sqrt(discriminant) / (2*a)\n\t upperRoot = -b / (2*a) + sqrt(discriminant) / (2*a)\n\t return(c(lowerRoot,upperRoot))\n\t} else {\n\t lowerRoot = -b / (2*a) + sqrt(discriminant) / (2*a)\n\t upperRoot = -b / (2*a) - sqrt(discriminant) /(2*a)\n\t return(c(lowerRoot,upperRoot))\n\t}\n }\n}\n\n", "meta": {"hexsha": "b002ea253377ca9f7a5e452fd8f9633823556051", "size": 2064, "ext": "r", "lang": "R", "max_stars_repo_path": "R/helperFunc.r", "max_stars_repo_name": "qingyuanzhao/ivmodel", "max_stars_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-09-22T13:38:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T02:04:23.000Z", "max_issues_repo_path": "R/helperFunc.r", "max_issues_repo_name": "qingyuanzhao/ivmodel", "max_issues_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-09T19:20:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T13:44:24.000Z", "max_forks_repo_path": "R/helperFunc.r", "max_forks_repo_name": "qingyuanzhao/ivmodel", "max_forks_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-01T16:33:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T16:33:38.000Z", "avg_line_length": 35.5862068966, "max_line_length": 104, "alphanum_fraction": 0.5867248062, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7174026085687731}} {"text": "## HF#1 Random Hex color\nrandHclr <- function() {\n m=255;r=g=b=0;\n r <- sample(0:m, 1, replace=TRUE);\n g <- sample(0:m, 1, replace=TRUE);\n b <- sample(0:m, 1, replace=TRUE);\n return(rgb(r,g,b,maxColorValue=m));\n}\n## HF#2 Metrics: Euclidean, Manhattan and Minkovski\nMetric <- function(x, y, mt) {\n if(mt==1) {return(sqrt(x*x + y*y))}\n if(mt==2) {return(abs(x) + abs(y))}\n if(mt==3) {return((abs(x)^3 + abs(y)^3)^0.33333)}\n}\n\n## Plotting Voronoi diagram. aev 3/12/17\n## ns - number of sites, fn - file name, ttl - plot title.\n## mt - type of metric: 1 - Euclidean, 2 - Manhattan, 3 - Minkovski.\npVoronoiD <- function(ns, fn=\"\", ttl=\"\",mt=1) {\n cat(\" *** START VD:\", date(), \"\\n\");\n if(mt<1||mt>3) {mt=1}; mts=\"\"; if(mt>1) {mts=paste0(\", mt - \",mt)};\n m=640; i=j=k=m1=m-2; x=y=d=dm=0;\n if(fn==\"\") {pf=paste0(\"VDR\", mt, ns, \".png\")} else {pf=paste0(fn, \".png\")};\n if(ttl==\"\") {ttl=paste0(\"Voronoi diagram, sites - \", ns, mts)};\n cat(\" *** Plot file -\", pf, \"title:\", ttl, \"\\n\");\n plot(NA, xlim=c(0,m), ylim=c(0,m), xlab=\"\", ylab=\"\", main=ttl);\n X=numeric(ns); Y=numeric(ns); C=numeric(ns);\n for(i in 1:ns) {\n X[i]=sample(0:m1, 1, replace=TRUE);\n Y[i]=sample(0:m1, 1, replace=TRUE);\n C[i]=randHclr();\n }\n for(i in 0:m1) {\n for(j in 0:m1) {\n dm=Metric(m1,m1,mt); k=-1;\n for(n in 1:ns) {\n d=Metric(X[n]-j,Y[n]-i, mt);\n if(d6000)=1 - F(6000)\n\n1 - pnorm(q=6000, mean=64*90, sd=sqrt(64*100))\n\n# * Example 2. ####\n# \n# The consignment contains 300 products of a certain type. It is known that the\n# probability of making a defective product of this type is 0.04.\n# \n# ** a) ####\n# \n# Estimate the probability that the proportion of defective products in the consignment\n# (300 products) will differ from the probability of producing a defective product by\n# less than 1% (i.e. $p-\\pi \\in <-0.01,0.01>$).\n# \n\n\n# p-pi from -0.01 to 0.01\n# for pi = 0.04, p is from 0.03 to 0.05\n# having 300 products, we should observe between 9 and 15 defective ones\n\n# X...number of defective products out of 300\n# X~Binom(n=300, pi=0.04)\n# P(9 <= X <= 15)=P(X<=15)-P(X<9)\npbinom(15,300,0.04)-pbinom(9-1,300,0.04)\n\n# X=(p - π)/sqrt(π*(1 - π)) * sqrt(n) ∼ N(0, 1)\n# P(-0.01/sqrt(π*(1-π))*sqrt(n) < X < 0.01/sqrt(π*(1-π))*sqrt(n))\npi = 0.04\nn = 300\nbound = 0.01/sqrt(pi*(1-pi))*sqrt(n)\npnorm(q=bound, mean=0, sd=1) - pnorm(q=-bound, mean=0, sd=1)\n\n# ** b) ####\n# \n# How will the result change if the shipment contains 3,000 products?\n# \n\n\npbinom(150,3000,0.04)-pbinom(90-1,3000,0.04)\n\nn = 3000\nbound = 0.01/sqrt(pi*(1-pi))*sqrt(n)\npnorm(q=bound, mean=0, sd=1) - pnorm(q=-bound, mean=0, sd=1)\n\n# * Example 3. ####\n# \n# Passenger regularly travel to and from work using public transport. It is known that\n# the waiting time for the arrival of public transport ranges from 0 to 3 minutes. What\n# is the probability that the total waiting time for a passenger during in 23 working\n# days will be less than 80 minutes?\n# \n\n\n# Y... time of the i-th waiting for public transport\n# y~R(0; 3)\n# X... total waiting time in 23 days(round trip ⇒ 46 waitings)\n# X~N(46 * EY; 46 * DY)\n# P(X<80)\n\na = 0\nb = 3\nn = 46\nEY = (a+b)/2\nDY = (b-a)^2/12\n\npnorm(q=80, mean=n*EY, sd=sqrt(n*DY))\n\n# * Example 4. ####\n# \n# Assume that the average electricity consumption of households in a given city in\n# January is 120 kWh and the standard deviation of consumption is 100 kWh. Determine the\n# probability that the average consumption of 100 randomly selected households will be\n# greater than 140 kWh.\n\n\n# Xi... consumption of the i-th household\n# X... average consumption of 100 households\n# X~N(EXi; Dxi/n)\n# P(X>140)\n\nEXi = 120\nDXi = 100^2\nn = 100\n1 - pnorm(q=140, mean=EXi, sd=sqrt(DXi/n))\n\n# * Example 5. ####\n# \n# The Acme Battery Company has developed a new type of mobile phone battery. On average,\n# batteries last 60 minutes on a single charge. The standard deviation of this time is 4\n# minutes. Assume that the production department runs a quality control test after 6\n# months. They performed two random selections with a range of 10 batteries and in both\n# found a standard deviation of battery life greater than 6 minutes. How likely were\n# they to expect such a result?\n# \n\n\n# X=(n - 1) * S^2/σ^2\n# X ∼ χ_n-1\n# P(S>6)=P(X>...)\n\nn = 10\nS_obs = 6\nsigma = 4\nX_obs = (n - 1)*S_obs^2/sigma^2\n\nP_one_observation = 1 - pchisq(q=X_obs, df=n-1)\nP_one_observation\nP_one_observation^2\n\n# * Example 6. ####\n# \n# The mortality tables show a probability of 0.99 that a 35-year-old man will live\n# another year. The annual premium for this age group is CZK 2,000, in the event of\n# death the insurance company will pay CZK 100,000. What is the probability that the\n# profit of the company insuring 500 men aged 35 will be at least CZK 500,000?(Solve in\n# two ways - using the binomial distribution and using the binomial distribution\n# approximation by the normal distribution.)\n\n\n# X... number of men out of 500 who won't live to see another year\n# X~Bi(500; 0.01)\n# Z=500 · 2,000 - X · 100,000\n# P(Z ≥ 500,000)=P(X ≤ 5)\n\npbinom(5, size=500, prob=0.01)\n\n# X~Bi(500; 0.01)~N(500 * 0.01; 500 * 0.01*(1-0.01))\n# P(X ≤ 5)~P(X<5.5)(continuity correction)\n\npnorm(5.5, mean=500*0.01, sd=sqrt(500*0.01*(1-0.01)))\n\n# * Example 7. ####\n# \n# Assume that approximately 60% of young men in the population have higher than\n# recommended serum cholesterol levels. In a random selection of 200 young men, how\n# likely will more than 120 of them have higher than recommended serum cholesterol\n# levels?\n# \n\n\n# X... number of young men out of 200 with higher than recommended serum cholesterol levels\n# X ∼ Bi(200; 0.6)\n# P(X>120)=1 - P(X ≤ 120)\n\n1 - pbinom(120, size=200, prob=0.6)\n\n# X~N(200 * 0.6; 200 * 0.6(1-0.6)), ie X ≈ N(120; 48)\n# 1 - P(X ≤ 120)~1 - P(X<120.5)(continuity correction)\n\n1 - pnorm(120.5, mean=200*0.6, sd=sqrt(200*0.6*(1-0.6)))\n\n\n\n", "meta": {"hexsha": "85560c70c5e5ee32713d091f522d2935372df1a7", "size": 9062, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 8/T10_Sampling_distributions.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise 8/T10_Sampling_distributions.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise 8/T10_Sampling_distributions.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 27.0507462687, "max_line_length": 91, "alphanum_fraction": 0.6486426837, "num_tokens": 2922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.7169183477196504}} {"text": "wavethresh = function(y, thresh.value=\"universal\", sigma=NA, p=1, low.level=4, by.level=F, filter.number=2, family=\"DaubExPhase\", bc=\"periodic\"){\r\n # Wavelet-based smoothing by Lp penalized least squares\r\n # INPUT\r\n # y = noisy signal\r\n # thresh.value = \"universal\", \"minimax\", \"SURE\", \"BIC\", \"SLIC\"\r\n # sigma = standard deviation of noise\r\n # p in [0,1] (0=hard, 1=soft)\r\n # low.level = lowest level where to start thresholding\r\n # by.level = T (levelwise) or F (global)\r\n\r\n\n if(!is.na(p)){\r\n if(p==1) type=\"soft\"\r\n if(p==0) type=\"hard\"\r\n }\r\n else type=\"lpin01\"\r\n\r\n N=length(y)\r\n if(!is.numeric(sigma)){\r\n ytHaar=wd(y,1,family=\"DaubExPhase\") \r\n sigma=mad(accessD(ytHaar,log(N,2)-1),center=0)\r\n }\r\n y=y/sigma\r\n yt=wd(y, filter.number=filter.number, family=family, bc=bc)\r\n\r\n if(by.level==F){\r\n if(thresh.value==\"universal\") thresh.value=sqrt(2*log(N))\r\n if(thresh.value==\"minimax\") {\r\n Ns=2^c(6:16)\r\n tmmS=c(1.474,1.669,1.859,2.045,2.226,2.403,2.575,2.743,2.906,3.066,3.221)\r\n tmmH=c(2.697,2.913,3.117,3.312,3.497,3.674,3.844,4.008,4.166,4.319,4.467)\r\n if(type==\"soft\") thresh.value=tmmS[match(N,Ns)]\r\n if(type==\"hard\") thresh.value=tmmH[match(N,Ns)]\r\n }\r\n if((thresh.value==\"SURE\")&(type==\"soft\")){\r\n aMLE=rev(yt$D)\r\n ## DJ 1995 JASA's Hybrid method eq. 14 page 1208\r\n if(mean(aMLE^2-1)>(log(N,2)^(3/2)/sqrt(N))){\r\n aMLE=aMLE[-c(1:(2^low.level-1))]\r\n aMLEabssort = sort(abs(aMLE))\r\n aMLEabssort2 = aMLEabssort^2\r\n lambdas=aMLEabssort;\r\n ND=length(aMLE)\r\n tp1 = cumsum(aMLEabssort2)+((ND-1):0)*aMLEabssort2;\r\n risk_hatS = (ND - (2 * (1:ND)) + tp1)/ND;\r\n thresh.value = lambdas[which.min(risk_hatS)]\r\n }\r\n else thresh.value=sqrt(2*log(N))\r\n }\r\n if((thresh.value==\"SLIC\")&(type==\"soft\")){\r\n ND=length(yt$D)\r\n lambdaU=sqrt(2*log(ND))\r\n lambda0=lambdaU/2\r\n a.hat=lp_shrink(yt$D, 1, lambda0)\r\n l1mean=mean(abs(a.hat))\r\n again=T\r\n while(again){\r\n lambda1=lambdaU/(1+l1mean*lambdaU)\r\n again=((abs(lambda1-lambda0)/lambda1)>1.e-6)\r\n lambda0=lambda1\r\n a.hat=lp_shrink(yt$D, 1, lambda0)\r\n l1mean=mean(abs(a.hat))\r\n }\r\n thresh.value=lambda0\r\n }\r\n if((thresh.value==\"BIC\")&(type==\"hard\")) thresh.value=sqrt(log(N))\r\n\r\n ytthresh=threshold.wd(yt, levels=low.level:(yt$nlevels-1), type=type, policy=\"manual\", value=thresh.value)\r\n ytthresh$D=ytthresh$D*sigma\r\n ytthresh$C=ytthresh$C*sigma\r\n }\r\n else{\r\n ########################### \r\n ## Levelwise thresholding\r\n ytthresh=yt\r\n for(level in low.level:(yt$nlevel-1)){\r\n ytj=accessD(yt,level)\r\n Nj=length(ytj)\r\n if(thresh.value==\"universal\") thresh.value.j=sqrt(2*log(Nj))\r\n if(thresh.value==\"minimax\") {\r\n Ns=2^c(3:16)\r\n # The first 4 values are extrapolated ones.\r\n tmmS=c(0.674,0.874,1.074,1.274,1.474,1.669,1.859,2.045,2.226,2.403,2.575,2.743,2.906,3.066,3.221)\r\n tmmH=c(1.757,2.007,2.247,2.477,2.697,2.913,3.117,3.312,3.497,3.674,3.844,4.008,4.166,4.319,4.467)\r\n if(type==\"soft\") thresh.value.j=tmmS[match(Nj,Ns)]\r\n if(type==\"hard\") thresh.value.j=tmmH[match(Nj,Ns)]\r\n }\r\n if((thresh.value==\"SURE\")&(type==\"soft\")){\r\n ## DJ 1995 JASA's Hybrid method eq. 14 page 1208\r\n if(mean(ytj^2-1)>(log(Nj,2)^(3/2)/sqrt(Nj))){\r\n aMLE=ytj\r\n aMLEabssort = sort(abs(aMLE))\r\n aMLEabssort2 = aMLEabssort^2\r\n lambdas=aMLEabssort;\r\n tp1 = cumsum(aMLEabssort2)+((Nj-1):0)*aMLEabssort2;\r\n risk_hatS = (Nj - (2 * (1:Nj)) + tp1)/Nj;\r\n thresh.value.j = lambdas[which.min(risk_hatS)]\r\n }\r\n else thresh.value.j=sqrt(2*log(Nj))\r\n }\r\n if((thresh.value==\"SURE\")&(type==\"hard\")){\r\n ## DJ 1995 JASA's Hybrid method eq. 14 page 1208\r\n if(mean(ytj^2-1)>(log(Nj,2)^(3/2)/sqrt(Nj))){\r\n aMLE=ytj\r\n aMLEabssort = sort(abs(aMLE))\r\n aMLEabssort2 = aMLEabssort^2\r\n risk_hatH=(Nj-(2 * (1:Nj)) + cumsum(aMLEabssort2))/Nj;\r\n ahatU=ytj*(abs(ytj)>sqrt(2*log(Nj)));\r\n for(n in 1:Nj){\r\n phi=aMLEabssort[n];\r\n risk_hatH[n]=risk_hatH[n]+2*phi/sqrt(2*pi)*mean(exp(-0.5*(-phi-ahatU)^2)+exp(-0.5*(phi-ahatU)^2))\r\n }\r\n thresh.value.j = aMLEabssort[which.min(risk_hatH)]\r\n }\r\n else thresh.value.j=sqrt(2*log(Nj))\r\n }\r\n if((thresh.value==\"SLIC\")&(type==\"soft\")){\r\n lambdaU=sqrt(2*log(Nj))\r\n lambda0=lambdaU/2\r\n ytj.hat=lp_shrink(ytj, 1, lambda0)\r\n l1mean=mean(abs(ytj.hat))\r\n again=T\r\n while(again){\r\n lambda1=lambdaU/(1+l1mean*lambdaU)\r\n again=((abs(lambda1-lambda0)/lambda1)>1.e-6)\r\n lambda0=lambda1\r\n ytj.hat=lp_shrink(ytj, 1, lambda0)\r\n l1mean=mean(abs(ytj.hat))\r\n }\r\n thresh.value.j=lambda0\r\n }\r\n if((thresh.value==\"BIC\")&(type==\"hard\")) thresh.value.j=sqrt(log(Nj))\r\n if((thresh.value==\"SURE\")&is.na(p)){\r\n outmin=nlminb(.5, SURE_lp, control=list(iter.max=20, x.tol=.05), lower=0, upper=1, yt=ytj, out_nb=1)\r\n p.j=outmin$par\r\n out=SURE_lp(p.j, ytj, 2)\r\n lambda.j=out$lambda_SURE\r\n thresh.value.j=(2-p.j)*(lambda.j*(2*(1-p.j))^(p.j-1))^(1/(2-p.j))\r\n }\r\n if((thresh.value==\"SLIC\")&is.na(p)){\r\n p1=1/log(Nj);\r\n phiU=sqrt(2*log(Nj));\r\n lambdapU=(phiU/(2-p1))^(2-p1)/(2-2*p1)^(p1-1)\r\n dyl = (2-2*p1)^((p1-1)/(2-p1))*lambdapU^((p1-1)/(2-p1));\r\n dyll= (2-2*p1)^((p1-1)/(2-p1))*(p1-1)/(2-p1)*lambdapU^((2*p1-3)/(2-p1));\r\n taupU=p1*phiU*lambdapU*(dyl)^2/(Nj*dyl+p1*lambdapU*dyll);\r\n ct0=phiU/taupU;ct1=0;low=lambdapU;high=lambdapU\r\n while(rootlambda(low,p1,ct0,ct1,Nj)<=0) {low=low/2}\r\n while(rootlambda(high,p1,ct0,ct1,Nj)>=0) {high=high*2} \r\n lambda1=uniroot(rootlambda,p=p1,ct0=ct0,ct1=ct1,N=Nj,interval=c(low,high));lambda1=lambda1$root \r\n \r\n MAXITER=20;\r\n again_p=1; again_lambda=1; iter=0;\r\n while((again_p|again_lambda)&(iter.001);\r\n \r\n lambdapU=(phiU/(2-p1))^(2-p1)/(2-2*p1)^(p1-1); \r\n dyl=(2-2*p1)^((p1-1)/(2-p1))*lambdapU^((p1-1)/(2-p1));\r\n dyll=(2-2*p1)^((p1-1)/(2-p1))*(p1-1)/(2-p1)*lambdapU^((2*p1-3)/(2-p1)); \r\n taupU=p1*phiU*lambdapU*(dyl)^2/(Nj*dyl+p1*lambdapU*dyll);\r\n \r\n Lp=mean((abs(ytj.hat))^p1);\r\n ct0=phiU/taupU;ct1=Lp;\r\n low=lambda0;\r\n while(rootlambda(low,p1,ct0,ct1,Nj)<=0) {low=low/2}\r\n high=lambdapU;\r\n while(rootlambda(high,p1,ct0,ct1,Nj)>=0) {high=high*2}\r\n lambda1=uniroot(rootlambda,p=p1,ct0=ct0,ct1=ct1,N=Nj,interval=c(low,high));lambda1=lambda1$root \r\n \r\n again_lambda=(mean(abs((lambda1-lambda0)/lambda1))>.01);\r\n } \r\n lambda.j=lambda1;\r\n p.j=p1;\r\n thresh.value.j=(2-p.j)*(lambda.j*(2*(1-p.j))^(p.j-1))^(1/(2-p.j))\r\n }\r\n if(!is.na(p)&((p==0)||(p==1))) ytthresh=threshold.wd(ytthresh, levels=level, type=type, policy=\"manual\", value=thresh.value.j)\r\n else {\r\n ytthresh.j=lp_shrink(ytj, p.j,lambda.j)\r\n ytthresh=putD(ytthresh, level, ytthresh.j)\r\n }\r\n }\r\n ytthresh$D=ytthresh$D*sigma\r\n ytthresh$C=ytthresh$C*sigma\r\n }\r\n\r\n mu.hat=wr(ytthresh)\r\n\r\n out=NULL\r\n out$alpha.MLE=yt\r\n out$alpha.hat=ytthresh\r\n out$mu.hat=mu.hat\r\n out$sigma.hat=sigma\r\n return(out)\r\n}\r\n\r\n##########################################\r\n## Two functions employed by SLIC: rootlambda and condloglikinp\r\nrootlambda=function(lambda,p,ct0,ct1,N){\r\n\r\n tau=sqrt(2*log(N))/ct0;\r\n if(lambda<0){\r\n fl=1.e10;\r\n }\r\n else {\r\n dyll=(2-2*p)^((p-1)/(2-p))*(p-1)/(2-p)*lambda^((2*p-3)/(2-p));\r\n temp1=(2-2*p)^((p-1)/(2-p))*lambda^((p-1)/(2-p));\r\n fl=-ct1*lambda + 1/p - ct0*lambda/N*temp1 + lambda/N*dyll/temp1;\r\n }\r\n return(fl)\r\n }\r\n \r\n############################################### \r\ncondloglikinp=function(p, alpha,lambda, N, tau){\r\n\r\n J=log(length(alpha))/log(2);\r\n Nm=length(alpha);\r\n Lp=sum((abs(alpha))^p);\r\n fp=Nm*lgamma(1/p+1)-Nm/p*log(lambda)+lambda*Lp;\r\n phi=(2-p)*(lambda*(2-2*p)^(p-1))^(1/(2-p));\r\n \r\n phiN=sqrt(2*log(N));\r\n dN=phiN-(log(log(N))+log(4*pi)-2*log(2))/2/phiN;\r\n ct1=phiN*(phi/tau-dN);\r\n logG1=log(phiN/tau)-exp(-ct1)-ct1;\r\n dyl=(2-2*p)^((p-1)/(2-p))*lambda^((p-1)/(2-p))\r\n logG1=logG1+log(dyl);\r\n\r\n fp=fp-logG1; \r\n\r\n return(fp)\r\n}\n", "meta": {"hexsha": "8041ff58132e420ee6d5eaa28b4397e8c91828f4", "size": 9225, "ext": "r", "lang": "R", "max_stars_repo_path": "wavethresh.r", "max_stars_repo_name": "asadharis/waveMesh-Code", "max_stars_repo_head_hexsha": "af0c126959f63c249381b44e52c4d2caeacf0bc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wavethresh.r", "max_issues_repo_name": "asadharis/waveMesh-Code", "max_issues_repo_head_hexsha": "af0c126959f63c249381b44e52c4d2caeacf0bc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-11T17:51:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-17T10:43:50.000Z", "max_forks_repo_path": "wavethresh.r", "max_forks_repo_name": "asadharis/waveMesh-Code", "max_forks_repo_head_hexsha": "af0c126959f63c249381b44e52c4d2caeacf0bc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7605042017, "max_line_length": 146, "alphanum_fraction": 0.5177235772, "num_tokens": 3254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7166677576829807}} {"text": "\ndf = NULL\n\n# Fixed parameters\ns <- .2\nga <- .02\ngl <- .01\ndelta <- .05\nalpha <- .3\n\n# Initialize dynamic process\nkycurr <- 2 # initial capital stock\nkyalt <- 5 # initial capital stock\n\ndf = NULL # initialize a dataframe\ndfalt = NULL # initialize a dataframe\nname = \"A\"\nnamealt = \"B\"\n\nfor (t in 1:150) # do for this many periods\n{\n gky <- s*(1/kycurr)^(1-alpha) - delta #(1-alpha)*(s/kycurr - delta - ga - gl) # calculate growth in k given current k/al\n df = rbind(df, data.frame(t,kycurr,gky,name)) # add to dataframe\n kycurr <- (1+gky-ga-gl)*(kycurr)# update current k/y for next period\n gky <- s*(1/kyalt)^(1-alpha) - delta #(1-alpha)*(s/kyalt - delta - ga - gl)\n dfalt = rbind(dfalt, data.frame(t,kyalt,gky,namealt)) # add to dataframe\n kyalt <- (1+gky-ga-gl)*(kyalt)\n}\n\ncolnames(dfalt) <- c(\"t\",\"kycurr\",\"gky\",\"name\")\ndfgraph = rbind(df,dfalt)\n\n# Initialize theoretical relationship\nfig <- plot_ly(dfgraph,\n x = ~kycurr, \n y = ~gky, \n color = ~name,\n frame = ~t, \n text = ~t,\n hoverinfo = \"text\",\n type = 'scatter',\n mode = 'markers',\n marker = list(size = 15)\n )\nfig <- fig %>% animation_slider(\n hide = T\n)\nfig <- fig %>% animation_button(\n x = 1, xanchor = \"right\", y = 0.4, yanchor = \"bottom\"\n)\nfig <- layout(fig, title = list(text = 'Dynamics of capital growth', x=0),\n xaxis = list(title = 'K/AL ratio', range=c(1.5,5.5),dtick=.5),\n yaxis = list (title = 'Growth rate of K', range=c(0,0.1),dtick=.01\n )\n)\napi_create(fig, filename = \"me-gky-dynamics\")\n\ndfgraph <- dfgraph[with(dfgraph,order(kycurr)),]\n\nfig <- plot_ly(dfgraph, x = ~kycurr, y = ~gky, type = 'scatter', mode = 'lines')\nfig <- layout(fig, title = list(text = 'Relationship of growth and level of K/Y', x=0),\n xaxis = list(title = 'Capital/output ratio',range=c(0,4.5),dtick=.5),\n yaxis = list (title = 'Growth rate of capital/output ratio', range=c(-.1,0.25))\n)\napi_create(fig, filename = \"me-gky-relationship\")\n\n## Create evolving frames for graphing changes in growth rate\ndf = NULL\n\nfor (t in 1:30)\n{\n kycurr <- 2^(1-alpha)\n kyalt <- 5^(1-alpha)\n kybgp <- 2.5\n dftemp = NULL\n dfalt = NULL\n dfbgp = NULL\n\n for (k in 1:t) # do for this many periods\n {\n name <- \"A\"\n ky <- kycurr \n gky <- (1-alpha)*(s/ky - delta - ga - gl) # calculate growth in k/y given current k/y\n dftemp = rbind(dftemp, data.frame(t,k,ky,gky,name)) # add to dataframe\n kycurr <- (1+gky)*(ky) # update current k/y for next period\n name <- \"B\"\n ky <- kyalt \n gky <- (1-alpha)*(s/ky - delta - ga - gl)\n dfalt = rbind(dfalt, data.frame(t,k,ky,gky,name)) # add to dataframe\n kyalt <- (1+gky)*(ky) # update current k/y for next period\n name <- \"BGP\"\n ky <- kybgp\n gky <- (1-alpha)*(s/ky - delta - ga - gl)\n dfalt = rbind(dfalt, data.frame(t,k,ky,gky,name)) # add to dataframe\n kybgp <- (1+gky)*(ky) # update current k/y for next period\n }\n df = rbind(df,dftemp)\n df = rbind(df,dfalt)\n df = rbind(df,dfbgp)\n}\n\n\ndf$lny <- (alpha/(1-alpha))*log(df$ky) + 4 + df$k*ga\ndf$gy <- ga + (alpha/(1-alpha))*df$gky\n\ndf <-df[order(df$name, df$t, df$k),]\nfig <- plot_ly(df,\n x = ~k, \n y = ~lny, \n frame = ~t,\n color = ~name,\n hoverinfo = \"text\",\n type = 'scatter',\n mode = 'lines'\n)\nfig <- fig %>% animation_slider(\n hide = T\n)\nfig <- fig %>% animation_button(\n x = 1, xanchor = \"right\", y = 0.4, yanchor = \"bottom\"\n)\nfig <- layout(fig, title = list(text = 'Level of GDP per capita over time', x=0),\n xaxis = list(title = 'Time', range=c(0,30),dtick=5),\n yaxis = list (title = 'Log GDP per capita', range=c(4,5)\n )\n)\n\napi_create(fig, filename = \"me-lny-animated\")\n\nfig <- plot_ly(df,\n x = ~k, \n y = ~gy, \n frame = ~t,\n color = ~name,\n hoverinfo = \"text\",\n type = 'scatter',\n mode = 'lines'\n)\nfig <- fig %>% animation_slider(\n hide = T\n)\nfig <- fig %>% animation_button(\n x = 1, xanchor = \"right\", y = 0.4, yanchor = \"bottom\"\n)\nfig <- layout(fig, title = list(text = 'Growth rate of GDP per capita over time', x=0),\n xaxis = list(title = 'Time', range=c(0,30),dtick=5),\n yaxis = list (title = 'Growth rate of GDP per capita', range=c(0,.05)\n )\n)\n\napi_create(fig, filename = \"me-gy-animated\")", "meta": {"hexsha": "f2b09eb083e97c18983b01869fa2a2562d6dd34b", "size": 4462, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Guide_ME_gKY.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/Guide_ME_gKY.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Guide_ME_gKY.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 29.5496688742, "max_line_length": 123, "alphanum_fraction": 0.5593904079, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7165138099458989}} {"text": "# ......................................................................................\n# ...................Exercise 11. Two-sample tests/Interval estimates ..................\n# ..........................Michal Béreš, Martina Litschmannová.........................\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# Overview of confidence intervals and hypothesis tests and their constructions ####\n# \n# * Two columns of data - pairs/independent ####\n# \n# - Paired data indicates data that are taken as two measurements of the same entities\n# -> data columns are dependent.\n# - For paired data, we calculate the difference between the columns(or another\n# function according to the input) and use one-sample tests for this difference.\n# \n# - If there is no dependency between values in the two columns the data are\n# independent. \n# - Two-sample test is needed\n\n\n# ** Examples of paired data: ####\n# \n# - measuring bulbs at two different temperatures(if each piece is measured twice - at\n# temperature 1 and temperature 2)\n# \n# - be careful here, it can happen that the tests are eg. destructive and it is not\n# possible to measure twice the same entity(product). Then we would consider two\n# independent selections, each for one type of measurement -> independent data columns\n# -> two-sample tests\n# \n# - measurement of the patient's blood values before and after drug administration\n# \n# - again pay attention to, for example, drug testing in two groups(placebo/real drug)\n# ->two independent groups -> two-sample tests\n\n\n# * In general for two-sample tests/CI ####\n# \n# - the test is always tied to the appropriate CI -> same conditions of use\n# \n# - if the test has conditions of use(eg: normality of data, symmetry of data) then this\n# condition must be met **for both data columns**, if at least one does not meet, we\n# consider the assumption to be broken\n# \n# - one of the very important assumptions is data independence\n# \n# - eg: measurement of products of manufacturer A and products of manufacturer B - here\n# it is reasonable to assume that the products of manufacturer A are separate entities\n# from the products of manufacturer B\n\n\n# * Two-sample tests/IO - difference of position measures ####\n# \n\n\n# we create test data\ndata1 = rnorm(n = 30, mean = 105, sd = 10)\ndata2 = rnorm(n = 30, mean = 100, sd = 10)\nboxplot(data1,data2)\n\n# ** Two-sample Student's t-test ####\n# \n# - Tests/estimates difference of means: $H_0: \\mu_{1} - \\mu_{2} = a$\n# - requirements:\n# - Data normality\n# - Homoskedasticity(scatter matching)\n# - independence of selections\n# - the function must have the parameter var.equal=TRUE\n\n\n# H0: mu1 - mu2=2\n# HA: mu1 - mu2!=2\n\nt.test(x = data1, y = data2, mu = 2, alternative = \"two.sided\",\n var.equal = TRUE, conf.level = 0.95)\n\n# H0: mu1 - mu2=2\n# HA: mu1 - mu2>2\n\nt.test(x = data1, y = data2, mu = 2, alternative = \"greater\",\n var.equal = TRUE, conf.level = 0.95)\n\n# H0: mu1 - mu2=2\n# HA: mu1 - mu2<2\n\nt.test(x = data1, y = data2, mu = 2, alternative = \"less\",\n var.equal = TRUE, conf.level = 0.95)\n\n# ** Aspin-Welsh test ####\n# \n# - Tests/estimates the difference of means: $H_0: \\mu_{1} - \\mu_{2} = a$\n# - requirements:\n# - Data normality\n# - independence of selections\n# - the function must have the parameter var.equal=FALSE\n\n\n# H0: mu1 - mu2=2\n# HA: mu1 - mu2!=2\n\nt.test(x = data1, y = data2, mu = 2, alternative = \"two.sided\",\n var.equal = FALSE, conf.level = 0.95)\n\n# H0: mu1 - mu2=2\n# HA: mu1 - mu2>2\n\nt.test(x = data1, y = data2, mu = 0, alternative = \"greater\",\n var.equal = FALSE, conf.level = 0.95)\n\n# H0: mu1 - mu2=2\n# HA: mu1 - mu2<2\n\nt.test(x = data1, y = data2, mu = 0, alternative = \"less\",\n var.equal = FALSE, conf.level = 0.95)\n\n# ** Mann-Whitney test ####\n# \n# - Tests/estimates difference of medians: $H_0: X_{0.5,1} - X_{0.5,2} = a$\n# - requirements:\n# - independence of selections\n# - (same shape of the distribution)\n# - requires conf.int=TRUE, to calculate CI\n\n\n# H0: X0.5,1 - X0.5,2=2\n# HA: X0.5,1 - X0.5,2!=2\n\nwilcox.test(x = data1, y = data2, mu = 2, alternative = \"two.sided\",\n conf.level=0.95, conf.int = TRUE)\n\n# H0: X0.5,1 - X0.5,2=2\n# HA: X0.5,1 - X0.5,2>2\n\nwilcox.test(x = data1, y = data2, mu = 2, alternative = \"greater\",\n conf.level=0.95, conf.int = TRUE)\n\n# H0: X0.5,1 - X0.5,2=2\n# HA: X0.5,1 - X0.5,2<2\n\nwilcox.test(x = data1, y = data2, mu = 2, alternative = \"less\",\n conf.level=0.95, conf.int = TRUE)\n\n# * Two-sample tests/CI - proportion of variances ####\n# \n# ** F-test ####\n# \n# - Tests/estimates the ratio of variances: $H_0: \\sigma^2_{1} / \\sigma^2_{2} = a$\n# - requirements:\n# - data normality\n# - independence of selections\n\n\n# H0: sigma1 ^ 2/sigma2 ^ 2=1\n# H0: sigma1 ^ 2/sigma2 ^ 2!=1\n\nvar.test(x = data1, y = data2, ratio = 1, alternative = \"two.sided\",\n conf.level = 0.95)\n\n# H0: sigma1 ^ 2/sigma2 ^ 2=1\n# H0: sigma1 ^ 2/sigma2 ^ 2>1\n\nvar.test(x = data1, y = data2, ratio = 1, alternative = \"greater\",\n conf.level = 0.95)\n\n# H0: sigma1 ^ 2/sigma2 ^ 2=1\n# H0: sigma1 ^ 2/sigma2 ^ 2<1\n\nvar.test(x = data1, y = data2, ratio = 1, alternative = \"less\",\n conf.level = 0.95)\n\n# ** Levene's test ####\n# \n# - Tests equality of variances: $H_0: \\sigma^2_{1} = \\sigma^2_{2}$!\n# - requirements:\n# - independence of selections\n# - requires data in standard data format \n# - leveneTest function in the car package\n\n\n# we produce data in a standard data format\n\ndata1.df = as.data.frame(data1)\ndata1.df$typ = \"d1\"\ncolnames(data1.df) = c(\"data\", \"typ\")\n\ndata2.df = as.data.frame(data2)\ndata2.df$typ = \"d2\"\ncolnames(data2.df) = c(\"data\", \"typ\")\n\ndata = rbind(data1.df, data2.df)\ndata$typ = as.factor(data$typ)\n\nhead(data)\n\n# install.packages(\"car\")\n\n# H0: sigma1 ^ 2=sigma2 ^ 2\n# HA: sigma1 ^ 2!=Sigma2 ^ 2\n\ncar::leveneTest(data$data ~ data$typ)\n\n# * Two-sample tests/CI - difference of probabilities ####\n# \n# ** Test of parameter of two binomial distributions ####\n# \n# - Tests if the probability matches: $H_0: \\pi_{1} - \\pi_{2} = 0$\n# - requirements:\n# - sufficient selection size: $n_i>\\frac{9}{p_i(1-p_i)}$\n# - independence of selections\n\n\n# we will produce suitable data\npi1 = 0.4\npi2 = 0.3\n\ndp1 = runif(n = 100, min = 0, max = 1) < pi1\ndp2 = runif(n = 130, min = 0, max = 1) < pi2\n\nx1 = sum(dp1)\nn1 = length(dp1)\n\nx2 = sum(dp2)\nn2 = length(dp2)\n\nx1\nn1\nx2\nn2\n\n# H0: pi1 - pi2=0\n# HA: pi1 - pi2!=0\n\nprop.test(x = c(x1, x2), n = c(n1, n2), alternative=\"two.sided\",\n conf.level=0.95)\n\n# H0: pi1 - pi2=0\n# HA: pi1 - pi2>0\n\nprop.test(x = c(x1, x2), n = c(n1, n2), alternative=\"greater\",\n conf.level=0.95)\n\n# H0: pi1 - pi2=0\n# HA: pi1 - pi2<0\n\nprop.test(x = c(x1, x2), n = c(n1, n2), alternative=\"less\",\n conf.level=0.95)\n\n# Examples ####\n\n\nlibrary(dplyr)\nlibrary(rstatix)\n\n# \n# * Example 1. ####\n# \n# Data in the cholesterol2.xls file indicate the blood cholesterol level of men of two\n# different age groups(20-30 years and 40-50 years). Verify at the significance level\n# 0.05 the hypothesis that the cholesterol level in the blood of older men does not\n# differ from the cholesterol level in the blood of younger men.\n\n\n# Load data\nchol = readxl::read_excel(\"data/testy_dvouvyberove.xlsx\",\n sheet = \"cholesterol2\",\n skip = 1) \ncolnames(chol)=c(\"young\",\"old\")\nhead(chol)\n\n# Convert to standard data format\nchol.s = stack(chol)\nchol.s = na.omit(chol.s)\ncolnames(chol.s) = c (\"values\",\"group\")\nhead(chol.s)\n\n# Exploratory analysis\nboxplot(chol.s$values ~ chol.s$group)\n\n# Elimination of outliars:\nchol.s$id = seq(1,length(chol.s$values))\n\noutliars = chol.s %>% group_by(group) %>% identify_outliers(values)\noutliars\n\nchol.s$values_cleared = ifelse(chol.s$id %in% outliars$id, NA, chol.s$values)\n\nboxplot(chol.s$values_cleared~chol.s$group)\n\n# be careful in the data we have NA\n# eg for length determination\n\nchol.s %>% group_by(group) %>% \n summarise(count = sum(!is.na(values_cleared)),\n mean = mean(values_cleared, na.rm = TRUE), \n std = sd(values_cleared, na.rm = TRUE))\n\n# rounding ->3 valid digits ->according to sd to thousands\n\n\n# **Difference of Mean/median test**\n\n\n# Verification of normality\nchol.s %>% group_by(group) %>% \n summarise(norm.pval = shapiro.test(values_cleared)$p.value)\n\n# normality at significance 0.05 OK\n\n\n# Exactly by F-test\n\n# H0: sigma.old=sigma.young\n# Ha: sigma.old<>sigma.young\n\n# I select the required data\nyoung = chol.s$values_cleared[chol.s$group == \"young\"]\nold = chol.s$values_cleared[chol.s$group == \"old\"]\n\nvar.test(x = young, y = old, ratio = 1, conf.level=0.95)\n\n# at. significance 0.05 we reject the assumption of same variances\n# The observed discrepancy between the variances is significant at the significance level of 0.05\n# Mark as statistically significant.\n\n\n# Verification of same mean values(Aspin-Welch test)\n\n# H0: mu.old - mu.young=0\n# Ha: mu.old - mu.young!=0\n\nt.test(x = old, y = young, mu = 0, \n alternative = \"two.sided\", var.equal=FALSE, conf.level=0.95)\n\n# in hl. significance 0.05 we reject H0->there is a stat. significant difference.\n\n\n# H0: mu.old=mu.young\n# Ha: mu.old>mu.young\n\nt.test(x = old, y = young, mu = 0, alternative = \"greater\",\n var.equal = FALSE, conf.level = 0.95)\n\n# * Example 2. ####\n# \n# The data in the depression.xls file represent the length of remission in days from a\n# simple random selection of two different groups of patients(patients with endogenous\n# depression and patients with neurotic depression). Verify that the observed difference\n# in mean remission length in these two groups of patients is statistically significant.\n# \n\n\n# Read data from xlsx file(using readxl package)\ndeprese = readxl::read_excel(\"data/testy_dvouvyberove.xlsx\",\n sheet = \"deprese\") \ncolnames(deprese)=c(\"endo\",\"neuro\")\n\nhead(deprese)\n\n# Conversion to standard data format\ndeprese.s = stack(deprese)\ndeprese.s = na.omit(deprese.s)\ncolnames(deprese.s) = c (\"values\",\"group\")\n\nhead(deprese.s)\n\n# Exploratory analysis\nboxplot(deprese.s$values~deprese.s$group)\n\n# Data does not contain outliers\n\n\nlibrary(dplyr)\n\ndeprese.s %>% group_by(group) %>% \n summarise(count = length(values),\n mean = mean(values), \n std = sd(values))\n\n# rounding ->3 valid digits ->according to sd\n\n\n# **Diference of Mean/median test**\n# \n\n\n# Normality verification\n# We assume the assumption of normality by the Shapir - Wilk test.\ndeprese.s %>% group_by(group) %>% \n summarise(norm.pval = shapiro.test(values)$p.value)\n\n\n# at significance 0.05, we reject the assumption of normality\n\n\n# at least as a guide, we check the similarity of the distribution\n\n# we choose data for easier processing\n\nneuro = deprese.s$values[deprese.s$group == \"neuro\"]\nendo = deprese.s$values[deprese.s$group == \"endo\"]\n\n\npar(mfrow = c(1,2))\nhist(neuro)\nhist(endo)\n\n# Difference of median (Mann-Whitney test)\n\n# According to the histograms, we assume that the data have the same type of distribution.\n\n# H0: med.neuro=med.endo(med.neuro - med.endo=0)\n# Ha: med.neuro!=Med.endo(med.neuro - med.endo!=0)\n\nwilcox.test(x = neuro, y = endo, mu = 0, alternative = \"two.sided\",\n conf.level=0.95, conf.int = TRUE)\n\n# at significance 0.05 we reject H0->there is a stat. significant difference\n\n\n# H0: med.neuro=med.endo(med.neuro - med.endo=0)\n# Ha: med.neuro>med.endo(med.neuro - med.endo>0)\n\nwilcox.test(x = neuro, y = endo, mu = 0, alternative = \"greater\",\n conf.level=0.95, conf.int = TRUE)\n\n# * Example 3. ####\n# \n# We monitor urine osmolality at the patient station at 08:00 and 11:00 for 16 men.\n# Based on the results in the osmolality.xls file, verify that the osmolality has\n# increased statistically significantly.\n# \n\n\n# Load data\nosmolalita = readxl::read_excel(\"data/testy_dvouvyberove.xlsx\",\n sheet = \"osmolalita\", skip = 1) \nosmolalita = osmolalita[,c(2,3)]\ncolnames(osmolalita)=c(\"o8\",\"o11\")\nhead(osmolalita)\n\n# Calculation of osmolality increase\nosmolalita$increase = osmolalita$o11 - osmolalita$o8\n\n# Exploratory analysis\npar(mfrow = c(1,1))\nboxplot(osmolalita$increase)\n\n# Data contains outliars\n\n\n# Elimination of outliars:\nosmolalita$id = seq(1,length(osmolalita$increase))\n\noutliars = osmolalita %>% identify_outliers(increase)\noutliars\nosmolalita$increase_cleared = ifelse(osmolalita$id %in% outliars$id, NA, osmolalita$increase)\n\nboxplot(osmolalita$increase_cleared)\n\n# Exploratory analysis for data without outliars\nlibrary(dplyr)\n\nosmolalita %>% summarise(count = sum(!is.na(increase_cleared)),\n mean = mean(increase_cleared, na.rm = TRUE), \n std = sd(increase_cleared, na.rm = TRUE))\n\n# rounding ->2 valid digits ->according to sd per unit\n\n\n# Verification of normality\n# The presumption of normality is verified by the Shapir - Wilk test.\nshapiro.test(osmolalita$increase_cleared)\n\n# Paired t-test\n# H0: mu.increase=0 mm\n# Ha: mu.increase>0 mm\n\nt.test(osmolalita$increase_cleared, mu = 0, alternative = \"greater\")\n\n# * Example 4. ####\n# \n# Semiconductor components of two manufacturers - MM and PP - were tested. MM claims\n# that its products have a lower percentage of defective pieces. To verify this claim,\n# 200 components were randomly selected from MM production, of which 14 were defective.\n# A similar experiment was performed at PP with the result of 10 defective out of 100\n# randomly selected components.\n# \n# ** a) ####\n# \n# Test MM's claim with a clean significance test.\n# \n\n\nx.MM = 14\nn.MM = 200\np.MM = x.MM/n.MM\np.MM\n\nx.PP = 10\nn.PP = 100\np.PP = x.PP/n.PP\np.PP\n\n# Verification of assumptions\n9/(p.MM*(1-p.MM))\n9/(p.PP*(1-p.PP))\n\n# Pearson's X2 test\n# H0: pi.PP=pi.MM\n# Ha: pi.PP>pi.MM\n\nprop.test(x = c(x.PP,x.MM),n = c(n.PP,n.MM), alternative = \"greater\",\n conf.level = 0.95)\n\n# at significance 0.05 we do not reject H0 - ie assumption.\n# identical error rates. Therefore, it cannot be said that MM has better production.\n\n\n# Pearson's X2 test\n# H0: pi.PP=pi.MM\n# Ha: pi.PP!=Pi.MM\n\nprop.test(x = c(x.PP,x.MM),n = c(n.PP,n.MM), alternative = \"two.sided\",\n conf.level = 0.95)\n\n# ** b) ####\n# \n# Test MM's statement using an interval estimate of a significance level of 0.05.\n# \n\n\n# Based on 95% Clopper - Pearson right - hand interval estimation\n# -0.036; 1,000) the observed difference in production quality can be described as\n# not statistically significant. We can reach the same conclusions on the basis of\n# Pearson's right-hand test\nprop.test(x = c(x.PP,x.MM),n = c(n.PP,n.MM), alternative = \"two.sided\",\n conf.level = 0.95)\n\n\n\n", "meta": {"hexsha": "5739ff7f143a085fbfabd15b4d0a9ca927e7df04", "size": 14959, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 11/T13_hypothesis_testing2.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exercise 11/T13_hypothesis_testing2.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise 11/T13_hypothesis_testing2.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 27.4981617647, "max_line_length": 97, "alphanum_fraction": 0.6499097533, "num_tokens": 4572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8104789178257653, "lm_q1q2_score": 0.716495195432722}} {"text": "# Transform model output to the Akaike Information Criterion (AIC) and the \n# Bayesian Information Criterion (BIC), as well as their respective transformations \n# to Akaike weights and approximat posterior model probabilities.\n\n# For details on Akaike Weights, see Wagenmakers, E.-J., & Farrell, S. (2004). \n# Model selection using Akaike weights. Psychonomic Bulletin & Review, 11, 192-196.\n# For details on the BIC-based approximation to posterior model probabilities, \n# see Wasserman, L. (2000). Bayesian model selection and averaging. \n# Journal of Mathematical Psychology, 44, 92-107. \n\nsource(\"chartr-HelperFunctions.r\")\n# Function to calculate model weights\n#\n# \npmp=function(IC) {\n # IC is the information criteria (AIC or BIC) for a set of models under comparison\n x=(IC-min(IC))\n # PMP is the posterior model probability\n pmp=exp(-.5*x)/sum(exp(-.5*x)) \n pmp \n}\n\ncalcIC = function(ll, npars, N)\n{\n \n # Calculate the information criteria for the models\n # AIC just penalizes number of parameters\n AIC = 2*npars - 2*ll;\n \n # BIC also penalizes by number of parameters,but also includes \n # a penalty of the number of trials used for computing the penalty\n BIC = log(N)*npars - 2*ll;\n \n data.frame(AIC=AIC, BIC=BIC, LL=-2*ll, PenA = 2*npars,PenB=log(N)*npars);\n}\n\n# Calculate AIC/BIC and their conversion to model weights \n#\n#\nmodelSelection=function(models,data) {\n # models is a list where each element holds the output from a model fit\n # data is a single subjects data informations\n npars=sapply(models,function(x) length(x$pars))\n ll=sapply(models,function(x) x$reobj)\n N=sum(dat$n)\n AIC=2*npars - 2*ll\n logL = -2*ll\n BIC=log(N)*npars - 2*ll\n AICw=pmp(AIC)\n BICw=pmp(BIC)\n logLw=pmp(logL);\n data.frame(AIC,BIC,AICw,BICw, N, logL,logLw, npars)\n}\n\n# This formats columns of data frames with different columns having different numbers of digits if needed.\n# \n#\n# \nformatColumns = function(data, digits)\n{\n \"%,%\" <- function(x,y)paste(x,y,sep=\"\")\n nms <- names(data)\n nc <- ncol(data)\n nd <- length(digits)\n if(nc!=nd) \n stop(\"Argument 'digits' must be vector of length \" %,% \n nc %,% \", the number of columns in 'data'.\")\n out <- as.data.frame(sapply(1:nc, \n FUN=function(x, d, Y)\n format(Y[,x], digits=d[x]), Y=tbl, d=digits))\n if(!is.null(nms)) names(out) <- nms\n out\n}\n", "meta": {"hexsha": "6405037d2336b4257d5307e1cf115ff686210864", "size": 2420, "ext": "r", "lang": "R", "max_stars_repo_path": "chartr-ModelSelection.r", "max_stars_repo_name": "mailchand/CHaRTr", "max_stars_repo_head_hexsha": "ba0f581b281ee531494e89be729831c5ce802152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-04-13T12:39:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T00:52:57.000Z", "max_issues_repo_path": "chartr-ModelSelection.r", "max_issues_repo_name": "mailchand/CHaRTr", "max_issues_repo_head_hexsha": "ba0f581b281ee531494e89be729831c5ce802152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-05T00:10:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T14:19:43.000Z", "max_forks_repo_path": "chartr-ModelSelection.r", "max_forks_repo_name": "mailchand/CHaRTr", "max_forks_repo_head_hexsha": "ba0f581b281ee531494e89be729831c5ce802152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-07-31T14:41:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-30T20:40:36.000Z", "avg_line_length": 32.7027027027, "max_line_length": 106, "alphanum_fraction": 0.6673553719, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025425, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7164507733236186}} {"text": "### Code skeleton for Series 7, task 2\n\n## Read in dataset, set seed, load package\nIris <- iris[,c(\"Petal.Length\", \"Petal.Width\", \"Species\")]\ngrIris <- as.integer(Iris[, \"Species\"])\nset.seed(16)\nlibrary(MASS)\n\n## Read n\nn <- nrow(Iris)\n\n## Utility functiom for plotting boundaries\npredplot <- function(object, x, gr = grIris, main = \"\", lines.only = FALSE,\n len = 42, colcont = \"black\", ...)\n{\n ## gr : the true grouping/class vector\n stopifnot(length(gr) == nrow(x))\n xp <- seq(min(x[, 1]), max(x[, 1]), length = len)\n yp <- seq(min(x[, 2]), max(x[, 2]), length = len)\n grid <- expand.grid(xp, yp)\n colnames(grid) <- colnames(x)[-3]\n Z <- predict(object, grid, ...)\n zp <- as.numeric(Z$class)\n zp <- Z$post[, 3] - pmax(Z$post[, 2], Z$post[, 1])\n if(!lines.only)\n plot(x[,1], x[,2], col = gr, pch = gr,\n main = main, xlab = colnames(x)[1], ylab = colnames(x)[2])\n contour(xp, yp, matrix(zp, len),\n add = TRUE, levels = 0, drawlabels = FALSE, col = colcont)\n zp <- Z$post[, 1] - pmax(Z$post[, 2], Z$post[, 3])\n contour(xp, yp, matrix(zp, len),\n add = TRUE, levels = 0, drawlabels = FALSE, col = colcont)\n}\n## Bootstrap size\nB <- 1000\n\n\n\n\n###################################################\n### TASK a)\n###################################################\n\n## Use function lda to fit data\nclass_lda <- lda(x = Iris[, -3], grouping = grIris)\n\n## Use function predplot to plot the boundaries\npredplot(class_lda, Iris, main = \"Classification with LDA\")\n\n## Use function qda to fit data\nclass_qda <- qda(x = Iris[, -3], grouping = grIris)\n\n## Use function predplot to plot the boundaries\npredplot(class_qda, Iris, main = \"Classification with QDA\")\n\n\n###################################################\n### TASKS b)\n###################################################\n\n## Create a random index matrix with either functions sample or sample.int to generate bootstrap\n## Each column corresponds to the n indices of one bootstrap sample\nindex <- matrix(sample.int(n, size = n * B, replace = TRUE), nrow=n, ncol=B)\n\n## Initialize the list for LDA and QDA fits\nfit_lda <- vector(\"list\", B)\nfit_qda <- vector(\"list\", B)\n\n\n## Use both methods on the bootstrap samples\nfor(i in 1:B) {\n ind <- index[, i]\n fit_lda[[i]] <- lda(x = Iris[ind, -3], grouping = grIris[ind])\n fit_qda[[i]] <- qda(x = Iris[ind, -3], grouping = grIris[ind])\n}\n\n## Initialize the mu_hat bootstrap estimates\nmu_hat_1 <- mu_hat_2 <- mu_hat_3 <- matrix(0, ncol = B, nrow = 2)\n\n## Determine the mu_hat bootstrap estimates\n\nfor(i in 1:B){\n ## Hint: look at fit_lda[[1]] and see how to extract the means\n mu_hat_all <- fit_lda[[i]]$means\n mu_hat_1[, i] <- mu_hat_all[1,]\n mu_hat_2[, i] <- mu_hat_all[2,]\n mu_hat_3[, i] <- mu_hat_all[3,]\n}\n\n## Plot the bootstrapped estimators\n## define a suitable plotting range\nxmin <- min(mu_hat_1[1,], mu_hat_2[1,], mu_hat_3[1,])\nxmax <- max(mu_hat_1[1,], mu_hat_2[1,], mu_hat_3[1,])\nymin <- min(mu_hat_1[2,], mu_hat_2[2,], mu_hat_3[2,])\nymax <- max(mu_hat_1[2,], mu_hat_2[2,], mu_hat_3[2,])\n## plot the estimated mean of each group\nplot(mu_hat_1[1,], mu_hat_1[2,], xlim = c(xmin, xmax), ylim = c(ymin, ymax),\n xlab = colnames(Iris)[1], ylab = colnames(Iris)[2], pch = 4,\n main = \"Bootstrap samples\")\npoints(mu_hat_2[1,], mu_hat_2[2,], col = 2, pch = 4)\npoints(mu_hat_3[1,], mu_hat_3[2,], col = 3, pch = 4)\n\n\n###################################################\n### TASK c)\n###################################################\n\n## Plot the bootstrapped boundaries estimates with LDA\npredplot(class_lda, Iris,\n main = \"Bootstrapped boundaries estimates with LDA\")\nfor(i in 1:B){\n fit <- fit_lda[[i]]\n predplot(fit, Iris, lines.only = TRUE, colcont = adjustcolor(\"gray\", 0.25))\n}\n\n\n\n## Plot the bootstrapped boundaries estimates with QDA\npredplot(class_qda, Iris,\n main= \"Bootstrapped boundaries estimates with QDA\")\nfor(i in 1:B){\n fit <- fit_qda[[i]]\n predplot(fit, Iris, lines.only = TRUE, colcont = adjustcolor(\"gray\", 0.25))\n}\n\n###################################################\n### TASK d)\n###################################################\n\n\n## write your own LOOCV code\n\ncnt_lda = 0\ncnt_qda = 0\nfor (i in 1:n){\n fit_lda_loocv <- lda(x = Iris[-i, -3], grouping = grIris[-i])\n cnt_lda = cnt_lda + as.integer(predict(fit_lda_loocv, Iris[i, -3])$class != grIris[i])\n fit_qda_loocv <- qda(x = Iris[-i, -3], grouping = grIris[-i])\n cnt_qda = cnt_qda + as.integer(predict(fit_qda_loocv, Iris[i, -3])$class != grIris[i])\n}\nprint(cnt_lda)\nprint(cnt_qda)\n", "meta": {"hexsha": "ae6882428511a0894b8e53a6f174832032a6edb3", "size": 4541, "ext": "r", "lang": "R", "max_stars_repo_path": "Computational_Statistics/Exercices/7_2.r", "max_stars_repo_name": "DanDoge/course_ethz", "max_stars_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Computational_Statistics/Exercices/7_2.r", "max_issues_repo_name": "DanDoge/course_ethz", "max_issues_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computational_Statistics/Exercices/7_2.r", "max_forks_repo_name": "DanDoge/course_ethz", "max_forks_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7552447552, "max_line_length": 96, "alphanum_fraction": 0.5787271526, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7164507580730773}} {"text": "primes <- c(2, 3, 5, 7, 11, 13)\nisPrime <- function(a) {\n i <- 1\n while (a %% primes[i] > 0) {\n if (primes[i] * primes[i] > a) {\n primes <<- append(primes, a)\n return(TRUE)\n }\n i <- i + 1\n }\n FALSE\n}\n\nprimeSeq <- function() {\n p0 <- 1\n i <- 0\n return(function() {\n if (p0 <= length(primes)) {\n i <<- primes[p0]\n p0 <<- p0 + 1\n return(i)\n }\n i <<- i + 2\n while (!isPrime(i)) {\n i <<- i + 2\n }\n p0 <<- p0 + 1\n return(i)\n })\n}\n\nprimesum <- 0\nnextPrime <- primeSeq()\nfor (i in 1:1000) {\n primesum = primesum + nextPrime()\n}\ncat(primesum, sep=\"\\n\")\n", "meta": {"hexsha": "f4ebfffcc601ea0e57526a584dff20fb9bdd090b", "size": 613, "ext": "r", "lang": "R", "max_stars_repo_path": "easy/sum_prime.r", "max_stars_repo_name": "IlkhamGaysin/ce-challenges", "max_stars_repo_head_hexsha": "ac6b8c1fc4b6c098e380b9d694e93e614f6c969b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-06-24T17:09:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-03T11:44:54.000Z", "max_issues_repo_path": "easy/sum_prime.r", "max_issues_repo_name": "IlkhamGaysin/ce-challenges", "max_issues_repo_head_hexsha": "ac6b8c1fc4b6c098e380b9d694e93e614f6c969b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "easy/sum_prime.r", "max_forks_repo_name": "IlkhamGaysin/ce-challenges", "max_forks_repo_head_hexsha": "ac6b8c1fc4b6c098e380b9d694e93e614f6c969b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.1315789474, "max_line_length": 36, "alphanum_fraction": 0.4584013051, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7164080634497959}} {"text": "#' Computes the dot product of two iterable objects\n#'\n#' Returns the dot product of two numeric iterables of equal length\n#'\n#' @importFrom iterators iter\n#' @export\n#' @param vec1 the first\n#' @param vec2 the second iterable object\n#' @return the dot product of the iterators\n#'\n#' @examples\n#' it <- iterators::iter(1:3)\n#' it2 <- iterators::iter(4:6)\n#' dotproduct(it, it2) # 32\n#'\n#' it <- iterators::iter(1:4)\n#' it2 <- iterators::iter(7:10)\n#' dotproduct(1:4, 7:10) # 90\n#'\ndotproduct <- function(vec1, vec2) {\n vec1 <- iterators::iter(vec1)\n vec2 <- iterators::iter(vec2)\n it <- imap(prod, vec1, vec2)\n sum(sapply(it, identity))\n}\n", "meta": {"hexsha": "e97ce7bc376caf175ccfa061fe9c13e2adbe99b9", "size": 643, "ext": "r", "lang": "R", "max_stars_repo_path": "R/dotproduct.r", "max_stars_repo_name": "ramhiser/itertools2", "max_stars_repo_head_hexsha": "471515f4e8cf0aa48cc6402741ad3feccca94a9b", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-02-02T02:54:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T12:07:34.000Z", "max_issues_repo_path": "R/dotproduct.r", "max_issues_repo_name": "ramhiser/itertools2", "max_issues_repo_head_hexsha": "471515f4e8cf0aa48cc6402741ad3feccca94a9b", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2015-01-07T15:36:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-18T18:01:36.000Z", "max_forks_repo_path": "R/dotproduct.r", "max_forks_repo_name": "ramhiser/itertools2", "max_forks_repo_head_hexsha": "471515f4e8cf0aa48cc6402741ad3feccca94a9b", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-02-02T05:04:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T02:13:12.000Z", "avg_line_length": 24.7307692308, "max_line_length": 67, "alphanum_fraction": 0.6594090202, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7162124321390788}} {"text": "\r\n\r\n# Goal: Simulate a dataset from the OLS model and obtain\r\n# obtain OLS estimates for it.\r\n\r\nx <- runif(100, 0, 10) # 100 draws from U(0,10)\r\ny <- 2 + 3*x + rnorm(100) # beta = [2, 3] and sigma = 1\r\n\r\n# You want to just look at OLS results?\r\nsummary(lm(y ~ x))\r\n\r\n# Suppose x and y were packed together in a data frame --\r\nD <- data.frame(x,y)\r\nsummary(lm(y ~ x, D))\r\n\r\n# Full and elaborate steps --\r\nd <- lm(y ~ x)\r\n# Learn about this object by saying ?lm and str(d)\r\n# Compact model results --\r\nprint(d)\r\n# Pretty graphics for regression diagnostics --\r\npar(mfrow=c(2,2))\r\nplot(d)\r\n\r\nd <- summary(d)\r\n# Detailed model results --\r\nprint(d)\r\n# Learn about this object by saying ?summary.lm and by saying str(d)\r\ncat(\"OLS gave slope of \", d$coefficients[2,1],\r\n \"and a error sigma of \", d$sigma, \"\\n\")\r\n\r\n\r\n## I need to drop down to a smaller dataset now --\r\nx <- runif(10)\r\ny <- 2 + 3*x + rnorm(10)\r\nm <- lm(y ~ x)\r\n\r\n# Now R supplies a wide range of generic functions which extract\r\n# useful things out of the result of estimation of many kinds of models.\r\n\r\nresiduals(m)\r\nfitted(m)\r\nAIC(m)\r\nAIC(m, k=log(10)) # SBC\r\nvcov(m)\r\nlogLik(m)\r\n\r\n", "meta": {"hexsha": "240c30f44ef62fcca0d3b33879c69abfa73a505b", "size": 1206, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o1.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o1.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o1.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.125, "max_line_length": 73, "alphanum_fraction": 0.6019900498, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7162124200993111}} {"text": "=begin\n # sample-m-polynomial01.rb\n\n require \"algebra\"\n P = MPolynomial(Integer)\n x, y, z, w = P.vars(\"xyz\")\n p((-x + y + z)*(x + y - z)*(x - y + z))\n #=> -x^3 + x^2y + x^2z + xy^2 - 2xyz + xz^2 - y^3 + y^2z + yz^2 - z^3\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "0a7a7ce43f1e60f99a9d412b88c18f2ee38faeac", "size": 249, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-m-polynomial01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-m-polynomial01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-m-polynomial01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6363636364, "max_line_length": 71, "alphanum_fraction": 0.4859437751, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9597620562254524, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.7161158941811823}} {"text": "## 2. Programming in R ##\n\n125-3\n\n## 3. R Syntax Rules ##\n\n224+667\n35/7\n(22*5)+3\n\n## 4. Exploring Data With R ##\n\n(92 + 87 + 85) / 3 # math\n(90 + 81 + 92) / 3 # chemistry\n(84 + 95 + 79) / 3 # writing\n(95 + 86 + 93) / 3 # art\n(77 + 85 + 90) / 3 # history\n(92 + 90 + 91) / 3 # music\n(85 + 88 + 95) / 3 # physical education\n\n## 5. Assigning Values to Variables ##\n\nmath <- 88\nchemistry <- 87.66667\nwriting <- 86\nart <- 91.33333\nhistory <- 84\nmusic <- 91\nphysical_education <- 89.33333\n\n## 6. Programming With Variables ##\n\nmath <- 88 \nchemistry <- 87.66667\nwriting <- 86\nart <- 91.33333\nhistory <- 84\nmusic <- 91\nphysical_education <- 89.33333\ngpa<-(math+chemistry+writing+art+history+music+physical_education)/7\n\n## 7. Vectors: Storage for Multiple Values ##\n\nmath <- 88 \nchemistry <- 87.66667\nwriting <- 86\nart <- 91.33333\nhistory <- 84\nmusic <- 91\nphysical_education <- 89.33333\nfinal_scores<-c(math,chemistry,writing,art,history,music,physical_education)\n\n## 8. Efficient Programming with Functions and Vectors ##\n\nfinal_scores <- c(math, chemistry, writing, art, history, music, physical_education)\ngpa<-mean(final_scores)\n\n## 9. Practice with Functions and Vectors ##\n\nfinal_scores <- c(math, chemistry, writing, art, history, music, physical_education)\nmax(final_scores)\nmin(final_scores)\nlength(final_scores)", "meta": {"hexsha": "c6bd3bc2c138b45a59ffa28445dfbdf3c0781420", "size": 1314, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction to Programming in R-332.r", "max_stars_repo_name": "saquibmehmood/Data-Projects", "max_stars_repo_head_hexsha": "136fbcd46f728e09c627f690fa1fa6c1d71c3ad2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-29T10:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T10:41:57.000Z", "max_issues_repo_path": "Introduction to Programming in R-332.r", "max_issues_repo_name": "saquib-mehmood/R_basics_to_advanced", "max_issues_repo_head_hexsha": "136fbcd46f728e09c627f690fa1fa6c1d71c3ad2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction to Programming in R-332.r", "max_forks_repo_name": "saquib-mehmood/R_basics_to_advanced", "max_forks_repo_head_hexsha": "136fbcd46f728e09c627f690fa1fa6c1d71c3ad2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8571428571, "max_line_length": 84, "alphanum_fraction": 0.6796042618, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.71605864842525}} {"text": "#' ---\n#' title: \"Uvod u R\"\n#' author:\n#' - \"Milutin Pejovic, Petar Bursac\"\n#' date: \"`r format(Sys.time(), '%d %B %Y')`\"\n#' output:\n#' html_document:\n#' keep_md: true\n#' theme: \"simplex\"\n#' highlight: tango\n#' toc: true\n#' toc_depth: 5\n#' toc_float: true\n#' fig_caption: yes\n#' ---\n#'\n#' # Programsko okruzenje\n#+ echo = FALSE, warning = FALSE, message = FALSE, fig.width = 10, fig.height = 8, fig.align='center'\nknitr::include_graphics(\"Figures/01-RConsole.jpg\")\nknitr::include_graphics(\"Figures/02-RStudio.jpg\")\n#'\n#'\n#'\n#'\n#' # Osnovne matematicke operacije #\n#'\n#' R je moguce koristiti kao bilo koji kalculator koristeci osnovne komande:\n#' Sabiranje\n2+2 \n1+2+3+4+5 \n#'\n#' Oduzimanje\n10-1 \n5-6 \n#'\n#' Mnozenje\n2*2\n1*2*3\n#'\n#' Deljenje\n4/2\n10/2/4\n#'\n#' Koriscenje zagrada:\n10/2+2\n10/(2+2)\n(10/2)+2\n#'\n#'\n#' Stepenovanje i korenovanje\n2^2\n3^4\n1^0\nsqrt(4)\n#'\n#'\n#' >

Zadatak 1

\n#' > + Pronadji operator koji za rezultat operacije deljenja daje celobrojni deo rezultat (npr 111 `operator` 100 = 1).\n#' > + Pronadji operator koji za rezultat operacije deljenja daje decimalni deo (npr 111 `operator` 100 = 0.11).\n#'\n#'\n#'\n#'\n#' # Pozivanje funkcija u R-u\n#' \n#' Logaritmi:\nlog(0)\nlog(1)\n#'\n#' kao i logaritmi sa proizvoljnom osnovom (bazom):\nlog10(1)\nlog10(10)\nlog2(1)\nlog2(2)\nlogb(1,5) # Dva argumenta\nlogb(5,base=5) # Dva argumenta od kojih je jedan imenovan\n#'\n#' Prirodni eksponent:\nexp(0)\nexp(1)\n#'\n#' Kao i mnoge druge matematicke operacije:\n#' Apsolutna vrednost\nabs(-10)\n#'\n#' Faktorial:\nfactorial(10)\n#'\n#'\n#' # Dodavanje komentara\n#'\n#' Dodavanje komentara je veoma vazan deo dokumentovanja koda.\n#' \n#' \n#'\n#' Svaki deo teksta koji je pracen sa (`#`) postaje komentar i `ne` izvrsava se od strane R-a.\n2+2 # This is a comment. The code before the `#` is still evaluated by R.\n#'\n#' Neki programski jezici omogucavaju tzv. multi-line komentare. R ne podrzava tu opciju. U R-u svaki komentar je zaseban\n#' R-studio podrzava `proglasavanje` vise linija koda komentarom pozivom jedne komande `ctrl+shift+c`.\n#'\n#'\n#'\n#'\n#' # Promenljive ili objekti\n#' \n#' \n#' R omogucuje da se svakoj vrednosti doda ime, kako bi se ona pozivanjem tog imena kasnije mogla upotrebiti. Dodeljivanjem imena nekoj vrednosti (moguce je dodati ime i nekoj funkciji ili skupu nekih vrednosti) na taj nacin kreiramo `promenljive`. \n#' Na primer, umesto da odmah vidimo rezultat operacije `2+2`, mi mozemo sklaistiti taj rezultat pod nekim imenom i kasnije ga pogledati:\na <- 2+2\n#' Ukoliko hocemo da vidimo rezultat koji se `krije` iza tog imena, mi cemo samo ukucati to ime i pristisnuti `enter`:\na\n#' Kao sto ste mogli da vidite, operator za dodeljivanje imenta je `<-` i rezultatu operacije na desnoj strani dodeli ime koje je na levoj strani operatora.\n#' Isti rezultat se dobija i sa znakom `=` (ali se zbog litljivosti koda i sireg koriscenja znaka jednakost on izbegava):\na = 2+2\na\n#' Moguce je koristiti operator i u `suprotnom` smeru, ali to nije uobicajeno:\n2+2 -> a\na\n#' \n\n#' Iz svega navedenog proizilazi da tako rezultat operacije koji je sacuvan pod nekim imenom mozemo pozivati u okviru drugih operacija:\n#' Tako na primer, ako zelimo da rezultau prethodne operacije dodamo broj 4, pisacemo komandu:\n#' \na + 4\n\n#' Moguce je da isto ime iskoristimo i za skladistenje druge vrednosti. U tom slucaju gubimo prethodno sacuvan rezultat pod tim imenom.\na <- 2+2\na <- 3\na\n\n#' Mozemo napraviti `kopiju` promenljive ali pod drugim imenom:\nb <- a\nb\n\n#' Ako zelimo da uklonimo promeljivu `a`, pozvacemo komandu `rm` (skracemo od `remove`):\nrm(a)\n\n#' Ako zelimo da vidimo kakve smo sve promenljive napravili. Pozvacemo komandu `ls`.\nls()\n#' Ova funkcija ce vam izlistati sve promenljive koje ste kreirali tokom R sesije. Jedno pokretanje R-a je jedna sesija. Sto vise promenljvih to je teze da znate sa cim baratate u tokom sesije. Memorija racuara se takode opterecuje vise sa vecim brojem promenljivih.\n\n#' Ukoliko zeimo da uklonimo sve promenljive to mozemo uraditi pozivom komande `rm(list = ls())`\n\n\n#' Takode, mozemo pozvati komandu:\nb <- NULL\n#' Ova komanda `ne brise` probmenljivu `b`, vec je samo ostavlja `praznom`.\n#' Treba imati na umu da je `NULL` razlicito `NA`!\n#' You can see this in the difference between the following two vectors:\n#'\n#' Postoji i drugi nacin dodeljivanja imena, odnosno kreiranja promenljivih, a to je pozivom komande `assign`:\nassign(\"x\",3)\nx\n#' To nije uobicajeno u pocetku, ali kasnije moze biti korisno.\n#' ## Pravila nazivanja promenljivih ##\n#'\n#' U R-u postoje jednostavna pravila koja se moraju postovati prilikom nazivanja promenljivih:\n#' \n# +Imena promeljivih u R-u su `case sensitive`, sto znaci da `a` nije isto sto i `A`.\n# +Imena promeljivih u R-u moraju pocinjati sa slovima.\n# +Imena promeljivih u R-u mogu sadrzati slova, znake i brojeve, kao na primer (`.`) ili (`_`).\n# +Pozeljno je izbegavati dugacka imena.\n#' \n#' \n#'\n#' # Help\n#' \n#' R omogucava brz i jednostavan poziv `help`-a za svaku funkciju. Help je veoma jednostavan i pregledan. Help se moze pozvati na jedan od sledecih nacina:\n#+ eval = FALSE\nhelp(lm)\n#' ili\n#+ eval = FALSE\n?lm\n#' Za odredeni operator mora se moraju se koristiti navodnici:\n#+ eval = FALSE\n?`+`\n#'\n#' # Uvod u strukture podataka u R-u\n#' \n#' R vam omogucava da kreirate promenljve od komlikovanijih struktura podataka, ne samo od jedne vrednosti. Na primer, vi mozete kreirati promenljviu koja sadrzi vektor, niz (array), matricu ili listu. Od vrste strukture podataka zavisi kako ce ona biti prikazana i koje operacije su nad njom moguce. \n#' \n#' ### Vektori, nizovi i matrice\n#' Vektor i niz se skladiste na isti nacin, samo se uz niz vezuje i broj dimenzija, pa tako se on moze posmatrati kao visedimenzionalni vektor. Na primer, komandom `c` se kreira vektor, a komandom `array` se kreira niz.\n\nv <- c(1,2,3,4,5,6,7,8,9,10,11,12)\nv\na <- array(v, dim=c(3,4))\na\n#'\n#' >

Zadatak 2

\n#' > + Pronadjite funkciju koja kreira `2x6` matricu od vrednosti koje se nalaze u promenljvoj `v.\n#' > + Kreirati vektor koji ce sadrzati imena studenata u ucionici.\n#' \n#' **Za vektore nizove i matrice je zajednicko da oni mogu skladistiti samo jednu vrstu podataka (najcesce numericke).**\n#' \n#' \n#' ### Liste\n#' \n#' Lista je struktura podataka koja moze skladistiti razlicite vrste podataka\n#' \ne <- list(student=\"Milutin Pejovic\", `broj indeksa` = 1018, `godina upisa` = 2012)\n#'\n#' >

Zadatak 3

\n#' > + Kreirati listu u kojoj ce prvi element sadrzati sva imena studenata, drugi element sve brojeve indeksa i treci element sve godine upisa.\n#'\n#' ### Data-frames\n#'\n#' `Dataframe` je tabelarna struktura podataka u kojoj svaka kolona moze da sadrzi razliciti tip podataka. Ona u stvari predstavlja listu gde je svaki element liste u stvari vektor sa istom duzimom. `dataframe` je najslicniji `excel` tabeli. \n\nstudenti <- data.frame(ime = c(\"Milutin\", \"Petar\"), Prezime = c(\"Pejovic\", \"Bursac\"), `Broj indeksa` = c(1018, 1023), `Godina upisa` = c(2002, 2013))\nstudenti\n#'\n#' \n#' # R paketi\n#'\n#' ### R paketi prosiruju mogucnosti osnovne instalacije R-a.\n#' \n#' \n#' R paketi su softverske jedinice koje su kreirane za resavanje odredenih problema. Tako na primer imamo pakete koji su namenjeni ucitavanju razlicitih formata podataka ili paketi koji su namenjeni ispisivanju dobijenih rezultata u razlicite vrste fajlova.\n#' \n#' \n#' Instalacija paketa se vrsi pozivom komande:\n#' \n#+ echo = TRUE, eval = FALSE\ninstall.packages(\"ime paketa\")\n#' \n#'Ucitavanje paketa se vrsi komandom `\n#'\n#+ eval = FALSE\nlibrary()\n#' Opis paketa se moze pogledati pozivom funkcije\n#+ eval = FALSE\npackageDescription(\"name-of-package\")\n#'\n#'\n#' Postoji ogroman broj paketa koji se skladiste na centralnom repozorijumu R-a koji se zove [CRAN/packages](https://cran.r-project.org/web/packages/index.html).\n#' \n#' \n#' \n", "meta": {"hexsha": "38bac2a6fd2c2b953d3e1f7d4911c4b6fd05c34b", "size": 7823, "ext": "r", "lang": "R", "max_stars_repo_path": "R/01-Uvod u R.r", "max_stars_repo_name": "Nauka-o-podacima-u-R-u/Slides", "max_stars_repo_head_hexsha": "5280e5cfa68bd097038fe72ddba66e355fd7ba64", "max_stars_repo_licenses": ["AFL-1.1"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/01-Uvod u R.r", "max_issues_repo_name": "Nauka-o-podacima-u-R-u/Slides", "max_issues_repo_head_hexsha": "5280e5cfa68bd097038fe72ddba66e355fd7ba64", "max_issues_repo_licenses": ["AFL-1.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/01-Uvod u R.r", "max_forks_repo_name": "Nauka-o-podacima-u-R-u/Slides", "max_forks_repo_head_hexsha": "5280e5cfa68bd097038fe72ddba66e355fd7ba64", "max_forks_repo_licenses": ["AFL-1.1"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4605809129, "max_line_length": 301, "alphanum_fraction": 0.7104691295, "num_tokens": 2927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7156988035321858}} {"text": "\r\n\r\n# Goals: ARMA modeling - estimation, diagnostics, forecasting.\r\n\r\n\r\n# 0. SETUP DATA\r\nrawdata <- c(-0.21,-2.28,-2.71,2.26,-1.11,1.71,2.63,-0.45,-0.11,4.79,5.07,-2.24,6.46,3.82,4.29,-1.47,2.69,7.95,4.46,7.28,3.43,-3.19,-3.14,-1.25,-0.50,2.25,2.77,6.72,9.17,3.73,6.72,6.04,10.62,9.89,8.23,5.37,-0.10,1.40,1.60,3.40,3.80,3.60,4.90,9.60,18.20,20.60,15.20,27.00,15.42,13.31,11.22,12.77,12.43,15.83,11.44,12.32,12.10,12.02,14.41,13.54,11.36,12.97,10.00,7.20,8.74,3.92,8.73,2.19,3.85,1.48,2.28,2.98,4.21,3.85,6.52,8.16,5.36,8.58,7.00,10.57,7.12,7.95,7.05,3.84,4.93,4.30,5.44,3.77,4.71,3.18,0.00,5.25,4.27,5.14,3.53,4.54,4.70,7.40,4.80,6.20,7.29,7.30,8.38,3.83,8.07,4.88,8.17,8.25,6.46,5.96,5.88,5.03,4.99,5.87,6.78,7.43,3.61,4.29,2.97,2.35,2.49,1.56,2.65,2.49,2.85,1.89,3.05,2.27,2.91,3.94,2.34,3.14,4.11,4.12,4.53,7.11,6.17,6.25,7.03,4.13,6.15,6.73,6.99,5.86,4.19,6.38,6.68,6.58,5.75,7.51,6.22,8.22,7.45,8.00,8.29,8.05,8.91,6.83,7.33,8.52,8.62,9.80,10.63,7.70,8.91,7.50,5.88,9.82,8.44,10.92,11.67)\r\n\r\n# Make a R timeseries out of the rawdata: specify frequency & startdate\r\ngIIP <- ts(rawdata, frequency=12, start=c(1991,4))\r\nprint(gIIP)\r\nplot.ts(gIIP, type=\"l\", col=\"blue\", ylab=\"IIP Growth (%)\", lwd=2,\r\n main=\"Full data\")\r\ngrid()\r\n\r\n# Based on this, I decide that 4/1995 is the start of the sensible period.\r\ngIIP <- window(gIIP, start=c(1995,4))\r\nprint(gIIP)\r\nplot.ts(gIIP, type=\"l\", col=\"blue\", ylab=\"IIP Growth (%)\", lwd=2,\r\n main=\"Estimation subset\")\r\ngrid()\r\n\r\n# Descriptive statistics about gIIP\r\nmean(gIIP); sd(gIIP); summary(gIIP);\r\nplot(density(gIIP), col=\"blue\", main=\"(Unconditional) Density of IIP growth\")\r\nacf(gIIP)\r\n\r\n\r\n# 1. ARMA ESTIMATION\r\nm.ar2 <- arima(gIIP, order = c(2,0,0))\r\nprint(m.ar2) # Print it out\r\n\r\n\r\n# 2. ARMA DIAGNOSTICS\r\ntsdiag(m.ar2) # His pretty picture of diagnostics\r\n## Time series structure in errors\r\nprint(Box.test(m.ar2$residuals, lag=12, type=\"Ljung-Box\"));\r\n## Sniff for ARCH\r\nprint(Box.test(m.ar2$residuals^2, lag=12, type=\"Ljung-Box\"));\r\n## Eyeball distribution of residuals\r\nplot(density(m.ar2$residuals), col=\"blue\", xlim=c(-8,8),\r\n main=paste(\"Residuals of AR(2)\"))\r\n\r\n\r\n# 3. FORECASTING\r\n## Make a picture of the residuals\r\nplot.ts(m.ar2$residual, ylab=\"Innovations\", col=\"blue\", lwd=2)\r\ns <- sqrt(m.ar2$sigma2)\r\nabline(h=c(-s,s), lwd=2, col=\"lightGray\")\r\n\r\np <- predict(m.ar2, n.ahead = 12) # Make 12 predictions.\r\nprint(p)\r\n\r\n## Watch the forecastability decay away from fat values to 0.\r\n## sd(x) is the naive sigma. p$se is the prediction se.\r\ngain <- 100*(1-p$se/sd(gIIP))\r\nplot.ts(gain, main=\"Gain in forecast s.d.\", ylab=\"Per cent\",\r\n col=\"blue\", lwd=2)\r\n\r\n## Make a pretty picture that puts it all together\r\nts.plot(gIIP, p$pred, p$pred-1.96*p$se, p$pred+1.96*p$se,\r\n gpars=list(lty=c(1,1,2,2), lwd=c(2,2,1,1),\r\n ylab=\"IIP growth (%)\", col=c(\"blue\",\"red\", \"red\", \"red\")))\r\ngrid()\r\nabline(h=mean(gIIP), lty=2, lwd=2, col=\"lightGray\")\r\nlegend(x=\"bottomleft\", cex=0.8, bty=\"n\",\r\n lty=c(1,1,2,2), lwd=c(2,1,1,2),\r\n col=c(\"blue\", \"red\", \"red\", \"lightGray\"),\r\n legend=c(\"IIP\", \"AR(2) forecasts\", \"95% C.I.\", \"Mean IIP growth\"))\r\n\r\n", "meta": {"hexsha": "e690722e998befe9824cf508a1393fb4baa16be5", "size": 3192, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/t1.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/t1.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/t1.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9577464789, "max_line_length": 906, "alphanum_fraction": 0.6115288221, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7156497531893425}} {"text": "#\n# University: Universidad de Valladolid\n# Degree: Grado en Estadística\n# Subject: Análisis de Datos\n# Year: 2017/18\n# Teacher: Miguel Alejandro Fernández Temprano\n# Author: Sergio García Prado (garciparedes.me)\n# Name: Correspondence Analysis - Sport\n#\n#\n\nrm(list = ls())\n\nlibrary(ggplot2)\nsuppressMessages(library(gdata))\n\nDATA <- read.xls('./../../datasets/sport.xls')\n\nN <- as.matrix.data.frame(DATA[,2:6])\nrownames(N) <- DATA[,1]\nN <- t(N)\n\nF <- N / sum(N)\nF\n\nDc <- diag( colSums(N) / sum(N))\nDc\n\nDr <- diag( rowSums(N) / sum(N))\nDr\n\n\nPc <- solve(Dc) %*% t(F)\nPc\n\nPr <- solve(Dr) %*% F\nPr\n\nX <- t(F) %*% solve(Dr) %*% F %*% solve(Dc)\n\nX_eigen <- eigen(X)\nX_lambda <- X_eigen$values\nX_u_1 <- X_eigen$vectors\n\nX_u_norm <- diag(t(X_u_1) %*% solve(Dc) %*% X_u_1)\n\nX_u <- t(t(X_u_1) / sqrt(X_u_norm))\n\nfact <-solve(Dc) %*% X_u\n\nProyec_r <- Pr %*% fact\nProyec_c <- t(sqrt(X_lambda) * t(fact))\n\nProyec_r_df <- as.data.frame(Proyec_r)\nrownames(Proyec_r_df) <- rownames(N)\n\nProyec_c_df <- as.data.frame(Proyec_c)\nrownames(Proyec_c_df) <- colnames(N)\n\nProyec_df <- rbind(Proyec_r_df, Proyec_c_df)\n\nggplot(data=Proyec_df, aes(x=V2, y=V3)) +\n geom_point() +\n geom_text(label=rownames(Proyec_df))\n", "meta": {"hexsha": "5d5e7e422e9228cf4fb204b99180de14fca84371", "size": 1192, "ext": "r", "lang": "R", "max_stars_repo_path": "data-analysis/correspondence-analysis/sport-ca.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "data-analysis/correspondence-analysis/sport-ca.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "data-analysis/correspondence-analysis/sport-ca.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3384615385, "max_line_length": 50, "alphanum_fraction": 0.6577181208, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679977, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7154895624599333}} {"text": "\n\n########################################################################\n########################################################################\n# Logistic regression example\n########################################################################\n########################################################################\n\n\n\n# install.packages(\"aod\")\n# install.packages(\"ggplot2\")\n# install.packages(\"vctrs\")\n# install.packages(\"VGAM\")\n# install.packages(\"quantreg\")\n\nlibrary(knitr)\nlibrary(vctrs)\nlibrary(aod)\nlibrary(ggplot2)\n\n# Graduate school admissions data from UCLA\nmydata <- read.csv(\"https://stats.idre.ucla.edu/stat/data/binary.csv\")\n# Saved at: \\Consulting\\Public Code Samples\\DataScience\\Data\n# Alternate URL: https://1drv.ms/u/s!AgXALnk1NWLck4JA_01l6gpD6pZxpQ\n\n\n## view the first few rows of the data\nhead(mydata)\n# The admit variable is a binary response variable\n# We will use gre, gpa, and rank as predictor variables.\n# gre and gpa are continuous; while rank is a four-level factor\n\n# Here are some examinations of the data:\nsummary(mydata)\nsapply(mydata, sd)\nxtabs(~admit + rank, data = mydata)\n\n# Factor the rank variable and create a logistic regretion using glm() - Generalized Linear Model\nmydata$rank <- factor(mydata$rank)\nmylogit <- glm(admit ~ gre + gpa + rank, data = mydata, family = \"binomial\")\n\n# See regression results using summary\nsummary(mylogit)\n\n# We can create confidence levels by log likelihood\nconfint(mylogit)\n# or based on the standard errors:\nconfint.default(mylogit)\n\n# The wald test will give us the overall effect of the rank variable on admit:\nwald.test(b = coef(mylogit), Sigma = vcov(mylogit), Terms = 4:6)\n\n# The chi-squared test statistic of 20.9 indicates that rank *is* statistically significant in predicting admit\n\n# Let's focus on Rank by taking the mean of the other variables, breaking up by each factor level\nnewdata1 <- with(mydata, data.frame(gre = mean(gre), gpa = mean(gpa), rank = factor(1:4)))\n\n## view data frame\nnewdata1\n\n# Let's use predict() to see if we can model the rank variable\nnewdata1$rankP <- predict(mylogit, newdata = newdata1, type = \"response\")\nnewdata1\n\n# In the above output we see that the predicted probability of being accepted into a \n# graduate program is 0.52 for students from the highest prestige undergraduate \n# institutions (rank=1), and 0.18 for students from the lowest ranked institutions \n# (rank=4), holding gre and gpa at their means. We can do something very similar to \n# create a table of predicted probabilities varying the value of gre and rank. \n\n# This is a technique for isolating the predictive effect of a single explanatory variable on the response\n\n# We are going to plot these, so we will create 100 values of gre between 200 and 800,\n# at each value of rank (i.e., 1, 2, 3, and 4).\n\nnewdata2 <- with(mydata, data.frame(gre = rep(seq(from = 200, to = 800, length.out = 100),\n 4), gpa = mean(gpa), rank = factor(rep(1:4, each = 100))))\n\n\n\n# The code to generate the predicted probabilities (the first line below) is \n# the same as before, except we are also going to ask for standard errors so we \n# can plot a confidence interval. \n\n\n# We get the estimates on the link scale and back transform both the predicted values\n# and confidence limits into probabilities.\n\nnewdata3 <- cbind(newdata2, predict(mylogit, newdata = newdata2, type = \"link\",\n se = TRUE))\nnewdata3 <- within(newdata3, {\n PredictedProb <- plogis(fit)\n LL <- plogis(fit - (1.96 * se.fit))\n UL <- plogis(fit + (1.96 * se.fit))\n})\n\n## view first few rows of final dataset\nhead(newdata3)\n\n# Below we make a plot with the predicted probabilities, and 95% confidence intervals.\nggplot(newdata3, aes(x = gre, y = PredictedProb)) + \n geom_ribbon(aes(ymin = LL, ymax = UL, fill = rank), alpha = 0.2) + \n geom_line(aes(colour = rank),size = 1)\n\n\n\n\n# Some methods to test fit below\nwith(mylogit, null.deviance - deviance)\nwith(mylogit, df.null - df.residual)\nwith(mylogit, pchisq(null.deviance - deviance, df.null - df.residual, lower.tail = FALSE))\n\n# The chi-square of 41.46 with 5 degrees of freedom and an associated p-value of \n# less than 0.001 tells us that our model as a whole fits significantly better \n# than an empty model. \n\n#To see the model's log likelihood\nlogLik(mylogit)\n\n\n########################################################################\n########################################################################\n# Multinomial regression example\n########################################################################\n########################################################################\n\nrequire(foreign)\nrequire(nnet)\nrequire(ggplot2)\nrequire(reshape2)\n\n# A data set showing occupational outcomes for vocational or academic educational paths\nml <- read.dta(\"https://stats.idre.ucla.edu/stat/data/hsbdemo.dta\")\n# Saved at: \\Consulting\\Public Code Samples\\DataScience\\Data\\UCLAHighSchoolVocationalSurvey.dta\n# Alternate URL: https://1drv.ms/u/s!AgXALnk1NWLck4JDxYy1aZKct65nOw?e=7JBQzi\n\n# Have a look at the data:\nwith(ml, table(ses, prog))\nwith(ml, do.call(rbind, tapply(write, prog, function(x) c(M = mean(x), SD = sd(x)))))\n\n# Let's use relevel to create a new variable weighing the \"academic\" prog variable response\nml$prog2 <- relevel(ml$prog, ref = \"academic\")\ntest <- multinom(prog2 ~ ses + write, data = ml) # multinom() does not require reshaping like mlogit() does\nsummary(test)\n# Test is a multinom() output of our model using the releveled program\n\n# We run a couple of tests on the model:\nz <- summary(test)$coefficients/summary(test)$standard.errors\nz\n# 2-tailed z test\np <- (1 - pnorm(abs(z), 0, 1)) * 2\np\n\n## extract the coefficients from the model and exponentiate\nexp(coef(test))\n\n# Use predicted probabilities to help understand the model. Calculate predicted probabilities for each of \n# the outcome levels using the fitted() function. \n# \n# We can start by generating the predicted probabilities for the observations in our dataset and viewing \n# the first few rows:\n \n head(pp <- fitted(test))\n\n# To examine the changes in predicted probability associated with one of our two \n# variables, we can create small datasets varying one variable while holding the \n# other constant. We will first do this holding write at its mean and examining \n# the predicted probabilities for each level of ses.\n\ndses <- data.frame(ses = c(\"low\", \"middle\", \"high\"), write = mean(ml$write))\npredict(test, newdata = dses, \"probs\")\n\ndwrite <- data.frame(ses = rep(c(\"low\", \"middle\", \"high\"), each = 41), write = rep(c(30:70), 3))\n\n## store the predicted probabilities for each value of ses and write\npp.write <- cbind(dwrite, predict(test, newdata = dwrite, type = \"probs\", se = TRUE))\n\n## calculate the mean probabilities within each level of ses\nby(pp.write[, 3:5], pp.write$ses, colMeans)\n\n## melt data set to long for ggplot2\nlpp <- melt(pp.write, id.vars = c(\"ses\", \"write\"), value.name = \"probability\")\nhead(lpp) # view first few rows\n\n# Plot the predicted probabilities against the writing score using the predictions generated\n# for the pp.write object above by the level of ses for different levels of the outcome variable.\n\nggplot(lpp, aes(x = write, y = probability, colour = ses)) + geom_line() + facet_grid(variable ~ ., scales = \"free\")\n\n########################################################################\n########################################################################\n# Poisson regression example (Zero Truncated)\n########################################################################\n########################################################################\ninstall.packages(\"rlang\")\ninstall.packages(\"knitr\")\ninstall.packages(\"vctrs\")\ninstall.packages(\"ggplot2\")\ninstall.packages(\"VGAM\")\nrequire(foreign)\nrequire(ggplot2)\nrequire(VGAM)\nrequire(boot)\n\n\n# Import data from hospital tracking patients who have died\ndat <- read.dta(\"https://stats.idre.ucla.edu/stat/data/ztp.dta\")\n# Saved at: \\Consulting\\Public Code Samples\\DataScience\\Data\\HospitalDeathTracking.dta\n# Alternate URL: https://1drv.ms/u/s!AgXALnk1NWLck4JBKcMG9lGWFR8TEA?e=jZf1H7\n\n# Convert a couple of the variables we'll be working with to factors\ndat <- within(dat, {\n hmo <- factor(hmo)\n died <- factor(died)\n})\n\nsummary(dat)\n\n# To really get a sense for the data, let's plot some graphs:\n# Length of stay with died in facets\nggplot(dat, aes(stay)) +\n geom_histogram() +\n scale_x_log10() +\n facet_grid(hmo ~ died, margins=TRUE, scales=\"free_y\")\n\n# Examine how stay looks across age groups:\nggplot(dat, aes(factor(age), stay)) +\n geom_violin() + # Violin plot is a great choice for this data spread\n geom_jitter(size=1.5) +\n scale_y_log10() +\n stat_smooth(aes(x = age, y = stay, group=1), method=\"loess\")\n\n# Look at live/die *by hmo*\nggplot(dat, aes(age, fill=died)) +\n geom_histogram(binwidth=.5, position=\"fill\") +\n facet_grid(hmo ~ ., margins=TRUE)\n\n# Now let's create a model predicting stay (a count variable) by the other variables in our set\nm1 <- vglm(stay ~ age + hmo + died, family = pospoisson(), data = dat)\nsummary(m1)\n\n# plot of residuals versus fitted values\noutput <- data.frame(resid = resid(m1), fitted = fitted(m1))\nggplot(output, aes(fitted, resid)) +\n geom_jitter(position=position_jitter(width=.25), alpha=.5) +\n stat_smooth(method=\"loess\")\n\n# Fit lines using quantile regression:\nggplot(output, aes(fitted, resid)) +\n geom_jitter(position=position_jitter(width=.25), alpha=.5) +\n stat_quantile(method=\"rq\")\n\n# Here we see the spread narrowing at higher levels. Let's cut the data into \n# intervals and check box plots for each. We will get the breaks from the algorithm \n# for a histogram.\n\noutput <- within(output, {\n broken <- cut(fitted, hist(fitted, plot=FALSE)$breaks)\n})\n\nggplot(output, aes(broken, resid)) +\n geom_boxplot() +\n geom_jitter(alpha=.25)\n\n\n# 1) Get the coefficients from our original model to use as start values for \n# the model to speed up the time it takes to estimate. \n# 2) Write a short function that takes data and indices as input and returns the parameters \n# we are interested in. \n# 3) Pass that to the boot function and do 1200 replicates, \n# using snow to distribute across four cores. \n\n\ndput(round(coef(m1),3)) # Coefficients\nf <- function(data, i) {\n require(VGAM)\n m <- vglm(formula = stay ~ age + hmo + died, family = pospoisson(),\n data = data[i, ], coefstart = c(2.436, -0.014, -0.136, -0.204))\n as.vector(t(coef(summary(m))[, 1:2])) #Original model coeffs as starting point\n}\n\nset.seed(10)\nres <- boot(dat, f, R = 1200, parallel = \"snow\", ncpus = 4) # 1200 repeats, \"snow\" parallel option, and 4 cores\n\n## print results\nres\n\n## basic parameter estimates with percentile and bias adjusted CIs\nparms <- t(sapply(c(1, 3, 5, 7), function(i) {\n out <- boot.ci(res, index = c(i, i + 1), type = c(\"perc\", \"basic\"))\n with(out, c(Est = t0, pLL = percent[4], pUL = percent[5],\n basicLL = basic[4], basicLL = basic[5]))\n}))\n\n## add row names\nrow.names(parms) <- names(coef(m1))\n## print results\nparms\n\n## exponentiated parameter estimates with percentile and bias adjusted CIs\nexpparms <- t(sapply(c(1, 3, 5, 7), function(i) {\n out <- boot.ci(res, index = c(i, i + 1), type = c(\"perc\", \"basic\"), h = exp)\n with(out, c(Est = t0, pLL = percent[4], pUL = percent[5],\n basicLL = basic[4], basicLL = basic[5]))\n}))\n\n## add row names\nrow.names(expparms) <- names(coef(m1))\n## print results\nexpparms\n\n# In order to better understand our results and model, let's plot some predicted values. \n# Because all of our predictors were categorical (hmo and died) or had a small \n# number of unique values (age) we will get predicted values for all possible \n# combinations. \n\n# First we create a new data set using the expand.grid function, \n# then estimate the predicted values using the predict function, and finally plot them.\n\nnewdata <- expand.grid(age = 1:9, hmo = factor(0:1), died = factor(0:1)) # New Data\nnewdata$yhat <- predict(m1, newdata, type = \"response\") # Predict values with our m1 model\n\nggplot(newdata, aes(x = age, y = yhat, colour = hmo)) + # Plot the results\n geom_point() +\n geom_line() +\n facet_wrap(~ died)\n\n\n## function to return predicted values\nfpred <- function(data, i, newdata) {\n require(VGAM)\n m <- vglm(formula = stay ~ age + hmo + died, family = pospoisson(),\n data = data[i, ], coefstart = c(2.436, -0.014, -0.136, -0.204))\n predict(m, newdata, type = \"response\")\n}\n\n## set seed and run bootstrap with 1,200 draws\nset.seed(10)\nrespred <- boot(dat, fpred, R = 1200, newdata = newdata,\n parallel = \"snow\", ncpus = 4)\n\n## get the bootstrapped percentile CIs\nyhat <- t(sapply(1:nrow(newdata), function(i) {\n out <- boot.ci(respred, index = i, type = c(\"perc\"))\n with(out, c(Est = t0, pLL = percent[4], pUL = percent[5]))\n}))\n\n## merge CIs with predicted values\nnewdata <- cbind(newdata, yhat)\n## graph with CIs\nggplot(newdata, aes(x = age, y = yhat, colour = hmo, fill = hmo)) +\n geom_ribbon(aes(ymin = pLL, ymax = pUL), alpha = .25) +\n geom_point() +\n geom_line() +\n facet_wrap(~ died)\n\n# And voila! A Poisson prediction model predicts how many deaths (count) to expect by age for HMO and non-HMO patients.\n\n\n\n", "meta": {"hexsha": "9e95034e67e6c35933e1093f7b2bb5d41005793d", "size": 13305, "ext": "r", "lang": "R", "max_stars_repo_path": "Regression Examples/SimpleRegressionExamples.r", "max_stars_repo_name": "perezrd5/Data-Science", "max_stars_repo_head_hexsha": "749a81349348b4b5434bf1c1491d43423790f8e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-10T18:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-10T18:38:59.000Z", "max_issues_repo_path": "Regression Examples/SimpleRegressionExamples.r", "max_issues_repo_name": "perezrd5/Data-Science", "max_issues_repo_head_hexsha": "749a81349348b4b5434bf1c1491d43423790f8e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Regression Examples/SimpleRegressionExamples.r", "max_forks_repo_name": "perezrd5/Data-Science", "max_forks_repo_head_hexsha": "749a81349348b4b5434bf1c1491d43423790f8e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7541436464, "max_line_length": 120, "alphanum_fraction": 0.6575723412, "num_tokens": 3512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7153759978993246}} {"text": "---\ntitle: \"matrix\"\nauthor: \"lois\"\ndate: \"11/25/2021\"\noutput: pdf_document\n---\n\n```{r}\nx <- (1:4)\ny <- (5:8)\nq = rbind(x, y)\nrownames <- x(\"a\", \"b\", \"c\", \"d\") \ncolnames <- x(\"e\", \"f\", \"g\", \"h\")\n```\n```{r}\nx <- 1:20\n\nlength(x)\n\nx<-seq(1,9, by = 2)\n\nx <- 0:6\nclass(x)\n\nas.numeric(x)\nas.logical(x)\nas.character(x)\n```\n```{r}\nx <- matrix(nrow = 2, ncol = 3)\nx\ndim(x)\nattributes(x)\n\nm <- matrix(1:6,nrow=2, ncol=3)\nm\nm <- matrix(1:6,nrow=2, ncol=3, byrow = TRUE)\nm\n\nx <- c(1,2,3,4,5,6,7,8,9,10)\nx\n\ndim(x) <- c(2,5)\nx\n```\n\n```{r}\nx<-4:6\ny<-1:3\ncbind(x,y)\n\nrbind(x,y)\n\nm<-matrix(1:4, nrow=2, ncol=2)\ncolnames(m)<-c(\"a\",\"b\")\nrownames(m)<-c(\"c\",\"d\")\nm\n\n```\n```{r}\n#Task 1\nx<-(1:4)\ny<-(5:8)\n\nM<- cbind(x,y)\nM\nQ <-rbind(x,y)\nQ\n\ncolnames(M)<-c(\"a\",\"b\")\nrownames(M)<-c(\"c\",\"d\",\"e\",\"f\")\nM\n\ncolnames(Q)<-c(\"a\",\"b\",\"c\",\"d\")\nrownames(Q)<-c(\"e\",\"f\")\nQ\n```\n```{r}\n#List\nm <- list(50, \"b\", TRUE, 1 + 4i)\nm\n\nx <- list(a = 1, b = \"c\", c = 3)\nx\n```\n```{r}\n#Factor\ngender <- c(\"male\",\"male\",\"female\",\"female\",\"male\",\"female\",\"male\")\ngender\n\nas.factor(gender)\nclass(gender)\nis.na(gender)\nis.nan(gender)\n```\n```{r}\n#Data Frame\nemp.data <- data.frame( emp_id = c (1:5),\nemp_name = c(\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\"),\nemp_gender = c(\"Male\", \"Male\", \"Female\", \"Male\", \"Male\"),\nemp_age = c(50, 40, 26, 38, 30),\nsalary = c(623.3,515.2,611.0,729.0,843.25))\nsubset(emp.data, emp_id==1)\nemp.data[3,]\nemp.data[which(emp.data$gender==\"Female\" & emp.data$age==26),]\nsubset(emp.data, emp_age>=40, select = c(emp_id, emp_gender, salary, emp_name))\n```\n\n```{r}\n#Data Frame Two\nnatives <- data.frame(cohort = c(1:9),\ncohort_name = c(\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"),\ncohort_num_of_natives = c(30, 20, 40, 53, 27, 20, 22, 29, 39))\nnatives$cohort_name\n```\n```{r}\nx<-5:7\nnames(x)\nnames(x)<-c(\"five\",\"six\",\"seven\")\nx\nnames(x)\n```\n```{r}\nx<-c(\"a\",\"b\",\"c\",\"d\")\nx[3]\nx[x>\"b\"]\n\nx<-matrix(1:6,2,3)\nx[1,2]\nx[1,]\nx[,3]\n```\n```{r}\n#Subsetting matrix\nx<-matrix(1:12,3,4)\nx\nx[2:3,2:4]\n```\n```{r}\n#subsetting drop\nx <- matrix(1:6, 2, 3)\nx[1, 2]\nx\nx[1, 2, drop = FALSE]\n```\n```{r}\ny <-matrix(1:12,4,4)\ncolnames(y)<- c(\"col_one\", \"col_two\", \"col_three\", \"col_four\")\ny\ny[1,2]\ny[3:4,1:3]\n\n\n```", "meta": {"hexsha": "9f60f9b37de4782e0292f189c8bbd51b7cb0541b", "size": 2179, "ext": "r", "lang": "R", "max_stars_repo_path": "R Data Science Project/Intoduction to data science.r", "max_stars_repo_name": "kindyluv/R_Data_Analysis", "max_stars_repo_head_hexsha": "f26f855d4ecdbec241074ead475b107841d231f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R Data Science Project/Intoduction to data science.r", "max_issues_repo_name": "kindyluv/R_Data_Analysis", "max_issues_repo_head_hexsha": "f26f855d4ecdbec241074ead475b107841d231f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R Data Science Project/Intoduction to data science.r", "max_forks_repo_name": "kindyluv/R_Data_Analysis", "max_forks_repo_head_hexsha": "f26f855d4ecdbec241074ead475b107841d231f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.1493506494, "max_line_length": 88, "alphanum_fraction": 0.5355667737, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7153475877769481}} {"text": "# KOLEKTIVNI MODEL TVEGANJA IN PANJERJEV ALGORITEM\n# Finančni praktikum 2020/21\n# Mitja Mandić\n\n\nlibrary(actuar)\nvzorec <- scan(\"vzorec4.txt\")\nhist(vzorec)\nhist <- recordPlot()\n\nparameter <- mde(vzorec, pweibull, measure = \"CvM\", start = list(shape = 10, scale = 10))\nshape_ocena <- parameter$estimate[1]\nscale_ocena <-parameter$estimate[2]\n\nhist(vzorec, breaks = 20,probability = TRUE, ylab = \"Gostota\")\ncurve(dweibull(x,shape_ocena,scale_ocena), from=2,to=7, add=TRUE, col = \"red\")\ngraf_prva <- recordPlot()\n\n\n#vzorčna in izračunana porazdelitvena funkcija\n\nplot(ecdf(vzorec), col = \"blue\", main = \"\", ylab = \" \")\ncurve(pweibull(x,shape_ocena,scale_ocena), add = TRUE)\ntitle(\"Vzorčna in porazdelitvena funkcija\")\nvzorcna_in_porazdelitvena <- recordPlot()\n\n#PORAZDELITEV VSOTE\n\npv.n <- 25 * 0.5\nv.n <- 25 * 0.5 * 0.5\n\n#paramteri weibullove\n\npv.w <- scale * gamma(1+1/shape) \nv.w <- scale^2 * (gamma(1+2/shape)-(gamma(1+1/shape))^2)\n\ne.s <- pv.n * pv.w\nv.s <- v.w * pv.n + pv.w^2 * v.n\n\n#DRUGA NALOGA\n\n#druga a\n\ndolzina <- 5\nkorak <- 1/10\ndiskretna <- discretize(pweibull(x, shape = shape_ocena , scale=scale_ocena), from = 0, to = 5,\n step = korak)\n\n#diskretna\n\n#druga b\n\ncurve(pweibull(x, shape = shape, scale = scale), from = 0, to = dolzina, xname = \"x\",ylab = \" \")\nplot(stepfun(x = seq(0, dolzina - korak, korak), y = diffinv(diskretna)),add = TRUE)\ntitle(\"Diskretizacija Weibullove porazdelitve in CDF\")\n\n#druga c\n\npanjer <- aggregateDist(method = \"recursive\", model.freq = \"binomial\",model.sev = diskretna, size = 25, prob = 0.5, \n x.scale = korak, tol = 0.001, maxit = 100000)\n\n#druga d\n#disperzija in upanje kumulativne škode\nskoki <- knots(panjer)\n\npricakovana_vrednost.panjer <- sum(knots(panjer) * diff(panjer))\n\npricakovana_vrednost_kvadrat.panjer <- sum(skoki ^ 2 * diff(panjer)) \n\nvarianca.panjer <- pricakovana_vrednost_kvadrat.panjer - pricakovana_vrednost.panjer^2\n\n#TRETJA NALOGA\n\n#tretja a\n\n#simulacija vsot\nvzorec_bin <- rbinom(10000,25,0.5)\nsimulacije <- as.data.frame(vzorec_bin)\ncolnames(simulacije) <- \"binomska\"\nsimulacije['vsota'] <- 0\n\ni = 1\nfor (i in 1:10000){\n simulacije[i,\"vsota\"] <- sum(rweibull(simulacije[i,1],shape_ocena,scale_ocena))\n #i = i + 1\n}\n\n#tretja b\n\nsimulirana_pv <- mean(simulacije[,\"vsota\"]) #simulirana vrednost: 29.651; waldov obrazec: 29.7\nsimulirana_var <- var(simulacije[,\"vsota\"]) #simulirana vrednost: 37.257; waldov obrazec: 37.3\n\n#tretja c\n\n\"Simulirana porazdelitev in porazdelitev kumulativne škode\"\nplot(ecdf(simulacije[,'vsota']), main = \"\")\nplot(panjer, sub = \"\", add = TRUE, col = \"Blue\")\ntitle(\"Simulirana porazdelitev in porazdelitev kumulativne škode\")\n", "meta": {"hexsha": "f7dc6b95a44ba96197d401dd2d2167fbbcd2fc8c", "size": 2666, "ext": "r", "lang": "R", "max_stars_repo_path": "druga_naloga/Mandic2.r", "max_stars_repo_name": "mitja-mandic/financni-praktikum", "max_stars_repo_head_hexsha": "fe7ececd401b7a002b9e11bd69938ba98a96a081", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "druga_naloga/Mandic2.r", "max_issues_repo_name": "mitja-mandic/financni-praktikum", "max_issues_repo_head_hexsha": "fe7ececd401b7a002b9e11bd69938ba98a96a081", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "druga_naloga/Mandic2.r", "max_forks_repo_name": "mitja-mandic/financni-praktikum", "max_forks_repo_head_hexsha": "fe7ececd401b7a002b9e11bd69938ba98a96a081", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9292929293, "max_line_length": 116, "alphanum_fraction": 0.6912978245, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.715282090351482}} {"text": "# Assignment 3\n\nlibrary(neuralnet)\nlibrary(gtools)\nlibrary(glue)\nprintf <- defmacro(str, expr = {print(glue(str))})\n\n# Creating output variable\noutput = list()\n\n# Part 1\nset.seed(1234567890)\nVar <- runif(500, 0, 10) \nmydata <- data.frame(Var, Sin=sin(Var)) \ntr <- mydata[1:25,] # Training \nte <- mydata[26:500,] # Test\n\n# Random initialization of the weights in the interval [-1, 1] \nwinit <- runif(n = 10, min = -1, max = 1)\nnn <- neuralnet(Sin ~ Var, data=tr, hidden = c(10), startweights=winit)\noutput$o3.1 = printf(\"start weights: {nn$startweights}\")\n\nplot(tr, cex=2) \npoints(te, col = \"blue\", cex=1)\npoints(te[,1],predict(nn,te), col=\"red\", cex=1)\ntitle(\"Prediction neural network 0 to 10\")\nlegend(\"bottomleft\", \n inset=.02, \n title=\"Datapoints\",\n c(\"Training\",\"Testing\",\"Predicted\"),\n col=c(\"black\",\"blue\",\"red\"), \n lwd=1, \n lty=c(0,0), \n pch=c(1,1,1))\n\n#part 2 \n\nh1 <- function(x) x\nh2 <- function(x) ifelse(x > 0, x, 0)\nh3 <- function(x) log(1 + exp(x))\n\nnn.h1 = neuralnet(Sin ~ Var, data=tr, hidden = c(10), startweights = winit, act.fct = h1)\nnn.h2 = neuralnet(Sin ~ Var, data=tr, hidden = c(10), startweights = winit, act.fct = h2)\nnn.h3 = neuralnet(Sin ~ Var, data=tr, hidden = c(10), startweights = winit, act.fct = h3)\n\n\npar(mfrow=c(2,2))\nplot(te, col = \"blue\", cex=1)\npoints(te[,1],predict(nn.h1,te), col=\"red\", cex=1)\ntitle(\"Linear\")\nplot(te, col = \"blue\", cex=1)\npoints(te[,1],predict(nn.h2,te), col=\"red\", cex=1)\ntitle(\"ReLU\")\nplot(te, col = \"blue\", cex=1)\npoints(te[,1],predict(nn.h3,te), col=\"red\", cex=1)\ntitle(\"Softplus\")\nplot(NULL,xaxt='n',yaxt='n',bty='n',ylab='',xlab='', xlim=0:1, ylim=0:1)\nlegend(\"topleft\", \n legend =c(\"Sample\", \"Predicted\"),\n title=\"Datapoints\",\n pch=1, pt.cex=2, cex=1, \n col = c(\"blue\", \"red\"))\npar(mfrow=c(1,1))\n\n\n# part 3\n\nVar2 <- runif(500, 0, 50) \nmydata2 <- data.frame(Var=Var2, Sin=sin(Var2))\n\nplot(mydata2[,1],predict(nn,mydata2), \n col=\"red\", cex=1,\n xlab=\"Var\", ylab=\"Sin\")\npoints(mydata2, col = \"blue\", cex=1)\nlegend(\"bottomleft\",\n y=-6,\n legend =c(\"Sample\", \"Predicted\"),\n title=\"Datapoints\",\n pch=1, pt.cex=2, cex=1, \n col = c(\"blue\", \"red\"))\n\n\n# part 4\npredict(nn,mydata2)\nplot(nn)\n\nconv.prediction = predict(nn,data.frame(Var=1000))\n\nconv.w.L1 = nn$weights[[1]][[1]][2,]\nconv.mask <- 0 < c(1, conv.w.L1)\nconv.w.L2 = nn$weights[[1]][[2]]\n\nconv.calculation = sum(conv.mask * conv.w.L2)\noutput$o3.4 = printf(\"Convergence of nn\n Calculation : {conv.calculation}\n Prediction : {conv.prediction}\n \")\n\n\n# part 5\n\nset.seed(1234567890)\nVar3 <- runif(500, 0, 10) \nmydata3 <- data.frame(Var=Var3, Sin=sin(Var3))\n\nnn.SinPredictVar <- neuralnet(Var ~ Sin, \n data=mydata3, \n hidden = c(10), \n startweights = winit, \n threshold = 0.1)\n\nplot(predict(nn.SinPredictVar,mydata3), mydata3[,2],\n col=\"red\", cex=1,\n xlab = \"Var\", ylab = \"Sin\")\npoints(mydata3, col = \"blue\", cex=1)\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "7f5ff681b19b7d79af891649306eaabe33a6f2b3", "size": 3083, "ext": "r", "lang": "R", "max_stars_repo_path": "tdde01-machine-learning/lab3/nn.r", "max_stars_repo_name": "AxelGard/university-projects", "max_stars_repo_head_hexsha": "0c9a6e785f1918c6ed0fd365b2d419c9f52edb50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tdde01-machine-learning/lab3/nn.r", "max_issues_repo_name": "AxelGard/university-projects", "max_issues_repo_head_hexsha": "0c9a6e785f1918c6ed0fd365b2d419c9f52edb50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tdde01-machine-learning/lab3/nn.r", "max_forks_repo_name": "AxelGard/university-projects", "max_forks_repo_head_hexsha": "0c9a6e785f1918c6ed0fd365b2d419c9f52edb50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0859375, "max_line_length": 89, "alphanum_fraction": 0.581900746, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7152657078962043}} {"text": "# Program to check if the input number is prime or not\n# take input from the user\nnum = as.integer(readline(prompt=\"Enter a number: \"))\nflag = 0\n# prime numbers are greater than 1\nif(num > 1) {\n# check for factors\nflag = 1\nfor(i in 2:(num-1)) {\nif ((num %% i) == 0) {\nflag = 0\nbreak\n}\n}\n} \nif(num == 2) flag = 1\nif(flag == 1) {\nprint(paste(num,\"is a prime number\"))\n} else {\nprint(paste(num,\"is not a prime number\"))\n}", "meta": {"hexsha": "06ab4d524634c383610c7d342fc95803d1f23b67", "size": 421, "ext": "r", "lang": "R", "max_stars_repo_path": "check_prime_number.r", "max_stars_repo_name": "MarcosFloresta/R_Examples", "max_stars_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "check_prime_number.r", "max_issues_repo_name": "MarcosFloresta/R_Examples", "max_issues_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "check_prime_number.r", "max_forks_repo_name": "MarcosFloresta/R_Examples", "max_forks_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0476190476, "max_line_length": 54, "alphanum_fraction": 0.6294536817, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7150609939503642}} {"text": "\r\n\r\n# Goal: To do `moving window volatility' of returns.\r\n\r\nlibrary(zoo)\r\n\r\n# Some data to play with (Nifty on all fridays for calendar 2004) --\r\np <- structure(c(1946.05, 1971.9, 1900.65, 1847.55, 1809.75, 1833.65, 1913.6, 1852.65, 1800.3, 1867.7, 1812.2, 1725.1, 1747.5, 1841.1, 1853.55, 1868.95, 1892.45, 1796.1, 1804.45, 1582.4, 1560.2, 1508.75, 1521.1, 1508.45, 1491.2, 1488.5, 1537.5, 1553.2, 1558.8, 1601.6, 1632.3, 1633.4, 1607.2, 1590.35, 1609, 1634.1, 1668.75, 1733.65, 1722.5, 1775.15, 1820.2, 1795, 1779.75, 1786.9, 1852.3, 1872.95, 1872.35, 1901.05, 1996.2, 1969, 2012.1, 2062.7, 2080.5), index = structure(c(12419, 12426, 12433, 12440, 12447, 12454, 12461, 12468, 12475, 12482, 12489, 12496, 12503, 12510, 12517, 12524, 12531, 12538, 12545, 12552, 12559, 12566, 12573, 12580, 12587, 12594, 12601, 12608, 12615, 12622, 12629, 12636, 12643, 12650, 12657, 12664, 12671, 12678, 12685, 12692, 12699, 12706, 12713, 12720, 12727, 12734, 12741, 12748, 12755, 12762, 12769, 12776, 12783), class = \"Date\"), frequency = 0.142857142857143, class = c(\"zooreg\", \"zoo\"))\r\n\r\n# Shift to returns --\r\nr <- 100*diff(log(p))\r\nhead(r)\r\nsummary(r)\r\nsd(r)\r\n\r\n# Compute the moving window vol --\r\nvol <- sqrt(250) * rollapply(r, 20, sd, align = \"right\")\r\n\r\n# A pretty plot --\r\nplot(vol, type=\"l\", ylim=c(0,max(vol,na.rm=TRUE)),\r\n lwd=2, col=\"purple\", xlab=\"2004\",\r\n ylab=paste(\"Annualised sigma, 20-week window\"))\r\ngrid()\r\nlegend(x=\"bottomleft\", col=c(\"purple\", \"darkgreen\"),\r\n lwd=c(2,2), bty=\"n\", cex=0.8,\r\n legend=c(\"Annualised 20-week vol (left scale)\", \"Nifty (right scale)\"))\r\npar(new=TRUE)\r\nplot(p, type=\"l\", lwd=2, col=\"darkgreen\",\r\n xaxt=\"n\", yaxt=\"n\", xlab=\"\", ylab=\"\")\r\naxis(4)\r\n\r\n", "meta": {"hexsha": "af10f143f4d48656914fb7c3d8f8e7a52786d510", "size": 1704, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p4.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p4.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p4.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.25, "max_line_length": 924, "alphanum_fraction": 0.6373239437, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7149707915204739}} {"text": "llr = function(k) {2 * sum(k) * (H(k) - H(rowSums(k)) - H(colSums(k)))}\nH = function(k) {N = sum(k) ; return (sum(k/N * log(k/N + (k==0))))}\n\nrootLLR = function(k) {sqrt(llr(k)) * ifelse(k[1,1] > (k[1,1] + k[1,2])/sum(k) * (k[1,1]+k[2,1]), 1, -1)}\n\n", "meta": {"hexsha": "6eaa1b903541544e03652da09016274ff78eab1f", "size": 249, "ext": "r", "lang": "R", "max_stars_repo_path": "llr.r", "max_stars_repo_name": "tdunning/surprise-figures", "max_stars_repo_head_hexsha": "63fd2606dc1f948f6eaecf7ee50541c4d424eb50", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "llr.r", "max_issues_repo_name": "tdunning/surprise-figures", "max_issues_repo_head_hexsha": "63fd2606dc1f948f6eaecf7ee50541c4d424eb50", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "llr.r", "max_forks_repo_name": "tdunning/surprise-figures", "max_forks_repo_head_hexsha": "63fd2606dc1f948f6eaecf7ee50541c4d424eb50", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5, "max_line_length": 105, "alphanum_fraction": 0.4859437751, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.7148634910381634}} {"text": "model = \"model\n{\n # Prior for all the parameters\n beta0 ~ dnorm(0, pow(1E3, -2))\n beta1 ~ dnorm(0, pow(1E3, -2))\n log_sigma ~ dunif(-10, 10)\n sigma <- exp(log_sigma)\n\n # Likelihood\n for(i in 1:N)\n {\n y[i] ~ dnorm(beta0 + beta1*x[i], pow(sigma, -2))\n }\n\n\ty_new ~ dnorm(beta0 + beta1*90, pow(sigma, -2))\n}\n\"\n\n# Load data from file\ndata = source('data.txt')$value\n\n# Variables to monitor\nvariable_names = c('beta0', 'beta1', 'sigma', 'y_new')\n\n# How many burn-in steps?\nburn_in = 10000\n\n# How many proper steps?\nsteps = 5000\n\n# Thinning?\nthin = 10\n\n\n\n\n# NO NEED TO EDIT PAST HERE!!!\n# Just run it all and use the results list.\n\nlibrary('rjags')\n\n# Write model out to file\nfileConn=file(\"model.temp\")\nwriteLines(model, fileConn)\nclose(fileConn)\n\nif(all(is.na(data)))\n{\n\tm = jags.model(file=\"model.temp\", inits=list(.RNG.seed=42, .RNG.name=\"base::Mersenne-Twister\"))\n} else\n{\n\tm = jags.model(file=\"model.temp\", data=data, inits=list(.RNG.seed=42, .RNG.name=\"base::Mersenne-Twister\"))\n}\nupdate(m, burn_in)\ndraw = jags.samples(m, steps, thin=thin, variable.names = variable_names)\n# Convert to a list\nmake_list <- function(draw)\n{\n\tresults = list()\n\tfor(name in names(draw))\n\t{\n\t\t# Extract \"chain 1\"\n\t\tresults[[name]] = as.array(draw[[name]][,,1])\n\t\t\n\t\t# Transpose 2D arrays\n\t\tif(length(dim(results[[name]])) == 2)\n\t\t\tresults[[name]] = t(results[[name]])\n\t}\n\treturn(results)\n}\nresults = make_list(draw)\n\n\n# Save as a text file\nchains = array(NA, dim=c(500, 3))\nchains[,1] = draw$beta0\nchains[,2] = draw$beta1\nchains[,3] = draw$sigma\nwrite.table(chains, 'chains.txt', row.names=FALSE, col.names=FALSE)\nwrite.table(results$y_new, 'prediction.txt', row.names=FALSE, col.names=FALSE)\n\n", "meta": {"hexsha": "ae5d4e1c7c10226f9a0e8fb3a08fb3a070a3f9d3", "size": 1708, "ext": "r", "lang": "R", "max_stars_repo_path": "Code/Regression/use_jags.r", "max_stars_repo_name": "xulinpan/stat331", "max_stars_repo_head_hexsha": "7ca22bf3ce2c43d1a3b5fd8ff22842bdeb87ecf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2015-03-09T18:03:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T03:36:54.000Z", "max_issues_repo_path": "Code/Regression/use_jags.r", "max_issues_repo_name": "xulinpan/stat331", "max_issues_repo_head_hexsha": "7ca22bf3ce2c43d1a3b5fd8ff22842bdeb87ecf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-07-07T05:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-10T08:48:27.000Z", "max_forks_repo_path": "Code/Regression/use_jags.r", "max_forks_repo_name": "xulinpan/stat331", "max_forks_repo_head_hexsha": "7ca22bf3ce2c43d1a3b5fd8ff22842bdeb87ecf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-07-29T14:34:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-04T20:04:47.000Z", "avg_line_length": 20.8292682927, "max_line_length": 107, "alphanum_fraction": 0.6492974239, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.7148380165592063}} {"text": "# Master Thesis Project - Extreme Value Theory\n# Getting the experimental data above the 95 %\n# and fitting a GEV distribution to it\n\n# Clear the environment\nrm(list=ls())\n\n# Close all already open graphic windows\ngraphics.off()\n\n# Sourcing the auxiliary files\nsource(\"loadStockData_plain.r\")\n\n# Remark : the csv uses the metastock data format \n# 7 columns : - Ticker (identifier of the stock\n# and stockmarket on which it is listed)\n#\t\t\t\t\t - Date (yyyymmdd)\n#\t\t\t\t\t - Open\n#\t\t\t\t\t - High\n#\t\t\t\t\t - Low\n#\t\t\t\t\t - Close\n#\t\t\t\t\t - Volume\n# By default, the highest price is used i.e. column 3.\nCHOICE <- 3\n\n# Loading the original data for the five stocks then\n# getting the LVMH and the Total data\ndf_plain <- loadStockData_plain(CHOICE)\n\n# Getting the log-returns\ndata_bnp <- df_plain[[1]]\ndata_bnp <- diff(log(data_bnp))\n\ndata_carrefour <- df_plain[[2]]\ndata_carrefour <- diff(log(data_carrefour))\n\ndata_lvmh <- df_plain[[3]]\ndata_lvmh <- diff(log(data_lvmh))\n\ndata_sanofi <- df_plain[[4]]\ndata_sanofi <- diff(log(data_sanofi))\n\ndata_total <- df_plain[[5]]\ndata_total <- diff(log(data_total))\n\n# Computing the 95 % - quantiles for each of the stocks\nquantiles <- c(quantile(data_bnp,0.99), quantile(data_carrefour,0.995), quantile(data_lvmh,0.995),\n\t\t\t\t\tquantile(data_sanofi,0.995), quantile(data_total,0.995))\n\t\t\t\t\t\n# Getting the data above the threshold\ndata_bnp <- data_bnp[data_bnp > quantiles[1]]\ndata_carrefour <- data_carrefour[data_carrefour > quantiles[2]]\ndata_lvmh <- data_lvmh[data_lvmh > quantiles[3]]\ndata_sanofi <- data_sanofi[data_sanofi > quantiles[4]]\ndata_total <- data_total[data_total > quantiles[5]]\n\n# Plotting the above-threshold data\nx_label <- \"\"\ny_label <- \"Stock price\"\ntitle1 <- \"BNP Paribas log-returns\"\ntitle2 <- \"Carrefour log-returns\"\ntitle3 <- \"LVMH log-returns\"\ntitle4 <- \"Sanofi log-returns\"\ntitle5 <- \"Total log-returns\"\nquartz()\npng(file = \"aboveThresholdData.png\")\npar(mfrow = c(3,2))\nplot(data_bnp, pch = 1, col = \"black\", type = 'p', xlab = x_label, ylab = y_label, main = title1)\nplot(data_carrefour, pch = 1, col = \"blue\", type = 'p', xlab = x_label, ylab = y_label, main = title2)\nplot(data_lvmh, pch = 1, col = \"green\", type = 'p', xlab = x_label, ylab = y_label, main = title3)\nplot(data_sanofi, pch = 1, col = \"purple\", type = 'p', xlab = x_label, ylab = y_label, main = title4)\nplot(data_total, pch = 1, col = \"red\", type = 'p', xlab = x_label, ylab = y_label, main = title5)\ndev.off()\ngraphics.off()\t\t\n\t\nprint(\"##################### BNP Paribas #####################\")\t\t\nquartz()\npng(file = \"gev.diag BNP Paribas\")\ngev.diag(gev.fit(data_bnp))\ndev.off()\ngraphics.off()\n\nprint(\"##################### Carrefour #####################\")\t\t\nquartz()\npng(file = \"gev.diag Carrefour\")\ngev.diag(gev.fit(data_carrefour))\ndev.off()\ngraphics.off()\n\nprint(\"##################### LVMH #####################\")\t\t\nquartz()\npng(file = \"gev.diag LVMH\")\ngev.diag(gev.fit(data_lvmh))\ndev.off()\ngraphics.off()\n\nprint(\"##################### Sanofi #####################\")\t\t\nquartz()\npng(file = \"gev.diag Sanofi\")\ngev.diag(gev.fit(data_sanofi))\ndev.off()\ngraphics.off()\n\nprint(\"##################### Total #####################\")\t\t\nquartz()\npng(file = \"gev.diag Total\")\ngev.diag(gev.fit(data_total))\ndev.off()\ngraphics.off()\n\nprint(\"##################### LVMH 2 #####################\")\t\t\t\ndata_lvmh <- diff(log(df_plain[[3]]))\ndata_lvmh <- data_lvmh[data_lvmh > quantile(data_lvmh,0.95)]\n\nquartz()\npng(file = \"gev.diag LVMH2\")\ngev.diag(gev.fit(data_lvmh))\ndev.off()\ngraphics.off()\n\nprint(\"##################### BNP 2 #####################\")\t\t\ndata_bnp <- diff(log(df_plain[[1]]))\ndata_bnp <- data_bnp[data_bnp > quantile(data_bnp,0.99)]\n\nquartz()\npng(file = \"gev.diag BNP2\")\ngev.diag(gev.fit(data_total))\ndev.off()\ngraphics.off()\n\nprint(\"#################################################\")\nprint(\"#################################################\")\t\t\nprint(\"#################################################\")\t\ndata_lvmh <- as.numeric((read.csv(\"daily_LVMH_table.csv\", header = FALSE))[[3]])\nquartz()\npng(file = \"LVMH_daily.png\")\nplot(1:length(data_lvmh), data_lvmh)\ndev.off()\ngraphics.off()\n\nlvmh_quant <- quantile(data_lvmh, 0.99)\ndata_lvmh <- data_lvmh[data_lvmh > lvmh_quant]\ndata_lvmh <- diff(log(data_lvmh))\n\n\nquartz()\npng(file = \"LVMH_daily_99quant.png\")\nplot(1:length(data_lvmh), data_lvmh)\ndev.off()\ngraphics.off()\n\nquartz()\npng(file = \"gev.diag LVMH3\")\ngev.diag(gev.fit(data_lvmh))\ndev.off()\ngraphics.off()\t\n\n\n\n\n\n", "meta": {"hexsha": "aec979a1dbfd492cb970670bcef3e395808d86ba", "size": 4487, "ext": "r", "lang": "R", "max_stars_repo_path": "r_final_task/ExtremeMeasurements.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r_final_task/ExtremeMeasurements.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r_final_task/ExtremeMeasurements.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6975308642, "max_line_length": 102, "alphanum_fraction": 0.6175618453, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.714760578910538}} {"text": "#ex1\n\nx=c(1, 8, 2, 6, 2, 8, 8, 5, 5, 5)\nprint(sum(x)/10)\nlog2(x)\nmax(x)-min(x)\ny = (x - 5)/2.624669\nprint(y)\nprint(mean(y))\nprint(sd(y))\n\n#ex2\nfactura = c(46, 33, 39, 37, 36, 30, 48, 32, 49, 35, 30, 48)\nprint(sum(factura))\nprint(min(factura))\nprint(max(factura))\nnr_luni = length(factura[factura > 40])\nprint(nr_luni)\nprint(100 * nr_luni/length(factura))\n\n#ex3\nz<-scan()\nprint(min(z))\nprint(max(z))\nprint(mean(z))\nprint(median(z))\nprint(sd(z))\nsort(z)\nprint(z)\nnorm = (z - mean(z))/sd(z)\nprint(norm)", "meta": {"hexsha": "9a987f93a8fac2e5404a15a9de8079f6d351ddfa", "size": 499, "ext": "r", "lang": "R", "max_stars_repo_path": "homework1/hw1.r", "max_stars_repo_name": "Amihaeseisergiu/Special-Chapters-Of-Artificial-Intelligence", "max_stars_repo_head_hexsha": "508de2e5277632d59f3330c9269357fdaf1fb5cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework1/hw1.r", "max_issues_repo_name": "Amihaeseisergiu/Special-Chapters-Of-Artificial-Intelligence", "max_issues_repo_head_hexsha": "508de2e5277632d59f3330c9269357fdaf1fb5cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework1/hw1.r", "max_forks_repo_name": "Amihaeseisergiu/Special-Chapters-Of-Artificial-Intelligence", "max_forks_repo_head_hexsha": "508de2e5277632d59f3330c9269357fdaf1fb5cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0967741935, "max_line_length": 59, "alphanum_fraction": 0.623246493, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.7662936324115012, "lm_q1q2_score": 0.714533030223958}} {"text": "#' Generate a vector of frequencies.\n#'\n#' @param N Number of elements in vector (must be even).\n#' @param freq.max Value of largest frequency.\n#'\n#' @return Vector of frequencies.\n#'\n#' @examples\n#' freq(10, freq.max = 5) # => c(-5, -4, -3, -2, -1, 1, 2, 3, 4, 5)\n#'\n#' @export\nfreq <- function(N, freq.max = 1/(2*pi)) {\n ## Input Validation ##\n\n if (N %% 2) {\n stop(\"'N' must be even\")\n }\n\n\n ## Setup ##\n\n # Precompute N/2, which we know to be an integer.\n half.N <- N / 2\n # Increment between freq[i] and freq[i+1].\n freq.step <- freq.max / half.N\n\n\n ## Frequency Vectors ##\n\n # Obtain the positive frequencies by counting from the smallest\n # one to the maximum. Start counting from 'freq.step', which is\n # the increment between frequencies, as zero frequency is\n # undefined.\n freq.pos <- seq(from = freq.step,\n to = freq.max,\n length.out = half.N)\n # Obtain the negative frequencies by reversing the order on the\n # positive ones, and negating them.\n freq.neg <- -rev(freq.pos)\n # Concatenate the negative and positive frequencies to get the\n # full vector of frequencies.\n freq <- c(freq.neg, freq.pos)\n\n\n ## Return ##\n\n list(\n freq = freq,\n freq.pos = freq.pos,\n freq.neg = freq.neg\n )\n}\n", "meta": {"hexsha": "1ad7cfbde421621216dec6cac793c5a2846d4ba6", "size": 1330, "ext": "r", "lang": "R", "max_stars_repo_path": "R/freq.r", "max_stars_repo_name": "dwysocki/random-noise-generation", "max_stars_repo_head_hexsha": "97bb8392faa4c25399b44b52bc471a95cb44ec7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-24T05:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-24T05:46:19.000Z", "max_issues_repo_path": "R/freq.r", "max_issues_repo_name": "dwysocki/random-noise-generation", "max_issues_repo_head_hexsha": "97bb8392faa4c25399b44b52bc471a95cb44ec7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/freq.r", "max_forks_repo_name": "dwysocki/random-noise-generation", "max_forks_repo_head_hexsha": "97bb8392faa4c25399b44b52bc471a95cb44ec7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0943396226, "max_line_length": 67, "alphanum_fraction": 0.5834586466, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7142585349006592}} {"text": "#ccc computes Lin's concordance correlation coefficient for the two vectors input\n#returns a dataframe containing several parameters\n#[1] ccc\n#[2] mean-shift\n#[3] var shift\n#[4] pearson's correlation \nccc <- function(x,y)\n {\n #check vectors are same length\n if(length(x)!=length(y)) stop(\"Vectors must be same length\")\n if(sum(c(x,y), na.rm=T)==0)\n {\n ccc <- 1\n u <- 0\n v <- 0\n p <- 1\n }\n else\n {\n m1 <- mean(x, na.rm=T)\n m2 <- mean(y, na.rm=T)\n v1 <- var(x, na.rm=T)\n v2 <- var(y, na.rm=T)\n sd1 <- sqrt(v1)\n sd2 <- sqrt(v2)\n \n u <- (m1-m2)/sqrt(sd1*sd2)\n v <- sd1/sd2\n Cb <- 1/((v+(1/v)+u^2)/2)\n \n p <- cor(x,y, use=\"complete.obs\",method=\"pearson\")\n\n B1 <- v*p\n B0 <- m1-(B1*m2)\n a <-(2*B1*v2)\n b <- v1+v2+(B0+(B1-1)*m2)^2\n ccc <- a/b\n }\n return(list(ccc=ccc, u=u, v=v, pearson=p))#, a=a, b=b, v1=v1, v2=v2, b0=B0, b1=B1, m2=m2))\n }\n\n", "meta": {"hexsha": "a545de0a4c33ca47b65bf338ac5008d2ed43ec08", "size": 1019, "ext": "r", "lang": "R", "max_stars_repo_path": "B_Lins_training_pre_survey/Marine_Institute_Ireland/Method_before_2020/functions/ccc.r", "max_stars_repo_name": "jdoylenep/wg_WGNEPS", "max_stars_repo_head_hexsha": "e7dbaab16152cd0d1a293377f9a410c6edb949d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "B_Lins_training_pre_survey/Marine_Institute_Ireland/Method_before_2020/functions/ccc.r", "max_issues_repo_name": "jdoylenep/wg_WGNEPS", "max_issues_repo_head_hexsha": "e7dbaab16152cd0d1a293377f9a410c6edb949d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "B_Lins_training_pre_survey/Marine_Institute_Ireland/Method_before_2020/functions/ccc.r", "max_forks_repo_name": "jdoylenep/wg_WGNEPS", "max_forks_repo_head_hexsha": "e7dbaab16152cd0d1a293377f9a410c6edb949d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-19T11:13:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-04T12:01:37.000Z", "avg_line_length": 24.2619047619, "max_line_length": 94, "alphanum_fraction": 0.4720314033, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7142262867294289}} {"text": "model_tavg <- function (tmin = 0.0,\n tmax = 0.0){\n #'- Name: Tavg -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: Mean temperature calculation\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: It simulates the depth of snow cover and recalculate weather data\n #'- inputs:\n #' * name: tmin\n #' ** description : current minimum air temperature\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : degC\n #' ** uri : \n #' * name: tmax\n #' ** description : current maximum air temperature\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 100.0\n #' ** unit : degC\n #' ** uri : \n #'- outputs:\n #' * name: tavg\n #' ** description : mean temperature\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : degC\n #' ** uri : \n tavg <- (tmin + tmax) / 2\n return (list('tavg' = tavg))\n}", "meta": {"hexsha": "f26c5b5226cb420921485128b80b0140d0e5066f", "size": 1959, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Tavg.r", "max_stars_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_stars_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/STICS_SNOW/Tavg.r", "max_issues_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_issues_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/STICS_SNOW/Tavg.r", "max_forks_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_forks_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6428571429, "max_line_length": 95, "alphanum_fraction": 0.3297600817, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7142091292949696}} {"text": "<<<<<<< HEAD\n#### Healthy Neighborhoods Project: Using Ecological Data to Improve Community Health\n### Neville Subproject: Using Random Forestes, Factor Analysis, and Logistic regression to Screen Variables for Imapcts on Public Health\n## National Health and Nutrition Examination Survey: The R Project for Statistical Computing Script by DrewC!\n# Detecting Prediabetes in those under 65\n\n#### Section A: Prepare Code\n\n### Step 1: Import Libraries and Import Dataset\n\n## Open R Terminal\nR # open R in VS Code (any terminal)\n\n## Import Hadley Wickham Libraries\nlibrary(tidyverse) # All of the libraries above in one line of code\nlibrary(skimr) # Library used for easy summary of data\n\n## Import Machine Learning Libraries\nlibrary(randomForest) # Popular random forest package for R\n\n## Import Statistics Libraries\nlibrary(MASS) # Stepwise inclusion model with linear and logistic options\nlibrary(pROC) # ROC tests with AUC output\nlibrary(psych) # Survey analysis library with factor analysis\nlibrary(GPArotation) # Rotation options for factor analysis\n\n## Import Data\nsetwd(\"C:/Users/drewc/GitHub/Healthy_Neighborhoods\") # Set wd to project repository\ndf_nhanes = read.csv(\"_data/nhanes_1516_noRX_stage.csv\") # Import dataset from _data folder\n\n## Verify\ndim(df_nhanes)\n\n### Step 2: Prepare Data for Classificaiton\n\n## Subset for outcome of interest\ndf_nhanes$outcome <- 0 # Add new outcome column and set value to 0\ndf_nhanes$outcome[df_nhanes$LBXGH >= 5.7 & df_nhanes$LBXGH < 6.4 ] <- 1 # Create new column based on conditions\ndf_nh = subset(df_nhanes, select = -c(SEQN, LBXGH, DIQ010))\n\n## Resolve missing data\ndf_nev = df_nh[, -which(colSums(is.na(df_nh)) > 3646)] # Remove variables with high missing values\ndf_nev = subset(df_nev, select = -c(AUATYMTL, SLQ300, SLQ310, AUATYMTR)) # Remove variables with factor value types\ndf_nev = na.omit(df_nev) # Omit rows with NA from Data Frame\ndf_nev = df_nev[which(df_nev$RIDAGEYR < 65), ]\n\n## Verify \ndim(df_nev)\ncolnames(df_nev)\n\n#### Section B: Vairable Selection using Quantitative and Qualitative Methods\n\n### Step 3: Conduct Factor Analysis to Identify Latent Variables\n\n## Subset by group with outcome\ndf_fa = subset(df_nev, outcome == 1) # Subset for outcome of interest\ndf_fa = subset(df_fa, select = -(outcome)) # Remove outcome variable\ndf_fa = na.omit(df_fa)\nnrow(df_fa) # Check number of rows\n\n## Perform Scree test and loadings\ncor_fa = cor(df_fa)\ncor_fa[!is.finite(cor_fa)] <- 0\nmodel_scree = fa.parallel(cor_fa) # Create scree plot to determine number of latent variables\nprint(model_scree)\n\n## Write Scree Test Output to File\nresult = model_scree # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"w\") # Open file and \"a\" to append\nwrite(\"Factor Analysis\", file) # Insert title\nwrite(\" \", file) # Insert space below title\nwrite(\"Eigenvalues from Scree Test\", file) # Insert title\nwrite(\" \", file) # Insert space below title\ncapture.output(result, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n## Idenitfy Loadings\nfactors = fa(r = cor_fa, nfactors = 10)\ndf_load = as.data.frame(unclass(factors$loadings))\ndf_ld = df_load[, which(apply(df_load, 2, max) > 0.5)] # Remove variables with high missing values\ncolnames(df_ld)\n\ndf_ld$factor1[df_ld$MR1 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor2[df_ld$MR2 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor3[df_ld$MR3 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor4[df_ld$MR4 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor5[df_ld$MR5 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor6[df_ld$MR6 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor7[df_ld$MR7 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor8[df_ld$MR8 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor9[df_ld$MR9 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor10[df_ld$MR10 > 0.5] <- 1 # Create new column based on conditions\ndf_ld = subset(df_ld, select = -c(MR1, MR2, MR3, MR4, MR5, MR6, MR7, MR8, MR9, MR10))\n\ndf_f1 = subset(df_ld, factor1 == 1) # Subset for outcome of interest\ndf_f1 = df_f1[\"factor1\"]\ndf_f2 = subset(df_ld, factor2 == 1) # Subset for outcome of interest\ndf_f2 = df_f2[\"factor2\"]\ndf_f3 = subset(df_ld, factor3 == 1) # Subset for outcome of \ndf_f3 = df_f3[\"factor3\"]\ndf_f4 = subset(df_ld, factor4 == 1) # Subset for outcome of interest\ndf_f4 = df_f4[\"factor4\"]\ndf_f5 = subset(df_ld, factor5 == 1) # Subset for outcome of interest\ndf_f5 = df_f5[\"factor5\"]\ndf_f6 = subset(df_ld, factor6 == 1) # Subset for outcome of interest\ndf_f6 = df_f6[\"factor6\"]\ndf_f7 = subset(df_ld, factor7 == 1) # Subset for outcome of interest\ndf_f7 = df_f7[\"factor7\"]\ndf_f8 = subset(df_ld, factor8 == 1) # Subset for outcome of interest\ndf_f8 = df_f8[\"factor8\"]\ndf_f9 = subset(df_ld, factor9 == 1) # Subset for outcome of interest\ndf_f9 = df_f9[\"factor9\"]\ndf_f10 = subset(df_ld, factor10 == 1) # Subset for outcome of interest\ndf_f10 = df_f10[\"factor10\"]\n\n## Write Scree Test Output to File\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"a\" to append\nwrite(\"Factor Loadings\", file) # Insert title\nwrite(\" \", file) # Insert space below title\ncapture.output(df_f1, file = file, append = TRUE) # write summary to file\ncapture.output(df_f2, file = file, append = TRUE) # write summary to file\ncapture.output(df_f3, file = file, append = TRUE) # write summary to file\ncapture.output(df_f4, file = file, append = TRUE) # write summary to file\ncapture.output(df_f5, file = file, append = TRUE) # write summary to file\ncapture.output(df_f6, file = file, append = TRUE) # write summary to file\ncapture.output(df_f7, file = file, append = TRUE) # write summary to file\ncapture.output(df_f8, file = file, append = TRUE) # write summary to file\ncapture.output(df_f9, file = file, append = TRUE) # write summary to file\ncapture.output(df_f10, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n### Step 4: Use a Random Forest to rank variables by importance \n\n## Create a Random Forest\ndf_rf = df_nev\nforest = randomForest(formula = outcome ~ ., data = df_rf, ntree = 1000, importance = TRUE) # This will take time\nsummary(forest) # Summary of forest model\n\n## Tidy Results for Variable Classification\nmat_forest = round(importance(forest), 2) # Round importance outcomes to two places,\ndf_forest = as.data.frame(mat_forest) # Save as data frame\ndf_forest = rownames_to_column(df_forest)\ncolnames(df_forest) <- c(\"Variable\", \"MSE\", \"Gini\") # Change column names to easily readible. Both values correspond to the summed increse in either Mean Squared Error or Gini as the variable is removed. Both are important and used elsewhere in randomforests (Scikit-learn). \n\n## Create Importance Variable Lists\ndf_rank = arrange(df_forest, desc(Gini)) # Descend by variable in data frame\ndf_rank = df_rank[which(df_rank$Gini > 0 & df_rank$MSE > 0), ]\nprint(df_rank) # Print output\n\n## Write Random Forest Output to File\nresult = print(df_rank) # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"w\" to overwrite\nwrite(\"Random Forest Variable Classification\", file) # Insert title\nwrite(\" \", file) # Insert space below title\nwrite.table(result, file, quote = FALSE, sep = \" \") # write table of values to filee\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n### Summary Statistics of Model Variables\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"w\" to overwrite\nwrite(\"Summary of Model Variables\", file) # Insert title\nwrite(\" \", file) # Insert space below result\nwrite(\"OHX19TC\", file) # Insert space below title\ncapture.output(summary(df_nev$OHX19TC), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"BMDAVSAD\", file) # Insert space below title\ncapture.output(summary(df_nev$BMDAVSAD), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"INDFMMPI\", file) # Insert space below title\ncapture.output(summary(df_nev$INDFMMPI), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"INQ080\", file) # Insert space below title\ncapture.output(summary(df_nev$INQ080), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"BMXLEG\", file) # Insert space below title\ncapture.output(summary(df_nev$BMXLEG), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"LBXWBCSI\", file) # Insert space below title\ncapture.output(summary(df_nev$LBXWBCSI), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"LBXRDW\", file) # Insert space below title\ncapture.output(summary(df_nev$LBXRDW), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"BPXDI3\", file) # Insert space below title\ncapture.output(summary(df_nev$BPXDI3), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"LBDRFO\", file) # Insert space below title\ncapture.output(summary(df_nev$LBDRFO), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n### Step 5: Liner Regression to Determine Direction of Impact\n\nmodel_logistic <- glm(outcome~ OHX19TC + BMDAVSAD + INDFMMPI + INQ080 + BMXLEG + LBXWBCSI + LBXRDW + BPXDI3 + LBDRFO, data = df_nev)\nsummary(model_logistic)\n\n## Write Model Output to File\nresult = summary(model_logistic) # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"a\" to append\nwrite(\" \", file) # Insert space below title\nwrite(\"First Logistic Regression for Variable Direction\", file) # Insert title\nwrite(\" \", file) # Insert space below title\ncapture.output(result, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n#### Section C: Build Regression Model and Risk Score for Validation \n\n### Step 5: Create Dichotomous Variables Based on 3rd Quartile\n\n## Create New Variables\ndf_nh$V1 <- 0 # Add new outcome column and set value to 0\ndf_nh$V2 <- 0 # Add new outcome column and set value to 0\ndf_nh$V3 <- 0 # Add new outcome column and set value to 0\ndf_nh$V4 <- 0 # Add new outcome column and set value to 0\ndf_nh$V5 <- 0 # Add new outcome column and set value to 0\ndf_nh$V1[df_nh$OHX01TC == 4 | df_nh$OHX02TC == 4 | df_nh$OHX03TC == 4 | df_nh$OHX04TC == 4 | df_nh$OHX05TC == 4 | df_nh$OHX06TC == 4 | df_nh$OHX07TC == 4 | df_nh$OHX08TC == 4 | df_nh$OHX09TC == 4 | df_nh$OHX10TC == 4 | df_nh$OHX11TC == 4 | df_nh$OHX12TC == 4 | df_nh$OHX13TC == 4 | df_nh$OHX14TC == 4 | df_nh$OHX15TC == 4 | df_nh$OHX16TC == 4 | df_nh$OHX17TC == 4 | df_nh$OHX18TC == 4 | df_nh$OHX19TC == 4 | df_nh$OHX20TC == 4 | df_nh$OHX21TC == 4 | df_nh$OHX22TC == 4 | df_nh$OHX23TC == 4 | df_nh$OHX24TC == 4 | df_nh$OHX25TC == 4 | df_nh$OHX26TC == 4 | df_nh$OHX27TC == 4 | df_nh$OHX28TC == 4 | df_nh$OHX29TC == 4 | df_nh$OHX30TC == 4 | df_nh$OHX31TC == 4 | df_nh$OHX32TC == 4] <- 1 # Create new column based on conditions\ndf_nh$V2[df_nh$BMDAVSAD > 25.1] <- 1 # Create new column based on conditions\ndf_nh$V3[df_nh$INDFMMPI > 5] <- 1 # Create new column based on conditions\ndf_nh$V4[df_nh$INQ080 == 1] <- 1 # Create new column based on conditions\ndf_nh$V5[df_nh$BMXLEG < 41.58] <- 1 # Create new column based on conditions\n\n## Resolve missing data\ndf_lon = subset(df_nh, select = c(outcome, V1, V2, V3, V4, V5)) # Remove variables with factor value types\ndf_lon = na.omit(df_lon) # Omit rows with NA from Data Frame\ndim(df_lon)\n\n### Step 6: Logistic Regression with Stepwise Selection for Final Model\n\n## Create training and validation set\nsample = sample.int(n = nrow(df_lon), size = floor(.50*nrow(df_lon)), replace = F) # Create training and testing dataset with 50% split\ntrain = df_lon[sample, ] # Susbset data frame by sample\ntest = df_lon[-sample, ] # Subset data frame by removing sample\n\n## Perform Logisitc Regression on selected variables\nmodel_logistic = glm(outcome~ V1 + V2 + V3 + V4 + V5, data = train)\nsummary(model_logistic)\n\n## Stepwise backward selection\nmodel_back = stepAIC(model_logistic, direction = \"backward\") # Stepwise backwards selection on model\nsummary(model_back) # Output model summary and check for variables to remove for final model\n\n## Write Quantitative Selection Model Output to File\nresult1 = print(summary(model_logistic)) # Save result df to variable\nresult2 = print(summary(model_back)) # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"a\" to append\nwrite(\"Training Logistic Regression Model\", file) # Insert space below title\nwrite(\" \", file) # Insert space below title\ncapture.output(result, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below title\nwrite(\"Stepwise Backwards Selection\", file) # Insert space below title\nwrite(\" \", file) # Insert space below title\ncapture.output(result2, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below title\nclose(file) # Close file\n\n### Step 7: Create Score and Verify\n\n# Create new column based on conditions\ntest$score <- 0 # Add new outcome column and set value to 0\ntest$score = (20*test$V2) + (15*test$V4) + (10*test$V5)\n\n## Final Model and AUC Score\nmodel_score = glm(outcome~ score, data = test) # Perform logistic regression model on selected variables on test data\nroc_test = roc(model_score$y, model_score$fitted.values, ci = T, plot = T) # Perform ROC test on test data\nauc(roc_test) # Print AUC score\n\n## Write Quantitative Selection Model Output to File\nresult = print(auc(roc_test)) # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"a\" to append\nwrite(\"Risk Score Validation\", file) # Insert space below title\nwrite(\" \", file) # Insert space below title\ncapture.output(result, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below title\nclose(file) # Close file\n\n=======\n#### Healthy Neighborhoods Project: Using Ecological Data to Improve Community Health\n### Neville Subproject: Using Random Forestes, Factor Analysis, and Logistic regression to Screen Variables for Imapcts on Public Health\n## National Health and Nutrition Examination Survey: The R Project for Statistical Computing Script by DrewC!\n# Detecting Prediabetes in those under 65\n\n#### Section A: Prepare Code\n\n### Step 1: Import Libraries and Import Dataset\n\n## Open R Terminal\nR # open R in VS Code (any terminal)\n\n## Import Hadley Wickham Libraries\nlibrary(tidyverse) # All of the libraries above in one line of code\nlibrary(skimr) # Library used for easy summary of data\n\n## Import Machine Learning Libraries\nlibrary(randomForest) # Popular random forest package for R\n\n## Import Statistics Libraries\nlibrary(MASS) # Stepwise inclusion model with linear and logistic options\nlibrary(pROC) # ROC tests with AUC output\nlibrary(psych) # Survey analysis library with factor analysis\nlibrary(GPArotation) # Rotation options for factor analysis\n\n## Import Data\nsetwd(\"C:/Users/drewc/GitHub/Healthy_Neighborhoods\") # Set wd to project repository\ndf_nhanes = read.csv(\"_data/nhanes_1516_noRX_stage.csv\") # Import dataset from _data folder\n\n## Verify\ndim(df_nhanes)\n\n### Step 2: Prepare Data for Classificaiton\n\n## Subset for outcome of interest\ndf_nhanes$outcome <- 0 # Add new outcome column and set value to 0\ndf_nhanes$outcome[df_nhanes$LBXGH >= 5.7 & df_nhanes$LBXGH < 6.4 ] <- 1 # Create new column based on conditions\ndf_nh = subset(df_nhanes, select = -c(SEQN, LBXGH, DIQ010))\n\n## Resolve missing data\ndf_nev = df_nh[, -which(colSums(is.na(df_nh)) > 3646)] # Remove variables with high missing values\ndf_nev = subset(df_nev, select = -c(AUATYMTL, SLQ300, SLQ310, AUATYMTR)) # Remove variables with factor value types\ndf_nev = na.omit(df_nev) # Omit rows with NA from Data Frame\ndf_nev = df_nev[which(df_nev$RIDAGEYR < 65), ]\n\n## Verify \ndim(df_nev)\ncolnames(df_nev)\n\n#### Section B: Vairable Selection using Quantitative and Qualitative Methods\n\n### Step 3: Conduct Factor Analysis to Identify Latent Variables\n\n## Subset by group with outcome\ndf_fa = subset(df_nev, outcome == 1) # Subset for outcome of interest\ndf_fa = subset(df_fa, select = -(outcome)) # Remove outcome variable\ndf_fa = na.omit(df_fa)\nnrow(df_fa) # Check number of rows\n\n## Perform Scree test and loadings\ncor_fa = cor(df_fa)\ncor_fa[!is.finite(cor_fa)] <- 0\nmodel_scree = fa.parallel(cor_fa) # Create scree plot to determine number of latent variables\nprint(model_scree)\n\n## Write Scree Test Output to File\nresult = model_scree # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"w\") # Open file and \"a\" to append\nwrite(\"Factor Analysis\", file) # Insert title\nwrite(\" \", file) # Insert space below title\nwrite(\"Eigenvalues from Scree Test\", file) # Insert title\nwrite(\" \", file) # Insert space below title\ncapture.output(result, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n## Idenitfy Loadings\nfactors = fa(r = cor_fa, nfactors = 10)\ndf_load = as.data.frame(unclass(factors$loadings))\ndf_ld = df_load[, which(apply(df_load, 2, max) > 0.5)] # Remove variables with high missing values\ncolnames(df_ld)\n\ndf_ld$factor1[df_ld$MR1 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor2[df_ld$MR2 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor3[df_ld$MR3 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor4[df_ld$MR4 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor5[df_ld$MR5 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor6[df_ld$MR6 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor7[df_ld$MR7 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor8[df_ld$MR8 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor9[df_ld$MR9 > 0.5] <- 1 # Create new column based on conditions\ndf_ld$factor10[df_ld$MR10 > 0.5] <- 1 # Create new column based on conditions\ndf_ld = subset(df_ld, select = -c(MR1, MR2, MR3, MR4, MR5, MR6, MR7, MR8, MR9, MR10))\n\ndf_f1 = subset(df_ld, factor1 == 1) # Subset for outcome of interest\ndf_f1 = df_f1[\"factor1\"]\ndf_f2 = subset(df_ld, factor2 == 1) # Subset for outcome of interest\ndf_f2 = df_f2[\"factor2\"]\ndf_f3 = subset(df_ld, factor3 == 1) # Subset for outcome of \ndf_f3 = df_f3[\"factor3\"]\ndf_f4 = subset(df_ld, factor4 == 1) # Subset for outcome of interest\ndf_f4 = df_f4[\"factor4\"]\ndf_f5 = subset(df_ld, factor5 == 1) # Subset for outcome of interest\ndf_f5 = df_f5[\"factor5\"]\ndf_f6 = subset(df_ld, factor6 == 1) # Subset for outcome of interest\ndf_f6 = df_f6[\"factor6\"]\ndf_f7 = subset(df_ld, factor7 == 1) # Subset for outcome of interest\ndf_f7 = df_f7[\"factor7\"]\ndf_f8 = subset(df_ld, factor8 == 1) # Subset for outcome of interest\ndf_f8 = df_f8[\"factor8\"]\ndf_f9 = subset(df_ld, factor9 == 1) # Subset for outcome of interest\ndf_f9 = df_f9[\"factor9\"]\ndf_f10 = subset(df_ld, factor10 == 1) # Subset for outcome of interest\ndf_f10 = df_f10[\"factor10\"]\n\n## Write Scree Test Output to File\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"a\" to append\nwrite(\"Factor Loadings\", file) # Insert title\nwrite(\" \", file) # Insert space below title\ncapture.output(df_f1, file = file, append = TRUE) # write summary to file\ncapture.output(df_f2, file = file, append = TRUE) # write summary to file\ncapture.output(df_f3, file = file, append = TRUE) # write summary to file\ncapture.output(df_f4, file = file, append = TRUE) # write summary to file\ncapture.output(df_f5, file = file, append = TRUE) # write summary to file\ncapture.output(df_f6, file = file, append = TRUE) # write summary to file\ncapture.output(df_f7, file = file, append = TRUE) # write summary to file\ncapture.output(df_f8, file = file, append = TRUE) # write summary to file\ncapture.output(df_f9, file = file, append = TRUE) # write summary to file\ncapture.output(df_f10, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n### Step 4: Use a Random Forest to rank variables by importance \n\n## Create a Random Forest\ndf_rf = df_nev\nforest = randomForest(formula = outcome ~ ., data = df_rf, ntree = 1000, importance = TRUE) # This will take time\nsummary(forest) # Summary of forest model\n\n## Tidy Results for Variable Classification\nmat_forest = round(importance(forest), 2) # Round importance outcomes to two places,\ndf_forest = as.data.frame(mat_forest) # Save as data frame\ndf_forest = rownames_to_column(df_forest)\ncolnames(df_forest) <- c(\"Variable\", \"MSE\", \"Gini\") # Change column names to easily readible. Both values correspond to the summed increse in either Mean Squared Error or Gini as the variable is removed. Both are important and used elsewhere in randomforests (Scikit-learn). \n\n## Create Importance Variable Lists\ndf_rank = arrange(df_forest, desc(Gini)) # Descend by variable in data frame\ndf_rank = df_rank[which(df_rank$Gini > 0 & df_rank$MSE > 0), ]\nprint(df_rank) # Print output\n\n## Write Random Forest Output to File\nresult = print(df_rank) # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"w\" to overwrite\nwrite(\"Random Forest Variable Classification\", file) # Insert title\nwrite(\" \", file) # Insert space below title\nwrite.table(result, file, quote = FALSE, sep = \" \") # write table of values to filee\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n### Summary Statistics of Model Variables\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"w\" to overwrite\nwrite(\"Summary of Model Variables\", file) # Insert title\nwrite(\" \", file) # Insert space below result\nwrite(\"OHX19TC\", file) # Insert space below title\ncapture.output(summary(df_nev$OHX19TC), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"BMDAVSAD\", file) # Insert space below title\ncapture.output(summary(df_nev$BMDAVSAD), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"INDFMMPI\", file) # Insert space below title\ncapture.output(summary(df_nev$INDFMMPI), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"INQ080\", file) # Insert space below title\ncapture.output(summary(df_nev$INQ080), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"BMXLEG\", file) # Insert space below title\ncapture.output(summary(df_nev$BMXLEG), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"LBXWBCSI\", file) # Insert space below title\ncapture.output(summary(df_nev$LBXWBCSI), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"LBXRDW\", file) # Insert space below title\ncapture.output(summary(df_nev$LBXRDW), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"BPXDI3\", file) # Insert space below title\ncapture.output(summary(df_nev$BPXDI3), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nwrite(\"LBDRFO\", file) # Insert space below title\ncapture.output(summary(df_nev$LBDRFO), file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n### Step 5: Liner Regression to Determine Direction of Impact\n\nmodel_logistic <- glm(outcome~ OHX19TC + BMDAVSAD + INDFMMPI + INQ080 + BMXLEG + LBXWBCSI + LBXRDW + BPXDI3 + LBDRFO, data = df_nev)\nsummary(model_logistic)\n\n## Write Model Output to File\nresult = summary(model_logistic) # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"a\" to append\nwrite(\" \", file) # Insert space below title\nwrite(\"First Logistic Regression for Variable Direction\", file) # Insert title\nwrite(\" \", file) # Insert space below title\ncapture.output(result, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below result\nclose(file) # Close file\n\n#### Section C: Build Regression Model and Risk Score for Validation \n\n### Step 5: Create Dichotomous Variables Based on 3rd Quartile\n\n## Create New Variables\ndf_nh$V1 <- 0 # Add new outcome column and set value to 0\ndf_nh$V2 <- 0 # Add new outcome column and set value to 0\ndf_nh$V3 <- 0 # Add new outcome column and set value to 0\ndf_nh$V4 <- 0 # Add new outcome column and set value to 0\ndf_nh$V5 <- 0 # Add new outcome column and set value to 0\ndf_nh$V1[df_nh$OHX01TC == 4 | df_nh$OHX02TC == 4 | df_nh$OHX03TC == 4 | df_nh$OHX04TC == 4 | df_nh$OHX05TC == 4 | df_nh$OHX06TC == 4 | df_nh$OHX07TC == 4 | df_nh$OHX08TC == 4 | df_nh$OHX09TC == 4 | df_nh$OHX10TC == 4 | df_nh$OHX11TC == 4 | df_nh$OHX12TC == 4 | df_nh$OHX13TC == 4 | df_nh$OHX14TC == 4 | df_nh$OHX15TC == 4 | df_nh$OHX16TC == 4 | df_nh$OHX17TC == 4 | df_nh$OHX18TC == 4 | df_nh$OHX19TC == 4 | df_nh$OHX20TC == 4 | df_nh$OHX21TC == 4 | df_nh$OHX22TC == 4 | df_nh$OHX23TC == 4 | df_nh$OHX24TC == 4 | df_nh$OHX25TC == 4 | df_nh$OHX26TC == 4 | df_nh$OHX27TC == 4 | df_nh$OHX28TC == 4 | df_nh$OHX29TC == 4 | df_nh$OHX30TC == 4 | df_nh$OHX31TC == 4 | df_nh$OHX32TC == 4] <- 1 # Create new column based on conditions\ndf_nh$V2[df_nh$BMDAVSAD > 25.1] <- 1 # Create new column based on conditions\ndf_nh$V3[df_nh$INDFMMPI > 5] <- 1 # Create new column based on conditions\ndf_nh$V4[df_nh$INQ080 == 1] <- 1 # Create new column based on conditions\ndf_nh$V5[df_nh$BMXLEG < 41.58] <- 1 # Create new column based on conditions\n\n## Resolve missing data\ndf_lon = subset(df_nh, select = c(outcome, V1, V2, V3, V4, V5)) # Remove variables with factor value types\ndf_lon = na.omit(df_lon) # Omit rows with NA from Data Frame\ndim(df_lon)\n\n### Step 6: Logistic Regression with Stepwise Selection for Final Model\n\n## Create training and validation set\nsample = sample.int(n = nrow(df_lon), size = floor(.50*nrow(df_lon)), replace = F) # Create training and testing dataset with 50% split\ntrain = df_lon[sample, ] # Susbset data frame by sample\ntest = df_lon[-sample, ] # Subset data frame by removing sample\n\n## Perform Logisitc Regression on selected variables\nmodel_logistic = glm(outcome~ V1 + V2 + V3 + V4 + V5, data = train)\nsummary(model_logistic)\n\n## Stepwise backward selection\nmodel_back = stepAIC(model_logistic, direction = \"backward\") # Stepwise backwards selection on model\nsummary(model_back) # Output model summary and check for variables to remove for final model\n\n## Write Quantitative Selection Model Output to File\nresult1 = print(summary(model_logistic)) # Save result df to variable\nresult2 = print(summary(model_back)) # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"a\" to append\nwrite(\"Training Logistic Regression Model\", file) # Insert space below title\nwrite(\" \", file) # Insert space below title\ncapture.output(result, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below title\nwrite(\"Stepwise Backwards Selection\", file) # Insert space below title\nwrite(\" \", file) # Insert space below title\ncapture.output(result2, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below title\nclose(file) # Close file\n\n### Step 7: Create Score and Verify\n\n# Create new column based on conditions\ntest$score <- 0 # Add new outcome column and set value to 0\ntest$score = (20*test$V2) + (15*test$V4) + (10*test$V5)\n\n## Final Model and AUC Score\nmodel_score = glm(outcome~ score, data = test) # Perform logistic regression model on selected variables on test data\nroc_test = roc(model_score$y, model_score$fitted.values, ci = T, plot = T) # Perform ROC test on test data\nauc(roc_test) # Print AUC score\n\n## Write Quantitative Selection Model Output to File\nresult = print(auc(roc_test)) # Save result df to variable\nfile = file(\"neville/neville_nhanes_pdm_under_results.txt\") # Open result file in subproject repository\nopen(file, \"a\") # Open file and \"a\" to append\nwrite(\"Risk Score Validation\", file) # Insert space below title\nwrite(\" \", file) # Insert space below title\ncapture.output(result, file = file, append = TRUE) # write summary to file\nwrite(\" \", file) # Insert space below title\nclose(file) # Close file\n\n>>>>>>> 321eaea894d29a3f212ee3e111b86695f46cf6db\n", "meta": {"hexsha": "7660eb8a261fe231c39357c979a5456e2291d45e", "size": 29562, "ext": "r", "lang": "R", "max_stars_repo_path": "_archive/_archive/neville_nhanes_predm_alpha.r", "max_stars_repo_name": "andrewcistola/healthy-neighborhoods", "max_stars_repo_head_hexsha": "08bd0cd9dcb81b083a003943cd6679ca12237a1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-13T17:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T17:50:08.000Z", "max_issues_repo_path": "_archive/_archive/neville_nhanes_predm_alpha.r", "max_issues_repo_name": "andrewcistola/healthy-neighborhoods", "max_issues_repo_head_hexsha": "08bd0cd9dcb81b083a003943cd6679ca12237a1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_archive/_archive/neville_nhanes_predm_alpha.r", "max_forks_repo_name": "andrewcistola/healthy-neighborhoods", "max_forks_repo_head_hexsha": "08bd0cd9dcb81b083a003943cd6679ca12237a1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.6818181818, "max_line_length": 724, "alphanum_fraction": 0.73465936, "num_tokens": 8647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7141218763131563}} {"text": "#' @title pvalue.rsquare\n#' @description unknown\n#' @family abysmally documented\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\n\tpvalue.rsquare = function( M ) {\n\t\t# R^2 = SSDmodel/(SSDmodel+SSDres) \n\t\t# F = DFres/DFmodel*SSDmodel/SSDres\n\t # 1/R^2 = 1 + 1/F*DFmodel/DFres \n\t\t# or, \n\t\t# F = 1/(1/R^2 - 1)*DFres/DFmodel = R^2/(1-R^2)*DFres/DFmodel \n\t\t\t# \n\t\t# Actually, R^2 itself has a beta distribution and you could use pbeta\n\t\t# directly, but then you'd need to figure out (or recall) what the\n\t\t# relation between the DF and the shape parameters of the beta\n\t\t# distribution are. By my reckoning, this should do it:\n\t\t# pbeta(Rsq, 1/2, (N-2)/2, lower.tail=FALSE)\n\t\t# \n\t\t# Residual standard error: 1.143 on 8 degrees of freedom\n\t\t# Multiple R-Squared: 0.0004207, Adjusted R-squared: -0.1245\n\t\t# F-statistic: 0.003367 on 1 and 8 DF, p-value: 0.9552\n\t\t# pbeta(0.0004207, 1/2, 8/2, lower=F)\n\t\t# >[1] 0.9551511\n\t\t\n\t\tdfres = df.residual(M)\n\t\tdfmod = sum( df.terms(M))\n\t\trsq = summary(M)$r.squared\n\t\tFval = 1/(1/ rsq - 1)*dfres/dfmod\n\t\t\n\t\tout = list( \n\t\t\trsquare=rsq, \n\t\t\tdfmod = dfmod,\n\t\t\tdfres = dfres,\n\t\t\tFval = Fval,\n\t\t\tpvalF = pf(Fval, sum( df.terms(M)) , df.residual(M), lower.tail=FALSE),\n\t\t\tpvalB = pbeta( rsq, dfmod/2, dfres/2, lower.tail=FALSE )\n\t\t)\n\t\treturn (out)\n\n\t}\n\n", "meta": {"hexsha": "d90724a279701ae6d4e6c29ebfecf8ad6405b93d", "size": 1295, "ext": "r", "lang": "R", "max_stars_repo_path": "R/pvalue.rsquare.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/pvalue.rsquare.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/pvalue.rsquare.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8333333333, "max_line_length": 74, "alphanum_fraction": 0.6347490347, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7140814543365902}} {"text": "DS <-function(train_X,train_Y){\r\n n_row <- nrow(train_X)\r\n Region <- function(s_rm,s_lstat){\r\n # Variables for finding our RSS for lstat and rm\r\n sum_lessthan_rm <-0\r\n sum_grtrthan_rm <-0\r\n sum_lessthan_lstat <-0\r\n sum_grtrthan_lstat <-0\r\n \r\n n_lessthan_rm <-0\r\n n_grtrthan_rm <-0\r\n n_lessthan_lstat <-0\r\n n_grtrthan_lstat <-0\r\n \r\n mean_Y_lessthan_rm <-0\r\n mean_Y_grtrthan_rm <-0\r\n mean_Y_lessthan_lstat <-0\r\n mean_Y_grtrthan_lstat <-0\r\n \r\n sum_grtrthan_sqr_rm <-0\r\n sum_lessthan_sqr_rm <-0\r\n sum_grtrthan_sqr_lstat <-0\r\n sum_lessthan_sqr_lstat <-0\r\n \r\n \r\n # Getting Regions for all S\r\n for(i in 1:n_row){\r\n if(train_X$rm[i] < s_rm){\r\n sum_lessthan_rm = sum_lessthan_rm + train_Y[i]\r\n n_lessthan_rm = n_lessthan_rm + 1\r\n }\r\n else{\r\n sum_grtrthan_rm = sum_grtrthan_rm + train_Y[i]\r\n n_grtrthan_rm = n_grtrthan_rm + 1\r\n }\r\n if(train_X$lstat[i] < s_lstat){\r\n sum_lessthan_lstat = sum_lessthan_lstat + train_Y[i]\r\n n_lessthan_lstat = n_lessthan_lstat + 1\r\n }\r\n else{\r\n sum_grtrthan_lstat = sum_grtrthan_lstat + train_Y[i]\r\n n_grtrthan_lstat = n_grtrthan_lstat + 1\r\n }\r\n }\r\n mean_Y_lessthan_rm = sum_lessthan_rm/n_lessthan_rm\r\n mean_Y_grtrthan_rm = sum_grtrthan_rm/n_grtrthan_rm\r\n mean_Y_lessthan_lstat = sum_lessthan_rm/n_lessthan_lstat\r\n mean_Y_grtrthan_lstat = sum_grtrthan_rm/n_grtrthan_lstat\r\n \r\n for(i in 1:n_row){\r\n if(train_X$rm[i] min(Rss_arr_rm[1,])){\r\n s_id = which.min(Rss_arr_rm)\r\n S <- train_X$rm[s_id]\r\n #caclulating regions R\r\n for(i in 1:n_row){\r\n #computing in each possible s\r\n if (train_X$rm[i] < S)\r\n {\r\n sumlessthan = sumlessthan+ train_Y[i]\r\n numlessthan =numlessthan+1\r\n }\r\n else{\r\n sumgreaterthan = sumgreaterthan+ train_Y[i]\r\n numgreaterthan = numgreaterthan+1\r\n }\r\n \r\n }\r\n meanYlessthan <- sumlessthan/numlessthan\r\n meanYgreatethan <- sumgreaterthan/numgreaterthan\r\n returnArray =c(\"rm\",S,meanYlessthan,meanYgreatethan)\r\n return(returnArray)\r\n }\r\n else{\r\n sIndex =which.min(Rss_arr_lstat)\r\n S<- train_X$lstat[sIndex]\r\n #caclulating regions R\r\n for(i in 1:253){\r\n #computing in each possible s\r\n if (train_X$lstat[i] < S)\r\n {\r\n sumlessthan = sumlessthan+ train_Y[i]\r\n numlessthan =numlessthan+1\r\n }\r\n if(train_X$lstat[i] >S){\r\n sumgreaterthan = sumgreaterthan+ train_Y[i]\r\n numgreaterthan = numgreaterthan+1\r\n }\r\n \r\n }\r\n meanYlessthan <- sumlessthan/numlessthan\r\n meanYgreatethan <- sumgreaterthan/numgreaterthan\r\n returnArray= c(\"lstat\",S,meanYlessthan,meanYgreatethan)\r\n return(returnArray)\r\n \r\n }\r\n}\r\n\r\n\r\nlibrary(MASS)\r\ndata(\"Boston\")\r\nset.seed(0911)\r\nn_row = nrow(Boston)\r\ndt <- sample(1:n_row,n_row/2)\r\ntrain <- Boston[dt,]\r\ntest <- Boston[-dt,]\r\ntrain_Y <- train$medv;\r\n\r\ndec_stmp = DS(train,train_Y)\r\ny_hat = matrix(nrow=1, ncol=nrow(test)) \r\n\r\ntest_sum_less_sqr <-0\r\ntest_sum_grtr_sqr <-0\r\nif(dec_stmp[1]==\"lstat\"){\r\n for(i in 1:nrow(test)){\r\n if(test$lstat[i] Sum\", hoverlabel = list(namelength = -1), \r\n line = list(color = \"#000000\", width = 2) )\r\n\r\nfor ( idx in seq(from = 2, to = length(r_PTS)) ) {\r\n p <- plotly::add_trace(\r\n p, type = \"bar\", alpha = 0.5, yaxis = \"y2\", \r\n x = as.ordered(indices), y = abel_weights[idx-1,], \r\n name = paste0(\"Abel Weights with r = \", sprintf(\"%.4f\", r_PTS[idx])), \r\n hoverlabel = list(namelength = -1), \r\n color = color_palette[idx] )\r\n p <- plotly::add_trace(\r\n p, type = \"scatter\", mode = \"lines\", \r\n x = as.ordered(indices), y = abel_mean[idx], yaxis = \"y\", \r\n name = paste0(\"Abel Sum with r = \", sprintf(\"%.4f\", r_PTS[idx])), \r\n hoverlabel = list(namelength = -1), \r\n color = color_palette[idx], alpha = 0.5 )\r\n}\r\n\r\np <- plotly::add_trace(\r\n p, type = \"scatter\", mode = \"lines+markers\", \r\n x = as.ordered(indices), y = series, yaxis = \"y\", \r\n name = \"Sequence a_k\", hoverlabel = list(namelength = -1), \r\n color = color_palette[length(r_PTS) + 1], alpha = 0.7 )\r\np <- plotly::add_trace(\r\n p, type = \"scatter\", mode = \"lines+markers\", \r\n x = as.ordered(indices), y = partial_sum, yaxis = \"y\", \r\n name = \"Cauchy Partial Sum s_k\", hoverlabel = list(namelength = -1), \r\n color = color_palette[length(r_PTS) + 2] )\r\np <- plotly::add_trace(\r\n p, type = \"scatter\", mode = \"lines+markers\", \r\n x = as.ordered(indices), y = cesaro_mean, yaxis = \"y\", \r\n name = \"Cesaro Partial Mean sigma_k\", hoverlabel = list(namelength = -1), \r\n color = color_palette[length(r_PTS) + 3] )\r\n\r\np <- plotly::layout(\r\n p, hovermode = \"compare\", legend = list(orientation = \"h\", yanchor = \"top\"), \r\n barmode = \"overlay\", # bargap = 0, \r\n yaxis = list(title = \"Value\", side = \"left\", automargin = TRUE, \r\n showgrid = TRUE, zeroline = FALSE, overlaying = \"y2\"), \r\n yaxis2 = list(title = \"Abel Weight\", side = \"right\", automargin = TRUE, tickformat = \".2%\", \r\n showgrid = FALSE, zeroline = FALSE), \r\n xaxis = list(title = \"Index\", dtick = \"L1\", \r\n showgrid = TRUE, automargin = TRUE)\r\n)\r\n\r\np\r\n", "meta": {"hexsha": "2d216dca5add189c7b609e3dca60d75b63465693", "size": 3695, "ext": "r", "lang": "R", "max_stars_repo_path": "sum-divergent-series/plot_sums.r", "max_stars_repo_name": "Haoen-Cui/talks", "max_stars_repo_head_hexsha": "133d85d70cd467e5a0df19cc5bec2454e9388898", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sum-divergent-series/plot_sums.r", "max_issues_repo_name": "Haoen-Cui/talks", "max_issues_repo_head_hexsha": "133d85d70cd467e5a0df19cc5bec2454e9388898", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sum-divergent-series/plot_sums.r", "max_forks_repo_name": "Haoen-Cui/talks", "max_forks_repo_head_hexsha": "133d85d70cd467e5a0df19cc5bec2454e9388898", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2254901961, "max_line_length": 95, "alphanum_fraction": 0.5596752368, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7138866782271053}} {"text": "euclidean <- function(a, b) {\n return (sqrt(sum((a - b) ^ 2)))\n}\n\nkNN <- function(dset, labels, point, k, dist = euclidean) {\n distance <- array(dim=dim(dset)[1])\n for (j in 1:dim(dset)[1]) {\n distance[j] <- dist(dset[j,], point)\n }\n sortedDataset <- dset[order(distance),]\n sortedLabels <- labels[order(distance)]\n \n classScores <- array(0L, dim = length(unique(labels)))\n names(classScores) = unique(labels)\n for (j in 1:k) {\n classScores[sortedLabels[j]] <- classScores[sortedLabels[j]] + 1\n }\n classScores <- classScores / k\n \n return (classScores)\n}\n\ngaussKernel <- function(dist, h) exp(sqrt(h / pi * 0.5) * -0.5 * (dist * h) ^ 2)\n\nparzen <- function(dset, labels, point, h, kernel, dist = euclidean) {\n dsetLength <- length(dset[,1])\n distances <- array(dim = c(dsetLength))\n \n uLabels <- unique(labels)\n classScores <- array(0L, dim = c(length(uLabels)))\n names(classScores) = uLabels;\n # classScores[\"undefined\"] <- 0.000001\n \n for (i in 1:dsetLength) {\n classScores[labels[i]] <- classScores[labels[i]] + kernel(dist(point, dset[i,]), h)\n }\n \n return(classScores)\n}\n\ncomputeMargins <- function(dset, labels) {\n dsetLen <- dim(dset)[1]\n margins <- array(0L, dim = dsetLen)\n for (i in 1:dsetLen) {\n cat(\"\\rProcessing\", i, \"of\", dsetLen)\n # classScores <- kNN(dset[-i,], labels[-i], dset[i,], 6)\n classScores <- parzen(dset[-i,], labels[-i], dset[i,], 1.6, gaussKernel)\n # cat(paste(labels[i]), names(classScores[which.max(classScores)]), \"\\n\")\n \n margins[i] <- classScores[labels[i]] - max(classScores[-as.integer(labels[i])])\n \n if (paste(labels[i]) != names(classScores[which.max(classScores)])) {\n #cat(classScores, labels[i], classScores[labels[i]], max(classScores[-which.max(classScores)]), classScores[-labels[i]], margins[i], \"\\n\")\n }\n }\n cat(\"\\n\")\n\n return (margins)\n}\n\n# tt <- kNN(iris[3:4], iris$Species, c(2.5, 1.1), 6)\n# tt <- parzen(iris[3:4], iris$Species, c(2.5, 1.1), 1.6, kernel = gaussKernel)\n\nmargins <- computeMargins(iris[3:4], iris$Species)\n\nmargins <- margins / max(abs(margins))\ncolors <- array(dim = length(margins))\n\nfor (i in 1:length(margins)) {\n colors[i] <- if (margins[i] > 0) rgb(1 - margins[i], 1, 0) else rgb(1, 1 - abs(margins[i]), 0)\n}\n\npar(mfcol = c(1,1))\nplot(iris[,3], iris[,4], col = colors, pch = 16)\n\n\n# 1 => rgb(0, 1, 0)\n# 0.5 => rgb()\n# 0 => rgb(1, 1, 0)\n# -1 => rgb(1, 0, 0)\n\n", "meta": {"hexsha": "5a52894d0da2326689aa908909094356eae9aba9", "size": 2404, "ext": "r", "lang": "R", "max_stars_repo_path": "4 - Selection of reference objects/margin-plot.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4 - Selection of reference objects/margin-plot.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4 - Selection of reference objects/margin-plot.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3170731707, "max_line_length": 144, "alphanum_fraction": 0.6098169717, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7138576339032623}} {"text": "=begin\n[(())] \n(())\n/\n(())\n/\n(())\n/\n(())\n\n= Polynomial\n((*(Class of Polynomial Ring)*))\n\nThis class expresses the polynomial ring over arbitrary ring.\nFor creating the actual class, use the class method ((<::create>))\nor (()), giving the coefficient ring.\n\n== File Name:\n* ((|polynomial.rb|))\n\n== SuperClass:\n\n* ((|Object|))\n\n== Included Modules\n\n* ((|Enumerable|))\n* ((|Comparable|))\n* (())\n#* (())\n\n== Associated Functions:\n\n--- Algebra.Polynomial(ring [, obj0 , obj1 [, ...]])\n Same as ((<::create>))(ring, obj0[, obj1 [, ...]]).\n\n== Class Methods:\n\n--- ::create(ring, obj0[, obj1[, ...]])\n Creates a polynomial ring class over the coefficient ring\n expressed by the class: ((|ring|)).\n \n The objects designated in (({obj0, obj1, ...})) express the variables,\n and the polynomial ring on the polynomial ring is recursively created, \n if this is multiple.\n\n The value of this method is the subclass of Polynomial class.\n This subclass has the class methods: ((|ground|)), ((|var|)), \n and ((|vars|)), which return the coefficient ring ((|ring|)), \n the primary variable object(the latest one) and all variables, \n respectively.\n\n The objects (({obj0, obj1, ...})) are to utilize for the name\n (the value of ((|to_s|)) ) of the variable.\n \n Example: Polynomial ring over Integer\n require \"polynomial\"\n P = Algebra::Polynomial.create(Integer, \"x\")\n x = P.var\n p((x + 1)**100) #=> x^100 + 100x^99 + ... + 100x + 1\n p P.ground #=> integer\n\n\n Example: Multi variate Polynomial ring over Integer\n require \"polynomial\"\n P = Algebra::Polynomial.create(Integer, \"x\", \"y\", \"z\")\n x, y, z = P.vars\n p((-x + y + z)*(x + y - z)*(x - y + z))\n #=> -z^3 + (y + x)z^2 + (y^2 - 2xy + x^2)z - y^3 + xy^2 + x^2y - x^3\n p P.var #=> z\n \n This (({P})) is equal to\n\n Algebra::Polynomial.create(\n Algebra::Polynomial.create(\n Algebra::Polynomial.create(\n Integer,\n \"x\"),\n \"y\"),\n \"z\")\n\n and the last variable ((|z|)) is the primary variable.\n\n--- ::var\n Returns the (primary) variable of the polynomial ring.\n\n--- ::vars\n Returns the array of the variables of the polynomial rings, \n collecting recursively.\n\n--- ::mvar\n Same as ((<::vars>)).\n\n--- ::to_ary\n Returns (({[self, *vars]})).\n\n Example: Define Polynomial ring and variables simulteniously\n P, x, y, z = Algebra::Polynomial.create(Integer, \"x\", \"y\", \"z\")\n\n--- ::variable\n Returns the object which expresses the (primary) variable of \n the polynomial ring.\n\n--- ::variables\n Returns the array of the objects which express the variables of \n the polynomial rings, collecting recursively.\n\n--- ::indeterminate(obj)\n Returns the variable expressed by ((|obj|)).\n\n--- ::monomial([n])\n Returns the monomial of degree ((|n|)).\n \n Example:\n P = Polynomial(Integer, \"x\")\n P.monomial(3) #=> x^3\n\n--- ::const(c)\n Returns the constant value ((|c|)).\n\n Example:\n P = Polynomial(Integer, \"x\")\n P.const(3) #=> 3\n P.const(3).type #=> P\n\n--- ::zero\n Returns the zero.\n \n--- ::unity\n Returns the unity.\n\n#--- ::euclidian?\n\n== Methods:\n\n--- var\n Same as ((<::var>)).\n\n--- variable\n Same as ((<::variable>)).\n\n--- each(&b)\n Iterates of coefficients in the ascendant power series.\n \n Example:\n P = Polynomial(Integer, \"x\")\n x = P.var\n (x**3 + 2*x**2 + 4).each do |c|\n p c #=> 4, 0, 2, 1\n end\n\n--- reverse_each(&b)\n Iterates of coefficients in the descendent power series.\n\n Example:\n P = Polynomial(Integer, \"x\")\n x = P.var\n (x**3 + 2*x**2 + 4).reverse_each do |c|\n p c #=> 1, 2, 0, 4\n end\n\n--- [](n)\n Returns the coefficient of degree ((|n|)).\n\n--- []=(n, v)\n Sets the coefficient of degree ((|n|)) into ((|v|)).\n\n--- monomial\n Same as ((<::monomial>)).\n\n--- monomial?\n Returns true if self is a monomial.\n\n--- zero?\n Returns true if self is the zero.\n\n--- zero\n Returns the zero.\n \n--- unity\n Returns the unity.\n\n#--- variable=(bf)\n#--- size\n#--- compact!\n#--- ground_div(n, d)\n\n--- ==(other)\n Returns true if ((|self|)) is equal to ((|other|)).\n\n--- <=>(other)\n Returns positive if ((|self|)) is greater than ((|other|)).\n\n--- +(other)\n Returns the sum of ((|self|)) and ((|other|)).\n\n--- -(other)\n Returns the difference of ((|self|)) from ((|other|)).\n\n--- *(other)\n Returns the product of ((|self|)) and ((|other|)).\n\n--- **(n)\n Returns the ((|n|))-th power of ((|self|)).\n\n--- /(other)\n Returns the quotient of ((|self|)) by ((|other|)).\n Same as ((
)).\n\n--- divmod(other)\n Returns the array [quotient, remainder] by ((|other|)).\n\n--- div(other)\n Returns the quotient of ((|self|)) by ((|other|)).\n Same as (({divmod(other).first})).\n\n--- %(other)\n Returns the remainder of ((|self|)) by ((|other|)).\n Same as (({divmod(other).last})).\n\n--- divide?(other)\n Returns true if ((|self|)) is divisible by ((|other|)).\n Same as (({divmod(other).last == zero?})).\n\n--- deg\n Returns the degree.\n\n Example:\n P = Polynomial(Integer, \"x\")\n x = P.var\n (5*x**3 + 2*x + 1).deg #=> 3\n\n--- lc\n Returns the leading coefficient.\n\n Example:\n (5*x**3 + 2*x + 1).lc #=> 5\n\n--- lm\n Returns the leading monomial.\n\n Example:\n (5*x**3 + 2*x + 1).lm #=> x**3\n\n--- lt\n Returns the leading term).\n Same as (({lc * lm})).\n\n Example:\n (5*x**3 + 2*x + 1).lt #=> 5*x**3\n\n--- rt\n Returns the rest term, which has the same value as (({self - lt})).\n\n Example:\n (5*x**3 + 2*x + 1).rt #=> 2*x + 1\n\n--- monic\n Returns the polynomial, which corrected the maximum order coefficient in 1.\n Same as (({self / lc})) .\n\n--- cont\n Returns the content (i.e. L.C.M of coefficients).\n\n--- pp\n Returns the primitive part.\n Same as(({self / cont})).\n\n--- to_s\n Returns the expression in strings.\n Use ((|display_type|)) in order to change the display format.\n The possible value of ((|display_type|)) is \n ((|:norm|))(default) and ((|:code|)).\n \n Example:\n P = Polynomial(Integer, \"x\")\n x = P.var\n p 5*x**3 + 2*x + 1 #=>5x^3 + 2x + 1\n P.display_type = :code\n p 5*x**3 + 2*x + 1 #=> 5*x**3 + 2*x + 1\n\n--- derivate\n Return the derivative.\n \n Example:\n (5*x**3 + 2*x + 1).derivate #=> 15*x**2 + 2\n\n--- sylvester_matrix(other)\n Return the Sylvester matrix of ((|self|)) and ((|other|)).\n\n--- resultant(other)\n Return the resultant of ((|self|)) with ((|other|))\n\n--- project(ring[, obj]){|c, n| ... }\n Returns the sum of the evaluations\n of ... for each monomial of coefficient ((|c|)) and degree ((|n|)).\n If ((|obj|)) is omitted, it is assumed to be (({ring.var})).\n \n Example:\n require \"polynomial\"\n require \"rational\"\n P = Algebra::Polynomial(Integer, \"x\")\n PQ = Algebra::Polynomial(Rational, \"y\")\n x = P.var\n f = 5*x**3 + 2*x + 1\n p f.convert_to(PQ) #=> 5y^3 + 2y + 1\n p f.project(PQ) {|c, n| Rational(c) / (n + 1)} #=> 5/4y^3 + y + 1\n\n--- evaluate(obj)\n Returns the value of ((|self|)) at ((|obj|)).\n This is equivalent to (({ project(ground, obj){|c, n| c} })).\n\n Example:\n require \"polynomial\"\n P = Algebra::Polynomial(Integer, \"x\")\n x = P.var\n f = x**3 - 3*x**2 + 1\n p f.evaluate(-1) #=> -3 (in Integer)\n p f.evaluate(x + 1) #=> x^3 - 3x - 1 (in P)\n\n--- call(obj)\n Same as (()).\n\n--- sub(var, value)\n Returns the value of substitution of a variable ((|var|)) by ((|value|)).\n\n Example:\n require \"polynomial\"\n P = Algebra::Polynomial(Integer, \"x\", \"y\", \"z\")\n x, y, z = P.vars\n f = (x - y)*(y - z - 1)\n p f.sub(y, z+1) #=> 0\n\n--- convert_to(ring)\n Returns the polynomial the one converted on ((|ring|)).\n This is equivalent to (({ project(ring){|c, n| c} })).\n\n= PolynomialFactorization\n((*(Module of Factorization)*))\n\nThe module of factorization of polynomials.\n\n== File Name:\n((|polynomial-factor.rb|))\n\n== Methods:\n\n--- sqfree\n Returns the square free parts.\n\n--- sqfree?\n Returns true if square free.\n\n--- irreducible?\n Returns true if irreducible\n\n--- factorize\n Returns the factorization.\n \n The following type can be factorized:\n * Integer\n * Rational\n * prime field\n * Algebraic Field\n\n\n= Algebra::SplittingField\n((*(Module of Splitting Field)*))\n\nThe module of the minimal splitting field of polynomials.\n\n\n== File Name:\n* ((|splitting-field.rb|))\n\n== Methods:\n\n--- decompose([fac0])\n Returns\n\n [field, modulus, facts, roots, addelems]\n\n Here the elements are: \n ((|field|)) the mimimal splitting field of ((|poly|)), \n ((|def_polys|)) the irreducible polynomial needed for the splitting,\n ((|facts|)) the linear factors of ((|poly|)) over ((|field|)), \n ((|roots|)) the roots of ((|poly|)) and\n ((|proots|)) the sorted array of ((|roots|)) in order that\n the added elements to the base field first.\n\n ((|fac0|)) makes the factorization fast. (((|facts|)) and ((|fact0|))\n are the instance of ((|Algebra::Factors|))).\n Generally, ((|field|)) is the object of\n (()).\n If ((|self|)) is splitted linearlly,\n that is the (()) ring own.\n\n Example:\n require \"algebra\"\n PQ = Polynomial(Rational, \"x\")\n x = PQ.var\n f = x**5 - x**4 + 2*x - 2\n field, def_polys, facts, roots, proots = f.decompose\n p def_polys #=> [a^4 + 2, b^2 + a^2]\n p facts #=> (x - 1)(x - a)(x + a)(x - b)(x + b)\n p roots #=> [1, a, -a, b, -b]\n p proots #=> [a, b, 1, -a, -b]\n fp = Polynomial(field, \"x\")\n x = fp.var\n facts1 = Factors.new(facts.collect{|g, n| [g.call(x), n]})\n p facts1.pi == f.convert_to(fp) #=> true\n\n--- splitting_field([fac0]))\n Returns the infomation of the splitting field of ((|self|)).\n Each field corresponds to the return value of (()):\n\n poly, field, roots, proots, def_polys\n\n The values of ((|roots|)) and ((|proots|)) are transrated in\n the elements of ((|fields|)).\n\n Example:\n require \"algebra\"\n PQ = Polynomial(Rational, \"x\")\n x = PQ.var\n f = x**5 - x**4 + 2*x - 2\n sf = f.splitting_field\n p sf.roots #=> [1, a, -a, b, -b]\n p sf.proots #=> [a, b, 1, -a, -b]\n p sf.def_polys #=> [a^4 + 2, b^2 + a^2]\n\n= Algebra::Galois\n((*(Module of Galois Group)*))\n\nThe module of Galois Group of polynomials\n\n== File Name:\n* ((|galois-group.rb|))\n\n== Included Module:\n(none)\n\n== Associated Method\n\n--- GaloisGroup.galois_group(poly)\n Same as (()).\n\n== Method:\n\n--- galois_group\n Retuns the galois group of ((|self|)).\n Each elements of this is the object of\n (()) of which elements are\n in (()).\n\n Example:\n require \"rational\"\n require \"polynomial\"\n\n P = Algebra.Polynomial(Rational, \"x\")\n x = P.var\n p( (x**3 - 3*x + 1).galois_group.to_a )\n #=>[[0, 1, 2], [1, 2, 0], [2, 0, 1]]\n\n (x**3 - x + 1).galois_group.each do |g|\n p g\n end\n #=> [0, 1, 2]\n # [1, 0, 2]\n # [2, 0, 1]\n # [0, 2, 1]\n # [1, 2, 0]\n # [2, 1, 0]\n\n=end\n", "meta": {"hexsha": "5bbb6d0d32c8fa08a04bf1006db92ffd698bc1a1", "size": 11545, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc/polynomial.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/polynomial.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/polynomial.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2542016807, "max_line_length": 79, "alphanum_fraction": 0.5564313556, "num_tokens": 3548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7137760284275104}} {"text": "\r\n\r\n# Goals: Do bootstrap inference, as an example, for a sample median.\r\n\r\nlibrary(boot)\r\n\r\nsamplemedian <- function(x, d) { # d is a vector of integer indexes\r\n return(median(x[d])) # The genius is in the x[d] notation\r\n}\r\n\r\ndata <- rnorm(50) # Generate a dataset with 50 obs\r\nb <- boot(data, samplemedian, R=2000) # 2000 bootstrap replications\r\ncat(\"Sample median has a sigma of \", sd(b$t[,1]), \"\\n\")\r\nplot(b)\r\n\r\n# Make a 99% confidence interval\r\nboot.ci(b, conf=0.99, type=\"basic\")\r\n\r\n", "meta": {"hexsha": "8817e42cdcef0d5463e171478910f41f297e24c5", "size": 544, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p2.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p2.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p2.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6315789474, "max_line_length": 77, "alphanum_fraction": 0.59375, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7134932215471659}} {"text": "probability_light=0.50\r\nprobability_medium=0.30\r\nprobability_heavy=0.20\r\n# probability that member is light , medium and heavy and no books borrow\r\nprobability_0_light=0.60\r\nprobability_0_medium=0.15\r\nprobability_0_heavy=0.05\r\n# the probability that the member is a light purchaser and purchases no books in 3 months\r\np=(probability_light*probability_0_light)/((probability_light*probability_0_light)+(probability_medium*probability_0_medium)+(probability_heavy*probability_0_heavy))\r\nprint(p)", "meta": {"hexsha": "4db2951441570a41a5f502a693cebe054a6c015c", "size": 495, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.3/Ex4_3.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.3/Ex4_3.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.3/Ex4_3.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 49.5, "max_line_length": 166, "alphanum_fraction": 0.8303030303, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993889, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.7132949593581257}} {"text": "pbenford <- function(d){\n return(log10(1+(1/d)))\n}\n\nget_lead_digit <- function(number){\n return(as.numeric(substr(number,1,1)))\n}\n\nfib_iter <- function(n){\n first <- 1\n second <- 0\n for(i in 1:n){\n sum <- first + second\n first <- second\n second <- sum\n }\n return(sum)\n}\n\nfib_sequence <- mapply(fib_iter,c(1:1000))\nlead_digits <- mapply(get_lead_digit,fib_sequence)\n\nobserved_frequencies <- table(lead_digits)/1000\nexpected_frequencies <- mapply(pbenford,c(1:9))\n\ndata <- data.frame(observed_frequencies,expected_frequencies)\ncolnames(data) <- c(\"digit\",\"obs.frequency\",\"exp.frequency\")\ndev_percentage <- abs((data$obs.frequency-data$exp.frequency)*100)\ndata <- data.frame(data,dev_percentage)\n\nprint(data)\n", "meta": {"hexsha": "ac15f628c1c2fa8d41f4fd2c7072f94b0803a266", "size": 722, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Benfords-law/R/benfords-law.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Benfords-law/R/benfords-law.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Benfords-law/R/benfords-law.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 22.5625, "max_line_length": 66, "alphanum_fraction": 0.703601108, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7132283750969627}} {"text": "## Author: Sergio García Prado\n## Title: Exercises with Solutions 4\n\nrm(list = ls())\n\nQ <- matrix(c(-4/10, 4/10, 0, 0, 0,\n 1/2, -4/5, 3/10, 0, 0,\n 0, 3/4, -19/20, 2/10, 0,\n 0, 0, 1, -11/10, 1/10,\n 0 , 0, 0, 1, -1),\n 5, 5, byrow = TRUE)\n\n\nA <- cbind(Q[, 1:(nrow(Q) - 1)], rep(1, nrow(Q)))\n\n## Should be solved via detailed balance equations...\n(stationary <- solve(A)[nrow(Q), ])\n# 0.456537618699781 0.365230094959825 0.14609203798393 0.029218407596786 0.00292184075967864\n\n(machines.mean <- sum(4:0 * stationary))\n# 3.24324324324324\n\n(all.busy.ratio <- sum(stationary[3] / 2, stationary[4:5]))\n# 0.10518626734843\n", "meta": {"hexsha": "f0fd8d9a4fd359e83d1caea444683c814dc03cf7", "size": 744, "ext": "r", "lang": "R", "max_stars_repo_path": "stochastic-processes/proposed-exercises/continuous-4.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "stochastic-processes/proposed-exercises/continuous-4.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "stochastic-processes/proposed-exercises/continuous-4.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.76, "max_line_length": 92, "alphanum_fraction": 0.5161290323, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.7132167706386954}} {"text": "#autor: Joao Sollari Lopes\n#local: INE, Lisboa\n#Rversion: 3.6.1\n#criado: 17.10.2019\n#modificado: 05.11.2019\n\nsetwd(\"2019/2019.08.13_formacao_RCD2019/bin/\")\nlibrary(\"tidyverse\")\nlibrary(\"modelr\")\n\n## 1. Modelling example\nlibrary(\"hexbin\")\n\n#diamonds data\n?diamonds\n\nfnam <- \"../results/modelling/diamonds1.tiff\"\ntiff(file=fnam,units=\"in\",width=3,height=3,res=300,compression=\"lzw\")\ndiamonds %>%\n ggplot() +\n geom_boxplot(aes(cut,price))\ndev.off()\n\nfnam <- \"../results/modelling/diamonds2.tiff\"\ntiff(file=fnam,units=\"in\",width=3,height=3,res=300,compression=\"lzw\")\ndiamonds %>%\n ggplot() +\n geom_boxplot(aes(clarity,price))\ndev.off()\n\nfnam <- \"../results/modelling/diamonds3.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=3,res=300,compression=\"lzw\")\ndiamonds %>%\n ggplot() +\n geom_hex(aes(carat,price),bins=50)\ndev.off()\n\ndiamonds2 <- diamonds %>%\n filter((x > 0) & (y > 0 & y < 20) & (z > 0 & z < 10)) %>%\n filter(carat <= 2.5) %>%\n select(carat,cut,color,clarity,price) %>%\n mutate(lprice = log(price), lcarat = log(carat))\n\nfnam <- \"../results/modelling/diamonds4.tiff\"\ntiff(file=fnam,units=\"in\",width=5,height=4,res=300,compression=\"lzw\")\ndiamonds2 %>%\n ggplot() +\n geom_hex(aes(lcarat,lprice),bins=50)\ndev.off()\n\n#model 1\ndiamonds_mod <- lm(lprice ~ lcarat,data=diamonds2)\nsummary(diamonds_mod)\n\ndiamonds2 <- diamonds2 %>%\n add_predictions(diamonds_mod,\"lpred\") %>%\n add_residuals(diamonds_mod,\"lresid\") %>%\n mutate(pred = exp(lpred))\n\nfnam <- \"../results/modelling/diamonds5.tiff\"\ntiff(file=fnam,units=\"in\",width=5,height=4,res=300,compression=\"lzw\")\ndiamonds2 %>%\n ggplot() +\n geom_hex(aes(carat,price),bins=50) +\n geom_line(aes(carat,pred),color=\"red\")\ndev.off()\n\nfnam <- \"../results/modelling/diamonds6.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\ndiamonds2 %>%\n ggplot() +\n geom_boxplot(aes(cut,lresid))\ndev.off()\n\nfnam <- \"../results/modelling/diamonds7.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\ndiamonds2 %>%\n ggplot() +\n geom_boxplot(aes(clarity,lresid))\ndev.off()\n\nfnam <- \"../results/modelling/diamonds8.tiff\"\ntiff(file=fnam,units=\"in\",width=5,height=4,res=300,compression=\"lzw\")\ndiamonds2 %>%\n ggplot() +\n geom_hex(aes(lcarat,lresid),bins=50)\ndev.off()\n\nfnam <- \"../results/modelling/diamonds9.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\ndiamonds2 %>%\n ggplot() +\n geom_point(aes(pred,price)) +\n geom_abline(aes(intercept=0,slope=1),size=1,color=\"white\")\ndev.off()\n\n#model 2\ndiamonds_mod2 <- lm(lprice ~ lcarat + clarity + cut,data=diamonds2)\nsummary(diamonds_mod2)\n\ndiamonds2 <- diamonds2 %>%\n add_predictions(diamonds_mod2,\"lpred2\") %>%\n add_residuals(diamonds_mod2,\"lresid2\") %>%\n mutate(pred2 = exp(lpred2))\n\nfnam <- \"../results/modelling/diamonds10.tiff\"\ntiff(file=fnam,units=\"in\",width=9,height=4.5,res=300,compression=\"lzw\")\ndiamonds2 %>%\n ggplot() +\n geom_hex(aes(carat,price),bins=50) +\n geom_line(aes(carat,pred2),color=\"red\") +\n facet_grid(cut ~ clarity)\ndev.off()\n\nfnam <- \"../results/modelling/diamonds11.tiff\"\ntiff(file=fnam,units=\"in\",width=5,height=4,res=300,compression=\"lzw\")\ndiamonds2 %>%\n ggplot() +\n geom_hex(aes(lcarat,lresid2),bins=50)\ndev.off()\n\nfnam <- \"../results/modelling/diamonds12.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\ndiamonds2 %>%\n ggplot() +\n geom_point(aes(pred2,price)) +\n geom_abline(aes(intercept=0,slope=1),size=1,color=\"white\")\ndev.off()\n \n## 2. Model Fitting\nset.seed(12345)\n\n#synthetic data\nreal_a1 <- 4.22\nreal_a2 <- 2.05\nx <- round(runif(n=30,min=0,max=10),digits=2)\ny <- real_a1*x + real_a2 + rnorm(n=30,mean=0,sd=1)\nsim1 <- tibble(x,y)\n\n#plot synthetic data\nfnam <- \"../results/modelling/synthetic1.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\nsim1 %>%\n ggplot() +\n geom_point(aes(x,y))\ndev.off()\n\n#### 2.1. fit model (random search)\nmodels <- tibble(\n a1 = runif(250,-20,40),\n a2 = runif(250,-5,5))\n\nfnam <- \"../results/modelling/synthetic2.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\nsim1 %>%\n ggplot() +\n geom_abline(data=models,aes(intercept=a1,slope=a2),alpha=0.24) + \n geom_point(aes(x,y))\ndev.off()\n\n#Linear regression model\nmodel1 <- function(a,dat){\n res <- a[1] + dat$x*a[2]\n return(res)\n}\n\n#Calculate Root-mean-squared-deviation\nmeasure_distance <- function(params,dat){\n diff <- dat$y - model1(params,dat)\n res <- sqrt(mean(diff^2))\n return(res)\n}\n\n#Helper function to calculate RMSD for synthetic data \"sim1\"\nsim1_dist <- function(a1,a2){\n res <- measure_distance(c(a1,a2),dat=sim1)\n return(res)\n}\n\nmodels <- models %>%\n mutate(RMSD = map2_dbl(a1,a2,sim1_dist))\nprint(models)\n\nbest_models <- models %>%\n filter(rank(RMSD) <= 10)\n \nfnam <- \"../results/modelling/synthetic3.tiff\"\ntiff(file=fnam,units=\"in\",width=5,height=4,res=300,compression=\"lzw\")\nsim1 %>%\n ggplot() +\n geom_point(aes(x,y),size=2,color=\"grey30\") +\n geom_abline(data=best_models,aes(intercept=a1,slope=a2,color=-RMSD))\ndev.off()\n\nfnam <- \"../results/modelling/synthetic4.tiff\"\ntiff(file=fnam,units=\"in\",width=5,height=4,res=300,compression=\"lzw\")\nmodels %>%\n ggplot() +\n geom_point(data=best_models,aes(a1,a2),size=4,color=\"red\") +\n geom_point(aes(a1,a2,color=-RMSD))\ndev.off()\n\n#### 2.2. fit model (grid search)\nmodels_grid <- expand.grid(\n a1 = seq(0,15,length=25),\n a2 = seq(2,5,length=25)) %>%\n mutate(RMSD=map2_dbl(a1,a2,sim1_dist))\nhead(models_grid,n=15)\n\nbest_grid <- models_grid %>%\n filter(rank(RMSD) <= 10)\n\nfnam <- \"../results/modelling/synthetic5.tiff\"\ntiff(file=fnam,units=\"in\",width=5,height=4,res=300,compression=\"lzw\")\nsim1 %>%\n ggplot() + \n geom_point(aes(x,y),size=2,color=\"grey30\") +\n geom_abline(data=best_grid,aes(intercept=a1,slope=a2,color=-RMSD))\ndev.off()\n\nfnam <- \"../results/modelling/synthetic6.tiff\"\ntiff(file=fnam,units=\"in\",width=5,height=4,res=300,compression=\"lzw\")\nmodels_grid %>%\n ggplot() +\n geom_point(data=best_grid,aes(a1,a2),size=4,color=\"red\") +\n geom_point(aes(a1,a2,color=-RMSD))\ndev.off()\n\n#### 2.3. fit model (Newton-Raphson optimization)\nbest_optim <- optim(c(0,0),measure_distance,dat=sim1) \nbest_a1 <- best_optim$par[1]\nbest_a2 <- best_optim$par[2]\n\nfnam <- \"../results/modelling/synthetic7.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\nsim1 %>%\n ggplot() + \n geom_point(aes(x,y),size=2,color=\"grey30\") +\n geom_abline(aes(intercept=best_a1,slope=best_a2))\ndev.off()\n\n#### 2.4. fit model (Least-Squares method)\nbest_lm <- lm(y ~ x,data=sim1)\nbest_a1 <- best_lm$coef[1]\nbest_a2 <- best_lm$coef[2]\n\nfnam <- \"../results/modelling/synthetic8.tiff\"\ntiff(file=fnam,units=\"in\",width=4,height=4,res=300,compression=\"lzw\")\nsim1 %>%\n ggplot() + \n geom_point(aes(x,y),size=2,color=\"grey30\") +\n geom_abline(aes(intercept=best_a1,slope=best_a2))\ndev.off()\n\n#### 2.5. summary\nres1 <- models %>%\n filter(rank(RMSD) == 1)\n\nres2 <- models_grid %>%\n filter(rank(RMSD) == 1)\n\nres3 <- tibble(\n a1 = best_optim$par[1],\n a2 = best_optim$par[2],\n RMSD = best_optim$value)\n\nres4 <- tibble(\n a1 = best_lm$coef[1],\n a2 = best_lm$coef[2],\n RMSD = sqrt(mean(best_lm$residuals^2)))\n\ntab1 = round(data.frame(rbind(res1,res2,res3,res4)),digits=2)\nrownames(tab1) = c(\"random\",\"grid\",\"NR\",\"LS\")\nfnam = \"../results/modelling/fitting1.txt\"\nwrite.table(tab1,fnam,sep=\",\",row.names=TRUE,col.names=NA)\n\n## 3. Model Diagnostic\nset.seed(12345)\n\n#synthetic data\nreal_a1 <- 4.22\nreal_a2 <- 2.05\nx <- round(runif(n=30,min=0,max=10),digits=2)\ny <- real_a1*x + real_a2 + rnorm(n=30,mean=0,sd=1)\nsim1 <- tibble(x,y)\n\n#fit model\nsim1_mod <- lm(y ~ x,data=sim1)\n\nsim1 <- sim1 %>%\n add_predictions(sim1_mod) %>%\n add_residuals(sim1_mod)\nprint(sim1)\n\n#scatterplot y~x \nfnam <- \"../results/modelling/visualization1.tiff\"\ntiff(file=fnam,units=\"in\",width=3,height=2.4,res=300,compression=\"lzw\")\nsim1 %>% \n ggplot() + \n geom_point(aes(x,y),size=2,color=\"grey30\") +\n geom_line(aes(x,pred)) +\n\tgeom_segment(aes(x=x,xend=x,y=y,yend=pred),alpha=0.2)\ndev.off()\n\n#scatterplot y~pred\nfnam <- \"../results/modelling/visualization2.tiff\"\ntiff(file=fnam,units=\"in\",width=3,height=2.4,res=300,compression=\"lzw\")\nsim1 %>% \n ggplot() + \n geom_abline(aes(intercept=0,slope=1),size=2,color=\"white\") +\n geom_point(aes(pred,y),size=2,color=\"grey30\")\ndev.off()\n\n#density(residuals)\nfnam <- \"../results/modelling/visualization3.tiff\"\ntiff(file=fnam,units=\"in\",width=3,height=2.4,res=300,compression=\"lzw\")\nsim1 %>% \n ggplot() + \n geom_density(aes(resid)) +\n stat_function(fun=dnorm,color=\"red\",args=list(mean=0,sd=1))\ndev.off()\n\n#scatterplot res~x\nfnam <- \"../results/modelling/visualization4.tiff\"\ntiff(file=fnam,units=\"in\",width=3,height=2.4,res=300,compression=\"lzw\")\nsim1 %>% \n ggplot() + \n geom_hline(aes(yintercept=0),size=2,color=\"white\") +\n geom_point(aes(x,resid))\ndev.off()\n\n#qqplot(residuals)\nfnam <- \"../results/modelling/visualization5.tiff\"\ntiff(file=fnam,units=\"in\",width=3,height=2.4,res=300,compression=\"lzw\")\nsim1 %>% \n ggplot() + \n geom_qq_line(aes(sample=resid),size=2,color=\"white\") + \n geom_qq(aes(sample=resid)) + \n labs(x=\"Theoretical Quantiles\",y=\"Sample Quantiles\") \ndev.off()\n\n#lagplot(residuals) \nfnam <- \"../results/modelling/visualization6.tiff\"\ntiff(file=fnam,units=\"in\",width=3,height=2.4,res=300,compression=\"lzw\")\nsim1 %>% \n ggplot() + \n geom_point(aes(c(resid[-1],NA),resid)) +\n labs(x=expression(resid[i-1]),y=expression(resid[i]))\ndev.off()\n", "meta": {"hexsha": "ac0e2528ead70fb8d5c13775471d2883c962750e", "size": 9533, "ext": "r", "lang": "R", "max_stars_repo_path": "bin/modelling.r", "max_stars_repo_name": "jsollari/RCD2019", "max_stars_repo_head_hexsha": "2de30ecc5684d3ae14d8f2ae1023e8a407f6eb66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/modelling.r", "max_issues_repo_name": "jsollari/RCD2019", "max_issues_repo_head_hexsha": "2de30ecc5684d3ae14d8f2ae1023e8a407f6eb66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/modelling.r", "max_forks_repo_name": "jsollari/RCD2019", "max_forks_repo_head_hexsha": "2de30ecc5684d3ae14d8f2ae1023e8a407f6eb66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2371428571, "max_line_length": 72, "alphanum_fraction": 0.6781705654, "num_tokens": 3346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7132089626421135}} {"text": "############################################\n# Part v\np = 0.1\nrho = 0.5\nn = 200\n\n\n# function to generate one dataset\n# following Qaqish (2003) algorithm\ngendataAR1 = function(n,p,rho){\n dat = c(rbinom(1,1,p),rep(NA,n-1))\n for(i in 2:n){\n j = i-1\n prob = p + rho*(dat[j]-p)\n dat[i] = rbinom(1,1,prob)\n }\n return(dat)\n}\n\n# Generate 100 replicates\nx = matrix(NA,100,n)\nfor(r in 1:100){\n x[r,]=gendataAR1(n,p,rho)\n}\n\nwrite(t(x),\"p.10_ar50_n200_r100.txt\",ncol=n) # each row in this file is a different simulated song\n\n\n#############################################\n# Part vi\np = 0.1\nrho = 0.5\nn = 600\n\n# function to generate one dataset\n# following Qaqish (2003) algorithm\ngendataAR1 = function(n,p,rho){\n dat = c(rbinom(1,1,p),rep(NA,n-1))\n for(i in 2:n){\n j = i-1\n prob = p + rho*(dat[j]-p)\n dat[i] = rbinom(1,1,prob)\n }\n return(dat)\n}\n\n# Generate 100 replicates\nx = matrix(NA,100,n)\nfor(r in 1:100){\n x[r,]=gendataAR1(n,p,rho)\n}\n\nwrite(t(x),\"p.10_ar50_n600_r100.txt\",ncol=n) # each row in this file is a different simulated song\n\n#############################################\n# Part vii\np = 0.1\nrho = 0.3\nn = 200\n\n# function to generate one dataset\n# following Qaqish (2003) algorithm\ngendataAR1 = function(n,p,rho){\n dat = c(rbinom(1,1,p),rep(NA,n-1))\n for(i in 2:n){\n j = i-1\n prob = p + rho*(dat[j]-p)\n dat[i] = rbinom(1,1,prob)\n }\n return(dat)\n}\n\n# Generate 100 replicates\nx = matrix(NA,100,n)\nfor(r in 1:100){\n x[r,]=gendataAR1(n,p,rho)\n}\n\nwrite(t(x),\"p.10_ar30_n200_r100.txt\",ncol=n) # each row in this file is a different simulated song\n\n#############################################\n# Part viii\np = 0.1\nrho = 0.3\nn = 600\n\n# function to generate one dataset\n# following Qaqish (2003) algorithm\ngendataAR1 = function(n,p,rho){\n dat = c(rbinom(1,1,p),rep(NA,n-1))\n for(i in 2:n){\n j = i-1\n prob = p + rho*(dat[j]-p)\n dat[i] = rbinom(1,1,prob)\n }\n return(dat)\n}\n\n# Generate 100 replicates\nx = matrix(NA,100,n)\nfor(r in 1:100){\n x[r,]=gendataAR1(n,p,rho)\n}\n\nwrite(t(x),\"p.10_ar30_n600_r100.txt\",ncol=n) # each row in this file is a different simulated song\n\n#############################################\n# Part ix\np = 0.2\nrho = 0.5\nn = 200\n\n# function to generate one dataset\n# following Qaqish (2003) algorithm\ngendataAR1 = function(n,p,rho){\n dat = c(rbinom(1,1,p),rep(NA,n-1))\n for(i in 2:n){\n j = i-1\n prob = p + rho*(dat[j]-p)\n dat[i] = rbinom(1,1,prob)\n }\n return(dat)\n}\n\n# Generate 100 replicates\nx = matrix(NA,100,n)\nfor(r in 1:100){\n x[r,]=gendataAR1(n,p,rho)\n}\n\nwrite(t(x),\"p.20_ar50_n200_r100.txt\",ncol=n) # each row in this file is a different simulated song\n\n#############################################\n# Part x\np = 0.2\nrho = 0.5\nn = 600\n\n# function to generate one dataset\n# following Qaqish (2003) algorithm\ngendataAR1 = function(n,p,rho){\n dat = c(rbinom(1,1,p),rep(NA,n-1))\n for(i in 2:n){\n j = i-1\n prob = p + rho*(dat[j]-p)\n dat[i] = rbinom(1,1,prob)\n }\n return(dat)\n}\n\n# Generate 100 replicates\nx = matrix(NA,100,n)\nfor(r in 1:100){\n x[r,]=gendataAR1(n,p,rho)\n}\n\nwrite(t(x),\"p.20_ar50_n600_r100.txt\",ncol=n) # each row in this file is a different simulated song\n\n", "meta": {"hexsha": "61efda7c0b2ca7d2c6b9ee65c22c40d462282d40", "size": 3170, "ext": "r", "lang": "R", "max_stars_repo_path": "GHSupplementaryFiles/AppendixD/ar1.r", "max_stars_repo_name": "iramler/guitar_hero_jse", "max_stars_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GHSupplementaryFiles/AppendixD/ar1.r", "max_issues_repo_name": "iramler/guitar_hero_jse", "max_issues_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GHSupplementaryFiles/AppendixD/ar1.r", "max_forks_repo_name": "iramler/guitar_hero_jse", "max_forks_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9371069182, "max_line_length": 98, "alphanum_fraction": 0.5719242902, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.713208958379742}} {"text": "=begin\n= Algebra\n\n2006.09.14\n\n*Version: 0.72\n*Author: Shin-ichiro HARA\n*e-mail: sinara@blade.nagaokaut.ac.jp\n*Home Page: (())\n\n== Preface\n\nThis is a library for mathematical computations. \nOur purpose is to express the mathematical object naturally in Ruby.\nThough it is not operated fast, we can see the algorithm of the\nmathematical processing not in black box but in scripts.\n\nThis library is in development stage.\nAt present, things we can handle are as follows:\n\n* One-variate polynomial\n * Fundamental operations (addition, multiplication, quotient/remainder, ...)\n * factorization\n * Galois group\n* Multi-variate polynomial\n * Fundamental operations (addition, multiplication, ...)\n * factorization\n * Creating Groebner-basis, quotient/remainder by Groebner-basis.\n* Algebraic systems\n * Creating quotient fields\n * Creating residue class fields\n * Operating matrices\n * Operating permutation groups\n* Sets and Maps\n\n== Installation\n\nInstall Ruby (See: (()) ).\n\nAfter expanding this archive, do\n\n ruby install.rb\n\nThen all files and directories under ((|lib|)) are copyed in\nthe directory where Ruby can load.\n\nTo accelerate calculation, it is better to use an extension \nlibrary of rational number:\n((())\nthan to use the stardard library rational.rb.\n\n== Usage and Samples\n\nSee (()) in ((|doc|)) directory, where \nmanuals and sample codes are.\n\n== Reference\n* D.Cox, J.Little and D.O'Shea, \"IDEALS, VARIETIES AND ALGORITHMS\", 1997, Springer.\n* K. Kodama, \"Polynomial\", (())\n* H.Anai, M.Noro and K.Yokoyama, \"Computation of the splitting fields and the Galois groups of polynomials\", Progres in Mathematics, 28-50, Vo.143, 1996\n\n\n=end\n", "meta": {"hexsha": "58535e0ff7301476ab4317ad3156a1a169ebd55f", "size": 1886, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc/README.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/README.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/README.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.46875, "max_line_length": 152, "alphanum_fraction": 0.7417815483, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7132089455878179}} {"text": "compute_π <- function(trials) {\n points <- matrix(runif(2*trials), nrow=2)\n inside <- sum(colSums(points^2) <= 1.0)\n return(4.0*inside/trials)\n}\n\nargs = commandArgs(trailingOnly=TRUE)\nif(length(args) < 1) {\n error(\"must provide number of trials\")\n}\ntrials = as.integer(args[1])\nset.seed(2018)\n\nstart.time <- Sys.time()\ninvisible(compute_π(trials))\nstop.time <- Sys.time()\ncat(\"First invocation: \", stop.time - start.time, \"s\\n\")\n\nstart.time <- Sys.time()\nπ <- compute_π(trials)\nstop.time <- Sys.time()\ncat(\"Second invocation:\", stop.time - start.time, \"s\\n\")\n\ncat(\"π ≈ \", π, \"\\n\")\n", "meta": {"hexsha": "df2d8bfcfcadf711b0bc0c9f66fdde0faf87dc6d", "size": 593, "ext": "r", "lang": "R", "max_stars_repo_path": "pi/R/pi-vec.r", "max_stars_repo_name": "ELIFE-ASU/meet-julia", "max_stars_repo_head_hexsha": "4e7efe885da3b935c61d7fab5c6e7fc057077be4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-03T10:39:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-03T10:39:33.000Z", "max_issues_repo_path": "pi/R/pi-vec.r", "max_issues_repo_name": "ELIFE-ASU/meet-julia", "max_issues_repo_head_hexsha": "4e7efe885da3b935c61d7fab5c6e7fc057077be4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-11T06:03:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-11T06:14:55.000Z", "max_forks_repo_path": "pi/R/pi-vec.r", "max_forks_repo_name": "ELIFE-ASU/meet-julia", "max_forks_repo_head_hexsha": "4e7efe885da3b935c61d7fab5c6e7fc057077be4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-11T05:36:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-11T05:36:39.000Z", "avg_line_length": 23.72, "max_line_length": 56, "alphanum_fraction": 0.6492411467, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7130985128420245}} {"text": "\r\n\r\n##########################################################\r\n#### R code for adding noise to correlation matrices #### \r\n#### J. Hardin, S.R. Garcia, D. Golan ####\r\n#### last updated 1/18/2013 ####\r\n##########################################################\r\n\r\n#################\r\n## EXAMPLE ##\r\n#################\r\n\r\n\r\n# adding noise to a 15x15 identity matrix\r\n\r\nnoise.iden <- noisecor(diag(15), epsilon = .5, eidim=2)\r\n\r\n\r\n# adding noise to a 2 block constant correlation matrix\r\nrho.blck = c(.9,.2)\r\neps.blck = 0.99 - max(rho.blck)\r\nsamp.blck <- simcor(k = 2, size = c(10, 5), rho = c(0.9, 0.2), delta = 0.39, epsilon = eps.blck, eidim = 2) \r\n\r\n\r\n# adding noise to a 2 block correlation matrix with an AR(1) strucutre\r\nrho.Top = c(.7,.9)\r\neps.Top = (1-max(rho.Top))/(1+max(rho.Top)) - .01\r\nsamp.Top <- simcorTop(k=2, size=c(10,5), rho=c(.7,.9), epsilon = eps.Top, eidim=2)\r\n\r\n\r\n# adding noise to a 2 block correlation matrix with a Hub structure\r\nrho.Hub = c(.9,.7)\r\ntau.Hub = c( (.9 - .7) / (10-2), (.7-.6)/(5-2))\r\neps.Hub = min(1-(rho.Hub) - 0.75*(tau.Hub) ) - .01\r\nsamp.Hub <- simcor.H(k=2, size=c(10,5),\trho=rbind(c(.9,.7), c(.7,.6)), power=1,\r\n\tepsilon=eps.Hub, eidim=2)\r\n\r\n\r\n\r\n########################\r\n## The Basic Function ##\r\n########################\r\n\r\n# this adds noise to any user specified correlation matrix\r\n\r\nnoisecor <- function(cormat, epsilon = .01, eidim=2){\r\n\r\nndim=dim(cormat)[1]\r\ndiag(cormat) <- 1 - epsilon\r\n\r\n### adding noise to the correlation matrix\r\n\r\neivect <- c( )\r\nfor (i in 1:ndim) {\r\n\tei <- runif(eidim, -1, 1)\r\n\teivect <- cbind(eivect, sqrt(epsilon) * ei / sqrt(sum(ei^2) ) )\r\n}\r\n \r\n\r\nbigE <- t(eivect) %*% eivect\r\ncor.nz <- cormat + bigE\r\ncor.nz\r\n\r\n}\r\n\r\n\r\n#######################################\r\n## Simulating different correlation ##\r\n## structures as in Hardin et al. ##\r\n#######################################\r\n\r\n\r\n################################\r\n## Simulating the Constant Correlation\r\n################################\r\n\r\n# this function simulates a block correlation matrix\r\n# The size and base correlation for each block is user specified\r\n# There is an additional delta parameter for the off diagonal correlations\r\n\r\n\r\n# k is the number of groups\r\n# size is a vector of length k specifying the size of each group \r\n# rho is a vector of length k specifying base correlation values\r\n# epsilon <- 0.99 - max(rho)\r\n# eidim is the space from which the noise is generated, the smaller the more noise\r\n# delta is the correlation of the off diagonal blocks\r\n\r\nsimcor = function (k = 6, size = c(10, 5, 8, 2, 15, 50), rho = c(0.7, \r\n 0.7, 0.5, 0.9, 0.85, 0.4), delta = 0.39, epsilon = 0.99 - \r\n max(rho), eidim = 2) \r\n{\r\n ndim <- sum(size)\r\n bigcor <- matrix(rep(delta, ndim * ndim), ncol = ndim)\r\n for (i in 1:k) {\r\n cor <- matrix(rep(rho[i], size[i] * size[i]), ncol = size[i])\r\n if (i == 1) {bigcor[1:size[1], 1:size[1]] <- cor}\r\n if (i != 1) {bigcor[(sum(size[1:(i - 1)]) + 1):sum(size[1:i]), \r\n (sum(size[1:(i - 1)]) + 1):sum(size[1:i])] <- cor}\r\n }\r\n diag(bigcor) <- 1 - epsilon\r\n\r\n eivect <- c()\r\n for (i in 1:ndim) {\r\n ei <- runif(eidim, -1, 1)\r\n eivect <- cbind(eivect, sqrt(epsilon) * ei/sqrt(sum(ei^2)))\r\n }\r\n bigE <- t(eivect) %*% eivect\r\n cor.nz <- bigcor + bigE\r\n cor.nz\r\n}\r\n\r\n\r\n################################\r\n## Simulating the Toeplitz Matrix\r\n################################\r\n\r\n# this function calculates an AR(1) Toeplitz matrix\r\n# with a block diagonal structure. The size and base correlation for each\r\n# block is user specified\r\n\r\n\r\n# k is the number of groups\r\n# size is a vector of length k specifying the size of each group \r\n# rho is a vector of length k specifying base correlation values\r\n# epsilon <- (1-max(rho))/(1+max(rho)) - .01 \r\n# eidim is the space from which the noise is generated, the smaller the more noise\r\n\r\nsimcorTop <- function(k=6,size=c(10,5,8,2,15,50),rho=c(.7,.7,.5,.9,.85,.4),epsilon= .01, eidim=2) {\r\n\r\n\r\nndim <- sum(size)# dim of correlation matrix\r\nbigcor<- matrix(rep(0, ndim*ndim), ncol=ndim)\r\n\r\n### generating the basic correlation matrix\r\n\r\n\r\nfor (i in 1:k){\r\n\r\n\ttop <- c(1,rho[i]^(seq(1:(size[i]-1))))\r\n\tcor <- toeplitz(top)\r\n\r\n\tif (i==1){bigcor[1:size[1], 1:size[1]] <- cor}\r\n\tif (i!=1){bigcor[(sum(size[1:(i-1)]) + 1):sum(size[1:i]),\r\n\t\t(sum(size[1:(i-1)]) + 1):sum(size[1:i])] <- cor}\r\n\t}\r\n\r\ndiag(bigcor) <- 1 - epsilon\r\n\r\n\r\n### adding noise to the correlation matrix\r\n\r\neivect <- c( )\r\nfor (i in 1:ndim) {\r\n\tei <- runif(eidim, -1, 1)\r\n\teivect <- cbind(eivect, sqrt(epsilon) * ei / sqrt(sum(ei^2) ) )\r\n}\r\n \r\n\r\nbigE <- t(eivect) %*% eivect\r\ncor.nz <- bigcor + bigE\r\ncor.nz\r\n\r\n}\r\n\r\n################################\r\n## Simulating the Hub Matrix (entries filled in using Toeplitz structure)\r\n################################\r\n\r\n# this function calculates a Toeplitz matrix with values descending\r\n# from a user specified maximum to minimum. The matrix has a \r\n# block diagonal structure. The size and base correlation for each\r\n# block is user specified.\r\n\r\n\r\n# k is the number of groups\r\n# size is a vector of length k specifying the size of each group \r\n# rho is a vector of length k specifying base correlation values\r\n# epsilon <- (1-min(rho) - 0.75*min(tau) ) - .01\r\n# tau_k = (max(rho_k) - min(rho_k) )/ (size_k -2) \r\n# eidim is the space from which the noise is generated, the smaller the more noise\r\n# power = 2 makes the correlations stay high\r\n# power = 0.5 makes the correlations descent rapidly\r\n\r\n\r\nsimcor.H <- function(k=6, size=c(10,5,8,7,15,50), \r\n\trho=rbind(c(.9,.7), c(.7,.7), c(.7,.2), c(.5,.3), c(.9,.85), c(.3,.2)), power=1,\r\n\tepsilon=.08, eidim=2){\r\n\r\n\r\n\tndim <- sum(size)# dim of correlation matrix\r\n\tbigcor<- matrix(rep(0, ndim*ndim), ncol=ndim)\r\n\r\n### generating the basic correlation matrix\r\n\r\n\r\n\tfor (i in 1:(k) ){\r\n\r\n\tcor <- toeplitz(rho.func(rho[i,1],rho[i,2],power,size[i]) )\r\n\r\n\tif (i==1){bigcor[1:size[1], 1:size[1]] <- cor}\r\n\tif (i!=1){bigcor[(sum(size[1:(i-1)]) + 1):sum(size[1:i]),\r\n\t\t(sum(size[1:(i-1)]) + 1):sum(size[1:i])] <- cor}\r\n\t}\r\n\tdiag(bigcor) <- 1 - epsilon\r\n\r\n\r\n### adding noise to the correlation matrix\r\n\r\n\teivect <- c( )\r\n\tfor (i in 1:ndim) {\r\n\tei <- runif(eidim, -1, 1)\r\n\teivect <- cbind(eivect, sqrt(epsilon) * ei / sqrt(sum(ei^2) ) )\r\n\t}\r\n \r\n\r\n\tbigE <- t(eivect) %*% eivect\r\n\tcor.nz <- bigcor + bigE\r\n\tcor.nz\r\n\t}\r\n\r\n\t\r\n# rho.func is needed for filling in the rest of the structure of the Hub\r\n# correlation matrix\r\n# r.max is the maximum user specified correlation\r\n# r.min is the minimum user specified correlation\r\n# power is the power at which the correlations descend\r\n# p is the size of the correlation block\r\n\r\nrho.func <- function(r.max, r.min, power,p){\r\n\trhovec <-c()\r\n\r\n\trhovec[1] <- 1\r\n\tfor(i in 2:p){\r\n\trhovec[i] <- r.max - ((i-2)/(p-2))^power*(r.max-r.min)\r\n\t}\r\n\trhovec}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "5df9b14c8cd1555cd259840c3d2f19eaeadec553", "size": 6890, "ext": "r", "lang": "R", "max_stars_repo_path": "notebooks/simcor.r", "max_stars_repo_name": "cosanlab/multivariate_inference", "max_stars_repo_head_hexsha": "f591748e6ebd792f4192c1d04014e872af50d08d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/simcor.r", "max_issues_repo_name": "cosanlab/multivariate_inference", "max_issues_repo_head_hexsha": "f591748e6ebd792f4192c1d04014e872af50d08d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/simcor.r", "max_forks_repo_name": "cosanlab/multivariate_inference", "max_forks_repo_head_hexsha": "f591748e6ebd792f4192c1d04014e872af50d08d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5892116183, "max_line_length": 109, "alphanum_fraction": 0.5608127721, "num_tokens": 2170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7130277671871927}} {"text": "# 4. faza: Analiza podatkov\n\n# 1.regresijska premica: ŠTEVILO UMRLIH V CESTNOPROMETNIH NESREČAH NA 10.000 REGISTRIRANIH MOTORNIH VOZIL V NASLEDNJIH LETIH\n\ngrupa <- group_by(preminuli, Leto)\npreminuli_Slovenija <- summarise(grupa, Stevilo=(sum(Preminuli, na.rm = TRUE)))\npreminuli_Slovenija <- transform(preminuli_Slovenija, Stevilo = (Stevilo / 12))\npreminuli_Slovenija$Stevilo <- round(preminuli_Slovenija$Stevilo, digits=2)\nprileganje <- lm(data = preminuli_Slovenija, Stevilo ~ Leto )\nm <- data_frame(Leto=seq(2019,2023,1))\npredvidevanje <- mutate(m, Stevilo=predict(prileganje,m))\npredvidevanje$Stevilo <- round(predvidevanje$Stevilo, digits = 2)\n\ngraf_regresijska_premica_preminulih <- ggplot(preminuli_Slovenija, aes(x=Leto, y=Stevilo)) +\n geom_smooth(method=lm, fullrange = TRUE, color = 'blue') +\n geom_point(data=predvidevanje, aes(x=Leto, y=Stevilo), color='red', size=2) +\n geom_point() +\n labs(title='Predvidevanje števila smrti v prometu v naslednjih letih', y=\"Stevilo\")\n\n\n\n# 2.regresijska premica: ŠTEVILO OSEBNIH AVTOMOBILOV NA 1000 PREBIVALCEV V PRIHODNOSTI\noseb_avto <- group_by(osebni_avtomobili,Leto)\noseb_avto1 <- summarise(oseb_avto, Stevilo=sum(Osebni_avtomobili, na.rm=TRUE))\noseb_avto_regije <- transform(oseb_avto1, Stevilo = Stevilo / 12)\noseb_avto_regije$Stevilo <- round(oseb_avto_regije$Stevilo, digits=2)\nprileganje <- lm(data = oseb_avto_regije, Stevilo ~ Leto )\nn <- data_frame(Leto=seq(2020,2024,1))\npredvidevanje_oseb_avto <- mutate(n, Stevilo=predict(prileganje, n))\n\ngraf_regresijske_premice_oseb_avto <- ggplot(oseb_avto_regije, aes(x=Leto, y=Stevilo)) +\n geom_smooth(method=lm, fullrange = TRUE, color = 'blue') +\n geom_point(data=predvidevanje_oseb_avto, aes(x=Leto, y=Stevilo), color='red', size=2) +\n geom_point() +\n labs(title='Predvidevanje števila osebnih avtomobilov na 1000 prebivalcev v prometu v prihodnosti', y=\"Stevilo\")\n\n\n\n# Cluster regij: ŠTEVILO UMRLIH V CESTNOPROMETNIH NESREČAH\n\n# Preminuli\ngrup <- group_by(preminuli, Regija)\npreminuli_sum <- summarise(grup, vsote=sum(Preminuli, na.rm = TRUE))\n\npreminuli_e <- dcast(preminuli, Regija~Leto, value.var = 'Preminuli' )\npreminuli_e <- left_join(preminuli_e, preminuli_sum, by = 'Regija')\npreminuli_e <- preminuli_e[order(preminuli_e$vsote, decreasing = FALSE),]\npreminuli_b <- preminuli_e[,-19]\npreminuli_b <- preminuli_b[,-1]\n\nn <- 5\nfit <- hclust(dist(scale(preminuli_b)))\nskupine <- cutree(fit, n)\n\ncluster <- mutate(preminuli_e, skupine)\ncluster <- cluster[,-2:-19]\ncolnames(cluster) <- c(\"Regija\", \"Preminuli\")\n\n# zemljevid\n\nRegije <- unique(zemljevid$NAME_1)\nRegije <- as.data.frame(Regije, stringsAsFactors=FALSE) \nnames(Regije) <- \"Regija\"\nskupaj <- left_join(Regije, cluster, by=\"Regija\")\n\n\nzemljevid_cluster_preminuli <- ggplot() + geom_polygon(data=left_join(zemljevid, skupaj, by=c(\"NAME_1\"=\"Regija\")),\n aes(x=long, y=lat, group=group, \n fill=factor(Preminuli))) +\n geom_line() +\n theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.text.y=element_blank(),\n axis.ticks.y=element_blank()) +\n guides(fill=guide_colorbar(title=\"Skupine\")) +\n ggtitle('Razvrstitev regij v skupine glede na število preminulih v cestnoprometnih nesrečah na 10.000 registriranih motornih vozil') +\n labs(x = \" \") +\n labs(y = \" \") +\n scale_fill_brewer(palette=\"YlOrRd\", na.value = \"#e0e0d1\") \n\n\n\n#SHINY\n\ngraf.regije <- function(regija){\n ggplot(preminuli %>% filter(Regija %in% regija)) + aes(x=Leto, y=Preminuli, group=Regija, color=Regija) +\n geom_line() + geom_point()+ xlab(\"Leto\") + ylab(\"Število preminulih\") +\n theme(axis.text.x = element_text(angle = 90, vjust = 0.3, hjust=1))\n}\n\ngraf_osebni_avto <- function(cifra) {\n ggplot(osebni_avtomobili %>% filter(Leto==cifra), aes(x=Regija, y=Osebni_avtomobili, fill=factor(Regija))) + \n ylim(0, 650) + geom_bar(stat = \"identity\") +\n xlab(\"Regija\") + ylab(\"Število osebnih avtomobilov\") + \n theme(axis.text.x = element_text(angle = 90, size = 8, hjust = 1, vjust = 0.5)) +\n labs(fill='Regija')\n \n}\n", "meta": {"hexsha": "72c7c38673edecb118b466290b135b22438105a5", "size": 4107, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "NikiFMF10/APPR-2020-21", "max_stars_repo_head_hexsha": "bb86e36ed9afa3a415519cb5b51f7202b0ad8053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analiza/analiza.r", "max_issues_repo_name": "NikiFMF10/APPR-2020-21", "max_issues_repo_head_hexsha": "bb86e36ed9afa3a415519cb5b51f7202b0ad8053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-12-26T14:03:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T11:59:56.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "NikiFMF10/APPR-2020-21", "max_forks_repo_head_hexsha": "bb86e36ed9afa3a415519cb5b51f7202b0ad8053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3402061856, "max_line_length": 136, "alphanum_fraction": 0.7124421719, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.713027756711742}} {"text": "# ......................................................................................\n# .................... Cvičení 9. Intervalové odhady (jednoho výběru)...................\n# ............... Michal Béreš, Martina Litschmannová, Veronika Kubíčková...............\n# ......................................................................................\n\n# Nezobrazuje-li se vám text korektně, nastavte File \\ Reopen with Encoding... na UTF-8\n# Pro zobrazení obsahu skriptu použijte CTRL+SHIFT+O\n# Pro spouštění příkazů v jednotlivých řádcích použijte CTRL+ENTER\n\n# Demonstrace na úvod - co je to intervalový odhad? ####\n# Uvažujme náhodnou veličinu z normálního rozdělení se střední hodnotou $\\mu$ a\n# směrodatnou odchylkou $\\sigma$. Budeme pracovat s výběry z této náhodné veličiny a\n# pomoci jich se budeme snažit odhadnout střední hodnutu rozdělení (zde známe její\n# skutečnou hodnotu, ale v praxi je její hodnota neznámá).\n\n\nn = 30 # velikost výběru\nmu = 100 # střední hodnota\nsigma = 10 # směr. odchylka\n\n# simulace náhodného výběru ze zadané náhodné veličiny\nvyber = rnorm(n = n, mean = mu, sd = sigma)\n\nX = mean(vyber) # výběrový průměr jako bodový odhad\nS = sd(vyber) # výběrová směr. odch.\nX\nS\n\n# Pro přehlednost si můžeme výběr vizualizovat.\n\n\noptions(repr.plot.width = 12) # šířka grafů v Jupyteru\npar(mfrow = c(1, 2)) # matice grafů 1x2\n\nhist(vyber)\nboxplot(vyber)\n\n# ** Samotné sestrojení Intervalového odhadu pomocí výběrové charakteristiky ####\n# Použijeme tuto výběrovou charakteristiku: (předpokládáme, že neznáme žádné skutečné\n# parametry rozdělení, pouze to, že je normální)\n# $Y=\\frac{\\bar X - \\mu}{S}\\sqrt{n} \\sim t_{n-1}$ \n# Jelikož, známe rozdělení Y jsme schopni napočítat $a$ a $b$ v následujícím výrazu:\n# $P(a10)\n# - funkce v Rku vyžaduje dodatečný parametr (conf.int = TRUE)\n# - vyžaduje knihovnu \"BSDA\"\n# - jakožto nejrobustnější test, se dá použít i na nespojitá data - např. pořadí v\n# nějakém seznamu\n\n\nvyber = rexp(n = 30, rate = 1/100)\nalpha = 0.05\n\n# skutečný medián\nqexp(p = 0.5, rate = 1/100)\n\n# bodový odhad\n# quantile(vyber, probs = 0.5)\nmedian(vyber)\n# IO\n# install.packages(\"BSDA\")\nlibrary(BSDA)\nSIGN.test(vyber, alternative = 'two.sided', conf.level = 1-alpha, \n conf.int = TRUE)$conf.int\n\n# * Míry variability jednoho výběru ####\n# Mírami variability rozumíme údaj určující rozptýlenost/variabilitu dat, nehledě na\n# celkových hodnotách. Pro data z normálního rozdělení můžeme odhadovat směrodatnou\n# odchylku.\n# *** IO směrodatné odchylky ####\n# - odhadujeme směrodatnou odchylku - bodovým odhadem je výběrový směrodatná odchylka\n# - data musejí pocházet z normálního rozdělení\n# - exploračně: šikmost a špičatost leží v (-2,2)\n# - exploračně: QQ graf má body přibližně na čáře\n# - exaktně: pomocí statistického testu, např. Shapiro-Wilk test\n# (shapiro.test(data))\n# - vyžaduje balíček \"EnvStats\"\n# - funkce v Rku, dává výpočet rozptylu - nutná odmocnina výsledku\n\n\nvyber = rnorm(n = 30, mean = 100, sd = 10)\nalpha = 0.05\n\n# exploračně test normality\nmoments::skewness(vyber)\nmoments::kurtosis(vyber) - 3\nqqnorm(vyber)\nqqline(vyber)\n\n# exaktně test normality dat\nshapiro.test(vyber)$p.value\n# vysledná p-hodnota musím být větší než hl. výz. (př. 0.05)\n\n# bodový odhad\nsd(vyber)\n# IO\n#install.packages(\"EnvStats\")\nlibrary(EnvStats)\nsqrt(varTest(vyber, alternative = 'two.sided', conf.level = 1-alpha)$conf.int)\n\n# Přidáme si ruční výpočet:\n# - vycházíme ze statistiky: $\\frac{S^2}{\\sigma^2}(n-1) \\sim \\chi^2_{n-1}$\n# - Horní mez:\n# - $P(\\frac{S^2}{\\sigma^2}(n-1) < \\chi^2_{\\alpha /2, n-1}) = \\alpha /2$\n# - $P(\\frac{S^2}{\\chi^2_{\\alpha /2, n-1}}(n-1) < \\sigma^2 ) = \\alpha /2$\n# - Dolní mez:\n# - $P(\\frac{S^2}{\\sigma^2}(n-1) > \\chi^2_{1-\\alpha /2, n-1}) = \\alpha /2$\n# - $P(\\frac{S^2}{\\chi^2_{1-\\alpha /2, n-1}}(n-1) > \\sigma^2 ) = \\alpha /2$\n# - Dohromady: $P(\\frac{S^2}{\\chi^2_{1-\\alpha /2, n-1}}(n-1) < \\sigma^2\n# <\\frac{S^2}{\\chi^2_{\\alpha /2, n-1}}(n-1)) = 1 - \\alpha$\n\n\n# ruční výpočet\nalpha = 0.05\nn = 30\nS = sd(vyber)\n\nhor_q = qchisq(1 - alpha/2, n-1)\ndol_q = qchisq(alpha/2, n-1)\nhor_q\ndol_q\n\nsqrt(S^2*(n-1)/dol_q)\nsqrt(S^2*(n-1)/hor_q)\n\n# * Pravděpodobnost výskytu u jednoho výběru ####\n# *** IO pravděpodobnosti ####\n# - odhadujeme pravděpodobnost - bodový odhad je relativní četnost\n# - vyžadujeme dostatečný počet dat: $n>\\frac{9}{p(1-p)}$\n# - Clopperův - Pearsonův odhad (binom.test)\n# - jako parametr nebere data, ale počet úspěchů a počet pozorování \n# - Waldův - z výběrových charakteristik\n\n\npi = 0.3\nn = 60\nalpha = 0.05\nvyber = runif(n = n, min = 0, max = 1) < pi\n\n# ověření předpokladů\np = mean(vyber)\np\n9/(p*(1-p))\n\n# bodový odhad\np\n# intervalový odhad Clopperův - Pearsonův\ncelk_pocet = length(vyber)\npocet_poz = sum(vyber)\nbinom.test(x = pocet_poz, n = celk_pocet, alternative = 'two.sided', \n conf.level = 1 - alpha)$conf.int\n\n# Intervalový odhad Waldův\ndol_q = qnorm(alpha/2)\nhor_q = qnorm(1-alpha/2)\n\np - hor_q*sqrt(p*(1-p)/n) # dolní mez IO\np - dol_q*sqrt(p*(1-p)/n) # horní mez IO\n\n# Výpočet 11 nejčastěji používaných intervalů spolehlivosti param. bin. rozdělení\n# pomocí balíčku binom\n# install.packages(\"binom\")\nlibrary(binom)\nbinom.confint(n = celk_pocet, x = pocet_poz)\n\n# Příklady ####\n# * Příklad 1. ####\n# Při kontrolních zkouškách 16 žárovek byl stanoven odhad střední hodnoty $\\bar x$ = 3\n# 000 hodin a směrodatné odchylky s = 20 hodin jejich životnosti. Za předpokladu,že\n# životnost žárovky má normální rozdělení, určete 90% intervalový odhad pro parametry µ\n# a σ\n\n\n# Odhadujeme stř.hodnotu a směr.odchylku životnosti žárovek\n# Součástí zadání je informace o normalitě dat\n\nn = 16 # rozsah souboru \nx.bar = 3000 # hodin.... průměr (bodový odhad střední hodnoty)\ns = 20 # hodin.... výběrová směrodatná odchylka (bodový odhad sm. odchylky)\nalpha = 0.1 # hladina významnosti (spolehlivost 1-alpha = 0.9)\n\n# Oboustranný intervalový odhad střední hodnoty\ndol_q = qt(alpha/2,n-1)\nhor_q = qt(1 - alpha/2,n-1)\n\nx.bar - hor_q*s/sqrt(n) # dolní mez IO\nx.bar - dol_q*s/sqrt(n) # horní mez IO\n\n# Oboustranný intervalový odhad směrodatné odchylky\ndol_q = qchisq(alpha/2,n-1)\nhor_q = qchisq(1 - alpha/2,n-1)\n\nsqrt((n-1)*s^2/hor_q) # dolní mez IO\nsqrt((n-1)*s^2/dol_q) # horní mez IO\n\n# * Příklad 2. ####\n# Hloubka moře se měří přístrojem, jehož systematická chyba je rovna nule a náhodné\n# chyby mají normální rozdělení se směrodatnou odchylkou 20 m. Kolik nezávislých měření\n# je třeba provést,aby s pravděpodobností 95 % stanovila hloubku s chybou menší než 10\n# m?\n\n\n# Určujeme odhad potřebného rozsahu výběru (počtu potřebnych měření)\n\n# Předpokládáme normalitu dat, se známým rozpylem (dle zadání)\n\nsigma = 20 # metrů .... známá směrodatná odchylka\nalpha = 0.05 # hladina významnosti (spolehlivost 1-alpha = 0.95)\ndelta = 10 # metrů ... přípustná chyba měření \n\n# Odhad rozsahu výběru\n# Y = delta/sigma*sqrt(n) ~ N(0,1), delta = X-mu\n# P(Y > Z_(1-alpha/2)) = alpha/2\n\n(qnorm(1 - alpha/2)*sigma/delta)^2 \n\n# * Příklad 3. ####\n# Úkolem je určit průměrnou hladinu cholesterolu v séru v určité populaci mužů. V\n# náhodném výběru (pocházejícím z normálního rozdělení ) 25 mužů je výběrový průměr 6,3\n# mmol/l a výběrová směrodatná odchylka 1,3 mmol/l.\n\n\n# Odhadujeme střední hladinu cholesterolu v séru \n# Předpokládáme normalitu dat (dle zadání)\n\nn = 25 # rozsah souboru \nx.bar = 6.3 # mmol/l .... průměr (bodový odhad střední hodnoty)\ns = 1.3 # mmol/l .... výběrová směr. odchylka (bodový odhad sm. odchylky)\nalpha = 0.05 # hladina významnosti (spolehlivost 1-alpha = 0.95)\n\n# Oboustranný intervalový odhad střední hodnoty\ndol_q = qt(alpha/2, n-1)\nhor_q = qt(1 -alpha/2, n-1)\n\nx.bar - hor_q*s/sqrt(n) # dolní mez IO\nx.bar - dol_q*s/sqrt(n) # horní mez IO\n\n# * Příklad 4. ####\n# Předpokládejme, že v náhodném výběru 200 mladých mužů má 120 z nich vyšší než\n# doporučenou hladinu cholesterolu v séru. Určete 95% interval spolehlivosti pro\n# procento mladých mužů\n# s vyšší hladinou cholesterolu v populaci.\n\n\n# Odhadujeme podíl mužů s vyšší hladinou cholesterolu v celé populaci, \n# tj. pravděpodobnost,že náhodně vybraný muž bude mít vyšší hladinu cholesterolu\n\nn = 200 # rozsah souboru \nx = 120 # počet \"úspěchů\"\np = x/n # relativní četnost (bodový odhad pravděpodobnosti)\np\nalpha = 0.05 # hladina významnosti (spolehlivost 1-alpha = 0.95)\n\n# Ověření předpokladů\n9/(p*(1-p))\n\n# Oboustranný Clopperův - Pearsonův (exaktní) int.ý odhad param. binom. rozdělení\nbinom.test(x,n,alternative=\"two.sided\",conf.level=0.95)$conf.int\n\n## Waldův (asymptotický) odhad (z-statistika) - aprox. normálním rozdělením dle CLV\ndol_q = qnorm(alpha/2)\nhor_q = qnorm(1-alpha/2)\n\np - hor_q*sqrt(p*(1-p)/n) # dolní mez IO\np - dol_q*sqrt(p*(1-p)/n) # horní mez IO\n\n# * Příklad 5. ####\n# V rámci výzkumné studie pracujeme s náhodným výběrem 70 žen z české populace. U každé\n# z žen byl změřen hemoglobin s přesností 0,1 g/100 ml. Naměřené hodnoty jsou v uvedeny\n# v souboru Hemoglobin.xls. Nalezněte 95% intervalové odhady směrodatné odchylky a\n# střední hodnoty hemoglobinu v populaci českých žen. (Normalitu ověřte na základě\n# exploračních grafů.)\n\n\n## Odhadujeme střední hodnotu a směrodatnou odchylku hemoglobinu v séru\n\n## Načtení dat z xlsx souboru (pomoci balíčku readxl)\nlibrary(readxl)\nhem = read_excel(\"data/intervalove_odhady.xlsx\",\n sheet = \"Hemoglobin\")\ncolnames(hem) = \"hodnoty\"\nhead(hem)\n\n## Explorační analýza\nboxplot(hem$hodnoty)\n\n# Data neobsahují odlehlá pozorování.\nsummary(hem$hodnoty)\nsd(hem$hodnoty)\n\n# Ověření normality - exploračně \nqqnorm(hem$hodnoty)\nqqline(hem$hodnoty)\n\nmoments::skewness(hem$hodnoty)\nmoments::kurtosis(hem$hodnoty) - 3\n# Šikmost i špičatost odpovídá norm. rozdělení. \n\n# ověření normality: exaktně - test normality.\n# Známe-li testování hypotéz, ověříme Shapirovým . Wilkovým testem.\nshapiro.test(hem$hodnoty)$p.value\n# Na hl. významnosti 0.05\n\n# 95% oboustranný intervalový odhad střední hodnoty\nmean(hem$hodnoty)\nt.test(hem$hodnoty, altarnative=\"two.sided\", conf.level=0.95)$conf.int\n\n## 95% oboustranný intervalový odhad směrodatné odchylky\nlibrary(EnvStats)\nsd(hem$hodnoty)\n\nsqrt(varTest(hem$hodnoty, alternative = \"two.sided\", conf.level = 0.95)$conf.int)\n\n# * Příklad 6. ####\n# Jaký musí být počet pozorování, jestliže chceme s pravděpodobností 0,95 stanovit\n# průměrnou hodnotu hemoglobinu u novorozenců s chybou nejvýše 1,0 $g/l$. Populační\n# rozptyl hodnot se\n# odhaduje hodnotou 46,0 $g^2/l^2$.\n\n\n# Určujeme odhad potřebného rozsahu výb. (počtu novorozenců, které musíme testovat)\n\n# Předpokládáme normalitu dat, bez tohoto předpokladu je příklad neřešitelný\n\nsigma = sqrt(46) # g/l .... známá směrodatná odchylka\nalpha = 0.05 # hladina významnosti (spolehlivost 1-alpha = 0.95)\ndelta = 1 # g/l ... přípustná chyba měření \n\n# Odhad rozsahu výběru\n# Y = delta/sigma*sqrt(n) ~ N(0,1), delta = X-mu\n# P(Y > Z_(1-alpha/2)) = alpha/2\n\n(qnorm(1 - alpha/2)*sigma/delta)^2 \n\n# * Příklad 7. ####\n# V datovém souboru pr7.xlsx naleznete měření hluku způsobeného větrákem počítače [dB].\n# Spočtěte 95% intervalový odhad průměrného hluku a 95% intervalový odhad variability\n# hluku.\n\n\nlibrary(readxl)\n# načtení dat\ndata = read_excel(\"data/pr7.xlsx\")\nhead(data)\n\nlength(data$dB)\n\n# vizualizace\npom = boxplot(data$dB)\n\n# odstranění OP\ndata_op = data\ndata_op$dB[data_op$dB %in% pom$out] = NA\ndata_op = na.omit(data_op)\nboxplot(data_op$dB)\n\n# test normality dat exploračně\nmoments::skewness(data_op$dB)\nmoments::kurtosis(data_op$dB) - 3\n\nqqnorm(data_op$dB)\nqqline(data_op$dB)\n\n# test normality exaktně\nshapiro.test(data_op$dB)$p.value\n\n# bodový a intervalový odhad střední hodnoty\nmean(data_op$dB)\n\nt.test(data_op$dB, alternative = \"two.sided\", conf.level = 0.95)$conf.int\n\n# bodový a intervalový odhad směrodatné odchylky\nsd(data_op$dB)\n\nsqrt(varTest(data_op$dB,alternative = \"two.sided\", conf.level = 0.95)$conf.int)\n\n# * Příklad 8. ####\n# V datovém souboru pr8.xlsx naleznete měření doby do poruchy elektrické součástky [h].\n# Spočtěte 99% intervalový odhad průměrné životnosti daného typu součastky.\n\n\nlibrary(readxl)\n# načtení dat\ndata = read_excel(\"data/pr8.xlsx\")\nhead(data)\n\nlength(data$cas_h)\n\n# vizualizace a ověření OP\nboxplot(data$cas_h)\n\nhist(data$cas_h)\n\n# test normality dat exploračně\nmoments::skewness(data$cas_h)\nmoments::kurtosis(data$cas_h) - 3\n\nqqnorm(data$cas_h)\nqqline(data$cas_h)\n\n# test normality exaktně\nshapiro.test(data$cas_h)$p.value\n\n# test symetrie exploračně\nmoments::skewness(data$cas_h)\nhist(data$cas_h)\n\n# exaktně: test symetrie\n# install.packages(\"lawstat\")\nlibrary(lawstat)\nsymmetry.test(data$cas_h,boot=FALSE)$p.value\n# vysledná p-hodnota musím být větší než hl. výz. (př. 0.05)\n\n# bodový a intervalový odhad mediánu\nmedian(data$cas_h)\n# IO\n# install.packages(\"BSDA\")\nalpha = 0.01\nlibrary(BSDA)\nSIGN.test(data$cas_h, alternative = 'two.sided', conf.level = 1-alpha, \n conf.int = TRUE)$conf.int\n\nsd(data$cas_h)\n\n\n\n", "meta": {"hexsha": "e968016e1ddb9f2d9eec85d0620299733528b01d", "size": 18659, "ext": "r", "lang": "R", "max_stars_repo_path": "CV9/cv9.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CV9/cv9.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CV9/cv9.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7397034596, "max_line_length": 88, "alphanum_fraction": 0.6885149258, "num_tokens": 7995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7129956312124994}} {"text": "compute_π <- function(trials) {\n inside <- 0.0\n for (i in 1:trials) {\n point <- runif(2)\n inside <- inside + (sum(point^2) <= 1.0)\n }\n return(4.0*inside/trials)\n}\n\nargs = commandArgs(trailingOnly=TRUE)\nif(length(args) < 1) {\n error(\"must provide number of trials\")\n}\ntrials = as.integer(args[1])\nset.seed(2018)\n\nstart.time <- Sys.time()\ninvisible(compute_π(trials))\nstop.time <- Sys.time()\ncat(\"First invocation: \", stop.time - start.time, \"s\\n\")\n\nstart.time <- Sys.time()\nπ <- compute_π(trials)\nstop.time <- Sys.time()\ncat(\"Second invocation:\", stop.time - start.time, \"s\\n\")\n\ncat(\"π ≈ \", π, \"\\n\")\n", "meta": {"hexsha": "1c86715ebde2f7ee3f3fdbfc676cb2f21199f3ea", "size": 628, "ext": "r", "lang": "R", "max_stars_repo_path": "pi/R/pi.r", "max_stars_repo_name": "ELIFE-ASU/meet-julia", "max_stars_repo_head_hexsha": "4e7efe885da3b935c61d7fab5c6e7fc057077be4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-03T10:39:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-03T10:39:33.000Z", "max_issues_repo_path": "pi/R/pi.r", "max_issues_repo_name": "ELIFE-ASU/meet-julia", "max_issues_repo_head_hexsha": "4e7efe885da3b935c61d7fab5c6e7fc057077be4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-11T06:03:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-11T06:14:55.000Z", "max_forks_repo_path": "pi/R/pi.r", "max_forks_repo_name": "ELIFE-ASU/meet-julia", "max_forks_repo_head_hexsha": "4e7efe885da3b935c61d7fab5c6e7fc057077be4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-11T05:36:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-11T05:36:39.000Z", "avg_line_length": 22.4285714286, "max_line_length": 56, "alphanum_fraction": 0.6146496815, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7905303087996142, "lm_q1q2_score": 0.7129956225933328}} {"text": "#############################################\n# Part i\nn = 200\np = 0.3\nrho = -0.3\n\n# subfunction needed to generate data\ncalcbij = function(rho,i){\n a = ((1-4*rho*rho)^0.5-1)/(2*rho)\n j = i-1\n bi = (a^(1:j) - a^(-(1:j)))/(a^-i - a^(i))\n return(bi)\n}\n\n# function to generate one dataset\n# following Qaqish (2003) algorithm\ngendataPW = function(n,p,rho){\n dat = c(rbinom(1,1,p),rep(NA,n-1))\n for(i in 2:n){\n j = i-1\n bi = calcbij(rho,i)\n prob = p + sum(bi*(dat[1:j]-p))\n if(prob < 0) prob = 0.0001\n if(prob > 1) prob = 0.9999\n dat[i] = rbinom(1,1,prob)\n }\n return(dat)\n}\n\n# Generate 100 replicates\nx = matrix(NA,100,n)\nfor(r in 1:100){\n x[r,]=gendataPW(n,p,rho)\n}\nwrite(t(x),\"p.30_pair.neg30_n200_r100.txt\",ncol=n) # each row in this file is a different simulated song\n\n#############################################\n# Part ii\nn = 600\np = 0.3\nrho = -0.3\n\n# subfunction needed to generate data\ncalcbij = function(rho,i){\n a = ((1-4*rho*rho)^0.5-1)/(2*rho)\n j = i-1\n bi = (a^(1:j) - a^(-(1:j)))/(a^-i - a^(i))\n return(bi)\n}\n\n# function to generate one dataset\n# following Qaqish (2003) algorithm\ngendataPW = function(n,p,rho){\n dat = c(rbinom(1,1,p),rep(NA,n-1))\n for(i in 2:n){\n j = i-1\n bi = calcbij(rho,i)\n prob = p + sum(bi*(dat[1:j]-p))\n if(prob < 0) prob = 0.0001\n if(prob > 1) prob = 0.9999\n dat[i] = rbinom(1,1,prob)\n }\n return(dat)\n}\n\n# Generate 100 replicates\nx = matrix(NA,100,n)\nfor(r in 1:100){\n x[r,]=gendataPW(n,p,rho)\n}\nwrite(t(x),\"p.30_pair.neg30_n600_r100.txt\",ncol=n) # each row in this file is a different simulated song\n", "meta": {"hexsha": "5d617632d9ff3739da3ebaf1cbecc3d46d47a308", "size": 1592, "ext": "r", "lang": "R", "max_stars_repo_path": "GHSupplementaryFiles/AppendixD/pairwiseCorrelation.r", "max_stars_repo_name": "iramler/guitar_hero_jse", "max_stars_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GHSupplementaryFiles/AppendixD/pairwiseCorrelation.r", "max_issues_repo_name": "iramler/guitar_hero_jse", "max_issues_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GHSupplementaryFiles/AppendixD/pairwiseCorrelation.r", "max_forks_repo_name": "iramler/guitar_hero_jse", "max_forks_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1111111111, "max_line_length": 106, "alphanum_fraction": 0.5546482412, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.712529909017682}} {"text": "\"\nНаписать формулу получения 10 случайных целых чисел из диапазона (min = -7, max = 28\nс помощью функции runif(),\nне используя при ее вызове задания минимального и максимального значений.\n\"\n{\nchecker <- function(n,min,max){\n return(floor((runif(n) * ((max - min) + 1)) + min))\n}\n\nn <- 10\nmin <- -7\nmax <- 28\nprint(checker(n,min,max))\n\n}", "meta": {"hexsha": "4f45714fff89227f82270879463edc043436778c", "size": 339, "ext": "r", "lang": "R", "max_stars_repo_path": "Course II/R/pract/pract4/task6.r", "max_stars_repo_name": "GeorgiyDemo/FA", "max_stars_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-08-18T20:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T02:39:45.000Z", "max_issues_repo_path": "Course II/R/pract/pract4/task6.r", "max_issues_repo_name": "GeorgiyDemo/FA", "max_issues_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 217, "max_issues_repo_issues_event_min_datetime": "2019-09-22T14:43:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:49:18.000Z", "max_forks_repo_path": "Course II/R/pract/pract4/task6.r", "max_forks_repo_name": "GeorgiyDemo/FA", "max_forks_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2019-09-18T11:36:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:43:00.000Z", "avg_line_length": 21.1875, "max_line_length": 85, "alphanum_fraction": 0.6725663717, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7119674894466623}} {"text": "#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n# Full Investment Constraints\r\ncset.sum <- function(returns, sum=1){\r\n p = ncol(returns)\r\n constaint.sum <- rep(1,p)\r\n A = cbind(constaint.sum) # Constraint matrix\r\n colnames(A) <- \"c.sum\"\r\n b = sum # Constraint bound\r\n meq = 1\r\n # cset.lo = constraints(A,b,meq)\r\n return(list(A=A,b=b,meq=meq,cname=\"cset.sum\"))\r\n}\r\n\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n\r\n# Long-Only Constraints\r\ncset.lo <- function(returns){\r\np = ncol(returns)\r\nA = diag(rep(1,p)) # Constraint matrix\r\ncolnames(A) <- paste(\"c.long.only\",1:ncol(A),sep=\"\")\r\nb = c(rep(0,p)) # Constraint bound\r\nmeq = 0\r\n# cset.lo = constraints(A,b,meq)\r\nreturn(list(A=A,b=b,meq=meq,cname=\"cset.lo\"))\r\n}\r\n\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n\r\n# Box Constraints\r\ncset.box <- function(returns,upper,lower){\r\np = ncol(returns)\r\n\r\nif(length(upper)==1)\r\n upper <- rep(upper, p)\r\n\r\n\r\nif(length(lower)==1)\r\n lower <- rep(lower, p)\r\n\r\n\r\nconstraint.box <-cbind(diag(rep(1,p)),diag(rep(-1,p)))\r\nA = cbind(constraint.box)\r\ncolnames(A) <- paste(\"c.box\",\r\n c(paste(\".low\",rep(1:(ncol(constraint.box)/2)),sep=\"\"),\r\n paste(\".up\",rep(1:(ncol(constraint.box)/2)),sep=\"\")),sep=\"\")\r\nb = c(lower,-upper)\r\nmeq = 0\r\n# cset.box = constraints(A,b,meq)\r\nreturn(list(A=A,b=b,meq=meq,cname=\"cset.box\"))\r\n}\r\n\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n\r\n# Group Constraints \r\ncset.groups <- function(returns=returns8,\r\n group=c(1,1,1,2,3,3,4,4),\r\n upper.group=rep(0.2,4),\r\n lower.group=rep(-0.2,4)){\r\np = ncol(returns)\r\n\r\n\r\nif(length(upper.group)==1)\r\n upper.group <- rep(upper.group, length(unique(group)))\r\n\r\n\r\nif(length(lower.group)==1)\r\n lower.group <- rep(lower.group, length(unique(group)))\r\n\r\n\r\nif(!all(length(group)==p,length(upper.group)==length(unique(group)), length(lower.group)==length(unique(group))))\r\n stop(\"any of the length of group/upper/lower bounds is not equal to the number of assets\")\r\n\r\nif(length(upper.group)==1)\r\n rep(upper.group, length(group))\r\n\r\nif(length(lower.group)==1)\r\n rep(lower.group, length(group))\r\n \r\ngnum <- length(unique(group))\r\nglist <- lapply(unique(group),function(x) which(x == group))\r\nnames(glist) <- unique(group)\r\nAg <- t(sapply(glist, function(x) {\r\n re <- rep(0,p)\r\n re[x] <- 1\r\n re}))\r\nAtp = rbind(Ag,-Ag)\r\nconstraint.groups = t(Atp)\r\nA <- cbind(constraint.groups)\r\ncolnames(A) <- paste(\"c.groups\",\r\n c(paste(\".low\",rep(1:(ncol(constraint.groups)/2)),sep=\"\"),\r\n paste(\".up\",rep(1:(ncol(constraint.groups)/2)),sep=\"\")),sep=\"\")\r\nbglo = c(lower.group)\r\nbgup = c(upper.group)\r\nb = c(bglo,-bgup)\r\nmeq = 0\r\n# cset.groups = constraints(A,b,meq)\r\nreturn(list(A=A,b=b,meq=meq,cname=\"cset.groups\"))\r\n}\r\n\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n\r\n# Turnover Constraints\r\n\r\ncset.turnover <- function(returns,toc,w.initial){\r\n\tp = ncol(returns)\r\n\tconstraint.turnover <- c(rep(0,p),rep(-1,p),rep(1,p))\r\n#\tconstraint.weights.initial <- rbind(diag(p),matrix(0,ncol=p,nrow=p*2))\r\n#\tconstraint.weights.finalsum <- c(rep(1,p),rep(0,2*p))\r\n\tconstraint.weights.initial <- rbind(diag(1,p),diag(-1,p),diag(-1,p))\r\n\tconstraint.weights.positive <-\r\n\t\t\trbind(matrix(0,ncol=2*p,nrow=p),diag(2*p))\r\n\ttemp.index <- (p*3-p+1):(p*3)\r\n\t#need to flip sign for w_sell\r\n\tconstraint.weights.positive[temp.index,]<-\r\n\t\t\tconstraint.weights.positive[temp.index,]*-1\r\n\t\r\n\tA <- cbind(constraint.weights.initial,\r\n\t\t\tconstraint.turnover, constraint.weights.positive)\r\n\tcolnames(A) <- c(paste(\"c.winit\",1:p,sep=\"\"),\r\n\t\t\t\"c.turnover\",\r\n\t\t\tpaste(\"c.wpos\",1:ncol(constraint.weights.positive),sep=\"\"))\r\n\tb <- c(w.initial,-toc,rep(0,2*p))\r\n\tmeq <- p+1\r\n\treturn(list(A=A,b=b,meq=meq,cname=\"cset.turnover\"))\r\n}\r\n\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n\r\n# Turnover Constraints made by hobbs\r\ncset.turnover.hobbs <- function(returns,toc,w.initial){\r\n\tp = ncol(returns)\r\n\tconstraint.turnover <- c(rep(0,p),rep(-1,p),rep(1,p))\r\n\tconstraint.weights.initial <- rbind(diag(p),matrix(0,ncol=p,nrow=p*2))\r\n\tconstraint.weights.positive <-\r\n\t\t\trbind(matrix(0,ncol=2*p,nrow=p),diag(2*p))\r\n\ttemp.index <- (p*3-p+1):(p*3)\r\n\t#need to flip sign for w_sell\r\n\tconstraint.weights.positive[temp.index,]<-\r\n\t\t\tconstraint.weights.positive[temp.index,]*-1\r\n\t\r\n\tA <- cbind(constraint.weights.initial,\r\n\t\t\tconstraint.turnover, constraint.weights.positive)\r\n\tcolnames(A) <- c( paste(\"c.winit\",1:ncol(constraint.weights.initial),sep=\"\"),\r\n\t\t\t\"c.turnover\",\r\n\t\t\tpaste(\"c.wpos\",1:ncol(constraint.weights.positive),sep=\"\"))\r\n\tb <- c(w.initial,-toc,rep(0,2*p))\r\n\tmeq <- p\r\n\t\r\n\treturn(list(A=A,b=b,meq=meq,cname=\"cset.turnover\"))\r\n}\r\n\r\n\r\n\r\n\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n\r\n#Proportional Cost Constraints\r\ncset.propcost<- function(returns, ptc,w.initial){\r\n p = ncol(returns)\r\n dvec <- rep(0,p*3) #no linear part in this problem\r\n #left hand side of constraints\r\n if(length(ptc)==1){\r\n ptc = rep(ptc,p)\r\n }\r\n if(length(ptc)!=p){\r\n stop(\"ptc must either be a single value, or the same length as the number of assets\")\r\n }\r\n \r\n constraint.sum.prop <- c(rep(1,p),1+ptc,(1-ptc))\r\n constraint.weights.initial <- rbind(diag(p),matrix(0,ncol=p,nrow=p*2))\r\n constraint.weights.positive <-\r\n rbind(matrix(0,ncol=2*p,nrow=p),diag(2*p))\r\n temp.index <- (p*3-p+1):(p*3)\r\n #need to flip sign for w_sell\r\n constraint.weights.positive[temp.index,]<-\r\n constraint.weights.positive[temp.index,]*-1\r\n #put left hand side of constraints into constraint matrix\r\n A <- cbind(constraint.sum.prop, constraint.weights.initial,\r\n constraint.weights.positive)\r\n colnames(A) <- c(\"c.sum.prop\",\r\n paste(\"c.winit\",1:ncol(constraint.weights.initial),sep=\"\"),\r\n paste(\"c.wpos\",1:ncol(constraint.weights.positive),sep=\"\"))\r\n #right hand side of constraints in this vector\r\n b <- c(1, w.initial,rep(0,2*p))\r\n n.eq = 1+ p\r\n return(list(A=A,b=b,meq=n.eq,cname=\"cset.propcost\"))\r\n}\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n# Target MU Constraints\r\ncset.mu.target <- function(returns, mu.target){\r\n p = ncol(returns)\r\n mu = apply(returns,2, mean)\r\n A = cbind(mu)\r\n colnames(A) <- \"c.mu.target\"\r\n b = mu.target\r\n meq = 1\r\n return(list(A=A,b=b,meq=meq,cname=\"cset.mu.target\"))\r\n}\r\n\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n\r\ncset.fixed <- function(returns, fixed.cost, wmax, wmin){\r\n \r\n # TBA\r\n}\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n# Modify constaints when turnover kicks in\r\nturnover.hobbs.modify <- function(cset=cset.i){\r\n switch(cset$cname,\r\n \"cset.sum\" = {\r\n cset.new <- cset\r\n cset.new$A <- rbind(cset$A,cset$A,cset$A)\r\n colnames(cset.new$A) <- colnames(cset$A)\r\n cset.new$b <- cset$b\r\n cset.new$meq <- cset$meq\r\n cset.new \r\n },\r\n \r\n \"cset.lo\" = { #may not be needed\r\n cset.new <- cset\r\n cset.new$A <- rbind(cset$A,cset$A,cset$A)\r\n colnames(cset.new$A) <- colnames(cset$A)\r\n cset.new$b <- cset$b\r\n cset.new$meq <- cset$meq\r\n cset.new \r\n },\r\n \r\n \"cset.box\" = {\r\n cset.new <- cset\r\n cset.new$A <- rbind(cset$A,cset$A,cset$A)\r\n colnames(cset.new$A) <- colnames(cset$A)\r\n cset.new$b <- cset$b\r\n cset.new$meq <- cset$meq\r\n cset.new \r\n },\r\n \r\n \"cset.groups\" = {\r\n cset.new <- cset\r\n cset.new$A <- rbind(cset$A,cset$A,cset$A)\r\n colnames(cset.new$A) <- colnames(cset$A)\r\n cset.new$b <- cset$b\r\n cset.new$meq <- cset$meq\r\n cset.new \r\n },\r\n \r\n \"cset.mu.target\" = {\r\n cset.new <- cset\r\n cset.new$A <- rbind(cset$A,cset$A,cset$A)\r\n colnames(cset.new$A) <- colnames(cset$A)\r\n cset.new$b <- cset$b\r\n cset.new$meq <- cset$meq\r\n cset.new \r\n }\r\n )\r\n \r\n}\r\n \r\n\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n\r\n# Modify constaints when turnover kicks in\r\nturnover.modify <- function(cset=cset.i){\r\n\t\r\n\tmakenullmat <- function(A){matrix(0,nrow=nrow(A),ncol=ncol(A))}\r\n\t\r\n\tswitch(cset$cname,\r\n\t\t\t\"cset.sum\" = {\r\n\t\t\t\tcset.new <- cset\r\n\t\t\t\tcset.new$A <- rbind(cset$A,\r\n\t\t\t\t\t\tmakenullmat(cset$A),makenullmat(cset$A))\r\n\t\t\t\tcolnames(cset.new$A) <- colnames(cset$A)\r\n\t\t\t\tcset.new$b <- cset$b\r\n\t\t\t\tcset.new$meq <- cset$meq\r\n\t\t\t\tcset.new \r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"cset.lo\" = { #may not be needed\r\n\t\t\t\tcset.new <- cset\r\n\t\t\t\tcset.new$A <- rbind(cset$A,\r\n\t\t\t\t\t\tmakenullmat(cset$A),makenullmat(cset$A))\r\n\t\t\t\tcolnames(cset.new$A) <- colnames(cset$A)\r\n\t\t\t\tcset.new$b <- cset$b\r\n\t\t\t\tcset.new$meq <- cset$meq\r\n\t\t\t\tcset.new \r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"cset.box\" = {\r\n\t\t\t\tcset.new <- cset\r\n\t\t\t\tcset.new$A <- rbind(cset$A,\r\n\t\t\t\t\t\tmakenullmat(cset$A),makenullmat(cset$A))\r\n\t\t\t\tcolnames(cset.new$A) <- colnames(cset$A)\r\n\t\t\t\tcset.new$b <- cset$b\r\n\t\t\t\tcset.new$meq <- cset$meq\r\n\t\t\t\tcset.new \r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"cset.groups\" = {\r\n\t\t\t\tcset.new <- cset\r\n\t\t\t\tcset.new$A <- rbind(cset$A,\r\n\t\t\t\t\t\tmakenullmat(cset$A),makenullmat(cset$A))\r\n\t\t\t\tcolnames(cset.new$A) <- colnames(cset$A)\r\n\t\t\t\tcset.new$b <- cset$b\r\n\t\t\t\tcset.new$meq <- cset$meq\r\n\t\t\t\tcset.new \r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"cset.mu.target\" = {\r\n\t\t\t\tcset.new <- cset\r\n\t\t\t\tcset.new$A <- rbind(cset$A,\r\n\t\t\t\t\t\tmakenullmat(cset$A),makenullmat(cset$A))\r\n\t\t\t\tcolnames(cset.new$A) <- colnames(cset$A)\r\n\t\t\t\tcset.new$b <- cset$b\r\n\t\t\t\tcset.new$meq <- cset$meq\r\n\t\t\t\tcset.new \r\n\t\t\t}\r\n\t)\r\n\t\r\n}\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n\r\n# Modify constaints when propcost kicks in\r\npropcost.modify <- function(cset=cset.i){\r\n switch(cset$cname,\r\n \"cset.sum\" = {\r\n stop(\"sum constraint are not combinable with propcost constraint\")\r\n },\r\n \r\n \"cset.lo\" = { #may not be needed\r\n cset.new <- cset\r\n cset.new$A <- rbind(cset$A,cset$A,cset$A)\r\n colnames(cset.new$A) <- colnames(cset$A)\r\n cset.new$b <- cset$b\r\n cset.new$meq <- cset$meq\r\n cset.new \r\n },\r\n \r\n \"cset.box\" = {\r\n cset.new <- cset\r\n cset.new$A <- rbind(cset$A,cset$A,cset$A)\r\n colnames(cset.new$A) <- colnames(cset$A)\r\n cset.new$b <- cset$b\r\n cset.new$meq <- cset$meq\r\n cset.new \r\n },\r\n \r\n \"cset.groups\" = {\r\n cset.new <- cset\r\n cset.new$A <- rbind(cset$A,cset$A,cset$A)\r\n colnames(cset.new$A) <- colnames(cset$A)\r\n cset.new$b <- cset$b\r\n cset.new$meq <- cset$meq\r\n cset.new \r\n },\r\n \r\n \"cset.mu.target\" = {\r\n cset.new <- cset\r\n cset.new$A <- rbind(cset$A,cset$A,cset$A)+1\r\n colnames(cset.new$A) <- colnames(cset$A)\r\n cset.new$b <- cset$b+1\r\n cset.new$meq <- cset$meq\r\n cset.new \r\n }\r\n )\r\n \r\n}\r\n\r\n\r\n#' Constraint specifications\r\n#' @param NULL\r\n#' @details \r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @family constraints\r\n#' @examples\r\n#' @export\r\n# Combine multiple constraints\r\ncombine.cset <- function(clist=c( \"sum\", \r\n \"lo\",\r\n \"box\",\r\n \"groups\",\r\n \"mu.target\",\r\n \"turnover.hobbs\",\r\n\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \"turnover\",\r\n \"propcost\"),\r\n returns=returns,\r\n list.arg=\r\n list(sum=NULL,\r\n mu.target=NULL, \r\n w.initial=NULL, \r\n toc=NULL,\r\n upper=NULL,\r\n lower=NULL,\r\n group=NULL,\r\n upper.group=NULL,\r\n lower.group=NULL,\r\n ptc=NULL),\r\n\t\t\t\t\t\tverbose=T\r\n ){\r\n \r\n clist <- unique(clist)\r\n \r\n if(\"turnover.hobbs\" %in% clist)\r\n is.turnover.hobbs <- TRUE else is.turnover.hobbs <- FALSE\r\n if(\"propcost\" %in% clist)\r\n is.propcost <- TRUE else is.propcost <- FALSE\r\n if(\"turnover\" %in% clist)\r\n\tis.turnover <- TRUE else is.turnover <- FALSE\r\n\r\n clist.names <- clist\r\n arg.sum.list <- list.arg\r\n arg.sum.list$returns <- returns\r\n cset <- list(NA)\r\n \r\n\tif(!any(c(\"sum\",\"propcost\")%in% clist.names )){\r\n\t\tclist.names <- c(\"sum\",clist.names)\r\n\t\targ.sum.list$sum = 1\r\n\t}\r\n \r\n # loop through each constraint\r\n for ( i in 1:length(clist.names)){\r\n\tif(verbose)\r\n cat(clist.names[i],\"\\n\")\r\n clist.names.i <- paste(\"cset.\",clist.names[i],sep=\"\")\r\n args.names <- names(formals(clist.names.i))\r\n \r\n # loop through each argument\r\n for (ii in 1:length(args.names)) {\r\n if(is.null(eval(parse(text=paste(\"arg.sum.list$\",args.names[ii],sep=\"\")))))\r\n stop(paste(\"you need to specify argument \",args.names[ii],\" in order to use constraint \",clist.names[i],sep=\"\" ))\r\n }\r\n \r\n cset.i <- do.call(clist.names.i,arg.sum.list[args.names]) \r\n \r\n\t# these three constraints cannot be together\r\n if (is.turnover.hobbs & !(clist.names.i %in% c(\"cset.turnover.hobbs\",\"cset.turnover\",\"cset.propcost\"))){\r\n cset[[i]] <- turnover.hobbs.modify (cset.i)\r\n } \r\n\telse if(is.turnover & !(clist.names.i %in% c(\"cset.turnover.hobbs\",\"cset.turnover\",\"cset.propcost\")))\r\n\tcset[[i]] <- turnover.modify (cset.i)\r\n\telse if(is.propcost & !(clist.names.i %in% c(\"cset.turnover.hobbs\",\"cset.turnover\",\"cset.propcost\")))\r\n {\r\n cset[[i]] <- propcost.modify(cset.i)\r\n } else\r\n cset[[i]] <- cset.i\r\n }\r\n\r\n # remove warning case\r\n index.rem <- which(sapply(cset, length)!=4)\r\n if(length(index.rem))\r\n cset[[index.rem]] <- NULL\r\n \r\n # dimnames(Amat) <- NULL\r\n A.all <- do.call(cbind,lapply(cset,function(x)x$A))\r\n colnames(A.all) <- unlist(lapply(cset,function(x)colnames(x$A)))\r\n b.all <- do.call(c,lapply(cset,function(x)x$b))\r\n names(b.all) <- colnames(A.all)\r\n meq.all <- do.call(c,lapply(cset,function(x)x$meq))\r\n \r\n if(sum(meq.all)!=meq.all[1]){\r\n # shift meq in front\r\n meq.pos <- sapply(cset,function(x)ncol(x$A))\r\n a <- NULL\r\n a[1] <- 1\r\n for (k in 2:length(meq.pos))\r\n a[k] <- a[k-1]+meq.pos[k-1]\r\n sequ <- NULL\r\n for (kk in 1:length(meq.pos)){\r\n if(meq.all[kk]!=0)\r\n sequ <- c(sequ, a[kk]:(a[kk]+meq.all[kk]-1))\r\n }\r\n \r\n A.temp <- A.all\r\n b.temp <- b.all\r\n A.all <- cbind(A.temp[,c(sequ)],A.temp[,-c(sequ)])\r\n b.all <- c(b.temp[c(sequ)],b.temp[-c(sequ)])\r\n \r\n # delete duplicated constraints not implemented \r\n INDEX <- NULL\r\n for (i in 1:ncol(A.all)){\r\n index <- which(apply(A.all, 2, function(x)all.equal(x,A.all[,i]))==\"TRUE\")\r\n if(length(index)>1){\r\n index <- index[-which(index==i)]\r\n INDEX <- c(INDEX,index[index>i]) \r\n }\r\n }\r\n if(length(INDEX)){\r\n A.all <- A.all[,-INDEX]\r\n b.all <- b.all[-INDEX]}\r\n meq.all <- sum(meq.all)} else{\r\n meq.all <- sum(meq.all)\r\n } \r\n \r\n\r\n return(list(A=A.all,\r\n b=b.all,\r\n meq=meq.all,\r\n clist.names= clist.names))\r\n}\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "a59a108b7ea6d51350d5c2ddd902bf6a096dc2ca", "size": 17236, "ext": "r", "lang": "R", "max_stars_repo_path": "R/constraint.sets.r", "max_stars_repo_name": "kecoli/PCRM", "max_stars_repo_head_hexsha": "6603978752abbf33b40c0ea2ca4706d0a9393e2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-15T15:17:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-15T15:17:44.000Z", "max_issues_repo_path": "R/constraint.sets.r", "max_issues_repo_name": "kecoli/PCRM", "max_issues_repo_head_hexsha": "6603978752abbf33b40c0ea2ca4706d0a9393e2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/constraint.sets.r", "max_forks_repo_name": "kecoli/PCRM", "max_forks_repo_head_hexsha": "6603978752abbf33b40c0ea2ca4706d0a9393e2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.774624374, "max_line_length": 122, "alphanum_fraction": 0.5549431423, "num_tokens": 5045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7118986255332357}} {"text": "# Team Rython, Dainius Masiliunas and Tim Weerman\n# Date: 11 January, 2016\n# Apache License 2.0\n\n# Calculate the Root Mean Squared Error\nRMSE = function(truth, prediction)\n{\n return(sqrt(mean((truth-prediction)^2, na.rm=TRUE)))\n}\n\n# Calculate partial RMSE for different zones by generating squared difference rasters.\nGetDifferenceRaster = function(former, latter, filename=paste(\"data/\", names(latter), \".grd\", sep=\"\"), force=FALSE)\n{\n # Figure out a reasonable output name\n if (filename == \"data/layer.grd\")\n warning(\"Please pass filename or assign meaningful names to input rasters! Else the loaded data may not match expectations.\")\n \n # Create one or load one\n if (!file.exists(filename) || force)\n {\n return(overlay(former, latter, fun=function(truth, prediction){(truth-prediction)^2},\n filename=filename))\n }\n else\n return(raster(filename))\n}\n\n# Calculate RMSE per zone\nStratifiedRMSE = function(truth, prediction, zones, zonenames = \"\", ...)\n{\n # Unfortunately, zonal() just passes a vector of numbers, not a matrix.\n # So we have to calclate RMSE manually from a difference raster.\n differenceRaster = GetDifferenceRaster(truth, prediction, ...)\n \n # Get a mean from the zones in the difference raster\n zonestats = zonal(differenceRaster, zones, fun=\"mean\")\n zonestats[,2] = sqrt(zonestats[,2])\n \n # Add nice labels, if we have them\n if (length(zonenames) > 1)\n rownames(zonestats) = zonenames\n \n return(zonestats)\n}\n", "meta": {"hexsha": "8bff8bbc2008609cb010c9edf709baeaa1d0f78e", "size": 1533, "ext": "r", "lang": "R", "max_stars_repo_path": "Lesson8/src/RMSE.r", "max_stars_repo_name": "GreatEmerald/geoscripting", "max_stars_repo_head_hexsha": "7133bc2275b9030f831860fd24cea53446fe3037", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-01-27T09:48:34.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-27T09:48:34.000Z", "max_issues_repo_path": "Lesson8/src/RMSE.r", "max_issues_repo_name": "GreatEmerald/geoscripting", "max_issues_repo_head_hexsha": "7133bc2275b9030f831860fd24cea53446fe3037", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson8/src/RMSE.r", "max_forks_repo_name": "GreatEmerald/geoscripting", "max_forks_repo_head_hexsha": "7133bc2275b9030f831860fd24cea53446fe3037", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0666666667, "max_line_length": 133, "alphanum_fraction": 0.682322244, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7117432425426042}} {"text": "randN = function(N) sample.int(N, 1) == 1\n\nunbiased = function(f)\n {while ((x <- f()) == f()) {}\n x}\n\nsamples = 10000\nprint(t(round(d = 2, sapply(3:6, function(N) c(\n N = N,\n biased = mean(replicate(samples, randN(N))),\n unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))\n", "meta": {"hexsha": "69b0252ab15e41525b231226cd9ab95b2017c924", "size": 307, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Unbias-a-random-generator/R/unbias-a-random-generator.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Unbias-a-random-generator/R/unbias-a-random-generator.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Unbias-a-random-generator/R/unbias-a-random-generator.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 25.5833333333, "max_line_length": 75, "alphanum_fraction": 0.5830618893, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.7114815670527681}} {"text": "####### SECTION 2 ####\n####################\nCD4.data <- read.table(\"Data/cd4.data\",\n col.names=c(\"Time\",\"CD4\",\"Age\",\"Packs\",\n \"Drugs\",\"Sex\",\"Cesd\",\"ID\")) #READ IN DATA \nattach(CD4.data) ##attach data frame, now you can use just the names\n\n###Figure 1\npostscript(\"Plots/plot-02-01.ps\")\npar(mfrow=c(1,1)) ##makes a 1,1 grid for the figure\nplot(Time,CD4,pch=\".\",main=\"CD4 counts vs Time\",xlab=\"Time since zeroconversion\",ylab=\"CD4\")##plots CD4 vs. Time \ndev.off()\n\n###Figures 2\npostscript(\"Plots/plot-02-02.ps\",horizontal=T)\nplot(Time,CD4,main=\"Regression Lines\",pch=\".\")\nabline(lm(CD4~Time))\no <- order(Time)\nlines(Time[o],lm(CD4~poly(Time,2))$fitted[o],lty=2)\nlines(Time[o],lm(CD4~poly(Time,3))$fitted[o],lty=4)\nlegend(3.75,3000,legend=c(\"line\",\"parabola\",\"cubic poly\"),lty=c(1,2,4))\ndev.off()\n\n###Figure 3\n###BIN SMOOTHER\npostscript(\"Plots/plot-02-03.ps\",horizontal=T)\ncs <- c(-Inf,quantile(Time,probs=c(1/5,2/5,3/5,4/5)),Inf)\nR <- cut(Time,cs)\nplot(Time,CD4,main=\"Bin Smoother\",pch=\".\")\nlines(Time[o],lm(CD4~R)$fitted[o])\ndev.off()\n###Figure 4\n###Running-mean and running-line \nlibrary(\"modreg\") ##this library contains the function ksmooth\npostscript(\"Plots/plot-02-04.ps\",horizontal=T)\no <- sample(1:length(Time),400) ##to make it fast for example look at only 400\n plot(Time[o],CD4[o],pch=\".\",main=\"Running Mean\")\nb <- c(-2,1,3) - 0.5\ne <- b + 1\nfor(i in 1:length(b)){ \n abline(v=c(b[i],e[i]),pch=2)\n oo <- o[Time[o]>=b[i] & Time[o]<=e[i]]\nsapply(oo,function(i) points(Time[oo],CD4[oo],pch=1))\nlines(range(Time[oo]),rep(mean(CD4[oo]),2))\n}\naux <- ksmooth(Time[o],CD4[o],kernel=\"box\",bandwidth=1,x.points=unique(Time[o])) ##box is default!\nlines(aux$x,aux$y)\ndev.off()\n###Figures 5\n##kernel smoother\npostscript(\"Plots/plot-02-05.ps\",horizontal=T)\nplot(Time[o],CD4[o],main=\"Kernel Smoother\",pch=\".\")\naux <- ksmooth(Time[o],CD4[o],kernel=\"normal\",bandwidth=1,x.points=unique(Time[o]))\nlines(aux$x,aux$y)\ndev.off()\n\n###Figure 6\npostscript(\"Plots/plot-02-06.ps\",horizontal=T)\no <- sample(1:length(Time),400) ##to make it fast for example look at only 400\nxx <- sort(Time[o])\naux11 <- ksmooth(xx,c(1,rep(0,length(o)-1)),kernel=\"normal\",bandwidth=1,x.points=unique(xx)) \nplot(aux11$x,aux11$y,type=\"l\",xlab=\"Time\",ylab=\"Weights\",main=\"Kernels\",col=2)\nrug(xx)\noo<- aux11$y>6.030458e-06\npoints(aux11$x[oo],aux11$y[oo],lty=2,pch=\"x\",cex=0.5)\naux12 <- ksmooth(xx,c(1,rep(0,length(o)-1)),kernel=\"box\",bandwidth=1,x.points=unique(xx))\nlines(aux12$x,aux12$y,lty=2,col=2)\noo <- aux12$y>6.030458e-06\npoints(aux12$x[oo],aux12$y[oo],lty=2,pch=\"x\",cex=0.5)\n##\naux21 <- ksmooth(xx,c(rep(0,round(length(o)/2)),1,rep(0,length(o)-round(length(o)/2)-1)),kernel=\"normal\",bandwidth=1,x.points=unique(xx))\nlines(aux21$x,aux21$y,type=\"l\",col=3)\noo<- aux21$y>6.030458e-06\npoints(aux21$x[oo],aux21$y[oo],lty=2,pch=\"x\",cex=0.5)\naux22 <- ksmooth(xx,c(rep(0,round(length(o)/2)),1,rep(0,length(o)-round(length(o)/2)-1)),kernel=\"box\",bandwidth=1,x.points=unique(xx))\nlines(aux22$x,aux22$y,lty=2,col=3)\noo<- aux22$y>6.030458e-06\npoints(aux22$x[oo],aux22$y[oo],lty=2,pch=\"x\",cex=0.5)\n##\naux31 <- ksmooth(xx,c(rep(0,round(length(o)*.9)),1,rep(0,length(o)-round(length(o)*.9)-1)),kernel=\"normal\",bandwidth=1,x.points=unique(xx))\nlines(aux31$x,aux31$y,type=\"l\",col=4)\noo<- aux31$y>6.030458e-06\npoints(aux31$x[oo],aux31$y[oo],lty=2,pch=\"x\",cex=0.5)\naux32 <- ksmooth(xx,c(rep(0,round(length(o)*.9)),1,rep(0,length(o)-round(length(o)*.9)-1)),kernel=\"box\",bandwidth=1,x.points=unique(xx))\nlines(aux32$x,aux32$y,lty=2,col=4)\noo<- aux32$y>6.030458e-06\npoints(aux32$x[oo],aux32$y[oo],lty=2,pch=\"x\",cex=0.5)\ndev.off()\n\n\ndetach(\"CD4.data\")\n", "meta": {"hexsha": "930bc96d966cbcbd64a5c18563747f824007e27d", "size": 3643, "ext": "r", "lang": "R", "max_stars_repo_path": "pages/754/code-02.r", "max_stars_repo_name": "igrabski/rafalab.github.io", "max_stars_repo_head_hexsha": "2f27ea0d9e0b8a2342bb851ae7415ba3268fd00f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2016-08-17T23:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T19:21:02.000Z", "max_issues_repo_path": "pages/754/code-02.r", "max_issues_repo_name": "igrabski/rafalab.github.io", "max_issues_repo_head_hexsha": "2f27ea0d9e0b8a2342bb851ae7415ba3268fd00f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-08-18T00:41:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T22:35:40.000Z", "max_forks_repo_path": "pages/754/code-02.r", "max_forks_repo_name": "igrabski/rafalab.github.io", "max_forks_repo_head_hexsha": "2f27ea0d9e0b8a2342bb851ae7415ba3268fd00f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2016-08-17T22:17:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T12:17:08.000Z", "avg_line_length": 39.597826087, "max_line_length": 139, "alphanum_fraction": 0.6568762009, "num_tokens": 1404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7113347392287833}} {"text": "# Reference: \"Robust Principal Component Analysis?\" https://arxiv.org/pdf/0912.3599.pdf\n\n# sum(abs(X))\none_norm = function(X)\n{\n if (is.ddmatrix(X))\n {\n ret = .Call(R_one_norm, X@Data)\n allreduce(ret)\n }\n else\n .Call(R_one_norm, X)\n}\n\n\n\n## \\mathcal{S} from the paper - sign(X) * pmax(abs(X) - tau, 0)\nshrink_op = function(X, tau)\n{\n # NOTE: this modifies the memory in place, which is potentially very dangerous\n if (is.ddmatrix(X))\n .Call(R_shrink_op, X@Data, tau)\n else\n .Call(R_shrink_op, X, tau)\n}\n\n\n\n## \\mathcal{D} from the paper\nsv_thresh = function(X, tau)\n{\n decomp = La.svd(X)\n \n sigma = decomp$d\n shrink_op(sigma, tau)\n U = decomp$u\n Vt = decomp$vt\n \n U %*% (sigma * Vt)\n}\n\n\n\n#' robpca\n#' \n#' Implementation of the robust pca algorithm.\n#' \n#' @description\n#' The optimization problem is solved by an alternating directions technique.\n#' \n#' @param M\n#' The input data, stored as a numeric matrix or ddmatrix.\n#' @param delta\n#' Numeric termination criteria. A smaller (closer to 0) value will require more\n#' iterations. See the summary following the Algorithm 1 listing in the\n#' referenced paper for details.\n#' @param maxiter\n#' Maximum number of iterations. Should at least be a few hundred.\n#' \n#' @references\n#' Candes, E.J., Li, X., Ma, Y. and Wright, J., 2011. Robust principal component\n#' analysis?. Journal of the ACM (JACM), 58(3), p.11.\n#' \n#' @examples\n#' \\dontrun{\n#' m = 10\n#' n = 3\n#' M = matrix(rnorm(m*n), m)\n#' robsvd(M)\n#' }\n#' \n#' @author\n#' Drew Schmidt\n#' \n#' @export\nrobpca = function(M, delta=1e-7, maxiter=1000)\n{\n ### I love dynamic typing\n assert.type(delta, \"numeric\")\n assert.posint(maxiter)\n \n if (class(M) != \"ddmatrix\")\n {\n M <- as.matrix(M)\n \n if (!is.double(M))\n storage.mode(M) <- \"double\"\n }\n \n \n ### the actual work\n n1 = nrow(M)\n n2 = ncol(M)\n \n lambda = 1/sqrt(max(n1, n2))\n \n mu = 0.25 * n1*n2 / one_norm(M)\n \n if (is.ddmatrix(M))\n {\n ictxt = ICTXT(M)\n S = pbdDMAT::ddmatrix(0, n1, n2, ICTXT=ictxt)\n Y = pbdDMAT::ddmatrix(0, n1, n2, ICTXT=ictxt)\n }\n else\n {\n S = matrix(0, n1, n2)\n Y = matrix(0, n1, n2)\n }\n \n conv = FALSE\n iter = 0L\n \n ub = delta * norm(M, \"F\")\n \n while (!conv && iter < maxiter)\n {\n if (iter == 0)\n L = sv_thresh(M, 1/mu)\n else\n L = sv_thresh(M - S + Y, 1/mu)\n \n tmp = M - L\n S = tmp + Y\n shrink_op(S, lambda/mu)\n \n tmp = tmp - S\n Y = Y + tmp\n \n term = norm(tmp, \"F\")\n conv = (term <= ub)\n iter = iter + 1L\n }\n \n info = list(iterations=iter, converged=iter 1 && a[i - 1] >= a[i]) i <- i - 1\n if (i == 1) {\n NULL\n } else {\n j <- i\n k <- n\n while (j < k) {\n s <- a[j]\n a[j] <- a[k]\n a[k] <- s\n j <- j + 1\n k <- k - 1\n }\n s <- a[i - 1]\n j <- i\n while (a[j] <= s) j <- j + 1\n a[i - 1] <- a[j]\n a[j] <- s\n a\n }\n}\n\nperm <- function(n) {\n e <- NULL\n a <- 1:n\n repeat {\n e <- cbind(e, a)\n a <- next.perm(a)\n if (is.null(a)) break\n }\n unname(e)\n}\n", "meta": {"hexsha": "fcb81e0b0a0ea39442048ba7584418d59f292f57", "size": 522, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Permutations/R/permutations-1.r", "max_stars_repo_name": "mullikine/RosettaCodeData", "max_stars_repo_head_hexsha": "4f0027c6ce83daa36118ee8b67915a13cd23ab67", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Permutations/R/permutations-1.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Permutations/R/permutations-1.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5, "max_line_length": 46, "alphanum_fraction": 0.3314176245, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7107688626255053}} {"text": "#' Calculation of theortical quantile (Quantile-Quantile Plot)\n#'\n#' @param y data sample\n#' @export\n#' @return Part of the qqnorm generic function\n#' @examples\n#' set.seed(123)\n#' test=lm(rnorm(100)~rnorm(100)+100)\n#' qq.function(test$residuals)\n\nqq.function=function(y){\n n=length(y)\n r=order(order(y))\n if(n>10){p=(r-1/2)/n}else{p=(r-3/8)/(n+1/4)}\n qqnorm.val=qnorm(p)\n return(qqnorm.val)\n}\n", "meta": {"hexsha": "97ef72feb0f2faf7d3a41d696f07f9d012173048", "size": 399, "ext": "r", "lang": "R", "max_stars_repo_path": "R/qq.function.r", "max_stars_repo_name": "SwampThingPaul/AnalystHelper", "max_stars_repo_head_hexsha": "0edc70df3a1e578ac97d15505dc46be982d1ac63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/qq.function.r", "max_issues_repo_name": "SwampThingPaul/AnalystHelper", "max_issues_repo_head_hexsha": "0edc70df3a1e578ac97d15505dc46be982d1ac63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/qq.function.r", "max_forks_repo_name": "SwampThingPaul/AnalystHelper", "max_forks_repo_head_hexsha": "0edc70df3a1e578ac97d15505dc46be982d1ac63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1666666667, "max_line_length": 62, "alphanum_fraction": 0.664160401, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7107392116738972}} {"text": "\ncurve(expr = dnorm(x, mean= 0,sd = 1), from = -4, to = 4, col = \"red\", lwd = 3.5,ylab=\"\",xlab=\"\",xaxt='n',yaxt='n')\ncurve(expr = dt(x, df = 1), from = -4, to = 4, col = \"red\", lwd = 3.5,ylab=\"\",xlab=\"\",xaxt='n',yaxt='n')\n\n#a mixture\nmyvar = 1\ncurve(expr = 0.25*dnorm(x, mean= 0,sd = sqrt(0.01*myvar)), ylim=c(0,1.8),from = -4, to = 4, col = \"red\", lwd = 3.5,ylab=\"\",xlab=\"\",xaxt='n',yaxt='n')\ncurve(expr = 0.25*dnorm(x, mean= 0,sd = sqrt(0.1*myvar)), from = -4, to = 4, col = \"red\", lwd = 3.5,ylab=\"\",xlab=\"\",xaxt='n',yaxt='n',add=TRUE)\ncurve(expr = 0.25*dnorm(x, mean= 0,sd = myvar), from = -4, to = 4, col = \"red\", lwd = 3.5,ylab=\"\",xlab=\"\",xaxt='n',yaxt='n',add=TRUE)\ncurve(1+x*4000, from = 0.0, to = 0.01, xname = \"x\", col = \"red\", lwd = 3.5,ylab=\"\",xlab=\"\",xaxt='n',yaxt='n',add=TRUE)\n\n\nlibrary(nimble)\ncurve(expr = ddexp(x), from = -4, to = 4, col = \"red\", lwd = 3.5,ylab=\"\",xlab=\"\",xaxt='n',yaxt='n')\n\nlibrary(EnvStats)\ncurve(expr = dnormMix(x, mean1 = 0, sd1 = 10, mean2 = 0, sd2 = 1, p.mix = 0.5), from = -4, to = 20, col = \"red\", lwd = 3.5,ylab=\"\",xlab=\"\",xaxt='n',yaxt='n')\n\ncurve(expr = dnormMix(x, mean1 = 0, sd1 = 10, mean2 = 0, sd2 = 1, mean3 = 0, sd3 = 1, p.mix = 0.5), from = -4, to = 20, col = \"red\", lwd = 3.5,ylab=\"\",xlab=\"\",xaxt='n',yaxt='n')\n", "meta": {"hexsha": "c7a577c21b746e81ed0ae728d6146d8bc5df5bcc", "size": 1269, "ext": "r", "lang": "R", "max_stars_repo_path": "distributions.r", "max_stars_repo_name": "QTL-rocks/Plots", "max_stars_repo_head_hexsha": "5959018e5b3a86cbc2e431b0f26863b8df6aaf74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distributions.r", "max_issues_repo_name": "QTL-rocks/Plots", "max_issues_repo_head_hexsha": "5959018e5b3a86cbc2e431b0f26863b8df6aaf74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distributions.r", "max_forks_repo_name": "QTL-rocks/Plots", "max_forks_repo_head_hexsha": "5959018e5b3a86cbc2e431b0f26863b8df6aaf74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-05T09:44:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-05T09:44:03.000Z", "avg_line_length": 63.45, "max_line_length": 179, "alphanum_fraction": 0.5374310481, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7107392099962363}} {"text": "################################################################################\n#\n#'\n#' Function to calculate the design effect of a stepped wedge cluster randomised\n#' study.\n#'\n#' @param k Number of steps in the stepped wedge study\n#' @param b Number of baseline measurements\n#' @param t Number of measurements after each step\n#' @param icc Intracluster correlation coefficient (\\code{ICC})\n#' @param size cluster size\n#'\n#' @return A numeric value of the design effect of a stepped wedge cluster\n#' ranomised study\n#'\n#' @examples\n#'\n#' get_deff_swedge(k = 2, b = 1, t = 1, icc = 0.034, size = 192)\n#'\n#' @export\n#'\n#\n################################################################################\n\nget_deff_swedge <- function(k, b, t, icc, size) {\n\n deff <- ((1 + icc * (k * t * size + b * size - 1)) / (1 + icc * (0.5 * (k * t * size) + b * size - 1))) * ((3 * (1 - icc)) / ((2 * t) * (k - 1 / k)))\n\n return(deff)\n}\n\n\n################################################################################\n#\n#'\n#' Function to calculate sample size requirements for a stepped wedge cluster\n#' randomised study.\n#'\n#' @param z1 The z-score indicating level of significance (confidence interval).\n#' Default at 1.96 for 95\\% confidence interval.\n#' @param z2 desired power. Default at 0.84 for 80\\% power.\n#' @param p1 Expected proportion for control group.\n#' @param p2 Expected proportion for intervention group\n#' @param deff Design effect of a stepped wedge cluster randomised study\n#'\n#' @return A numeric value of sample size needed for a stepped wedge cluster\n#' ranomised study\n#'\n#' @examples\n#'\n#' get_ss_swedge(z1 = 1.96, z2 = 0.84,\n#' p1 = 0.2, p2 = 0.15,\n#' deff = get_deff_swedge(k = 2, b = 1, t = 1,\n#' icc = 0.034, size = 192))\n#'\n#' @export\n#'\n#\n################################################################################\n\nget_ss_swedge <- function(z1 = 1.96, z2 = 0.84, p1, p2, deff) {\n\n n1 <- ((z1 + z2) ^ 2) * ((p1 * (1 - p1)) + (p2 * (1 - p2))) / (p1 - p2) ^ 2\n\n n <- n1 * 2 * deff\n\n return(n)\n}\n", "meta": {"hexsha": "f910af688460a450069a2c15e0d852868a1d45b1", "size": 2107, "ext": "r", "lang": "R", "max_stars_repo_path": "R/stepped_wedge.r", "max_stars_repo_name": "validmeasures/sampsizer", "max_stars_repo_head_hexsha": "801108c9c131b895465f3f328f04f642721953bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-25T11:46:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-25T11:46:49.000Z", "max_issues_repo_path": "R/stepped_wedge.r", "max_issues_repo_name": "validmeasures/sampsizser", "max_issues_repo_head_hexsha": "801108c9c131b895465f3f328f04f642721953bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/stepped_wedge.r", "max_forks_repo_name": "validmeasures/sampsizser", "max_forks_repo_head_hexsha": "801108c9c131b895465f3f328f04f642721953bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5362318841, "max_line_length": 151, "alphanum_fraction": 0.5040341718, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7799929053683039, "lm_q1q2_score": 0.7107137130873599}} {"text": "\nR version 3.0.0 (2013-04-03) -- \"Masked Marvel\"\nCopyright (C) 2013 The R Foundation for Statistical Computing\nPlatform: i386-w64-mingw32/i386 (32-bit)\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n#formulas, equations and notation from http://homeweb2.unifr.ch/hungerbu/pub/sonnenuhr/sundial.ps\n# and by the paper of C. Blatter (http://dz-srv1.sub.uni-goettingen.de/sub/digbib/loader?did=D241775)\n \nepsilon=23.45*2*pi/360\nalpha =78.5 *2*pi/360\nkappa =0.016722\n\nmu<-function(t,epsilon,alpha,kappa) {\nzaehl= -sin(delta(t,kappa))+tan(epsilon/2)^2*sin(2*(t-alpha)+delta(t,kappa))\nnenn = cos(delta(t,kappa))+tan(epsilon/2)^2*cos(2*(t-alpha)+delta(t,kappa))\nreturn( atan(zaehl/nenn) )\n}\n\n# approximation by Blatter\npsi<-function(t) {\n return(t+delta(t))\n }\n \n delta<-function(t,kappa) {\n return( 2*sin(t)*kappa+5/4*sin(2*t)*kappa^2 )\n }\n \n png(filename=\"Equation of time.jpg\", width=1024, height=768, pointsize=12)\n par(bg=\"whitesmoke\")\n time=seq(-0.6,2*pi+0.4,length=365+(0.6+0.4)/(2*pi)*365)\n da<-paste(\"1.\",as.character(seq(1,12,by=2)),\".07\",sep=\"\")\n da<-as.Date(c(da,\"1.1.08\"),\"%d.%m.%y\")\n #umrechungsfaktor: 24h=2*pi\n plot(time,mu(time,epsilon,alpha,kappa)*24*60/(2*pi),type=\"l\",col=\"red\",xlab=\"Tag\",ylab=\"Time in Minutes\",main=\"Equation of time: true solar time - mean solar time\",cex.main=1.5,lwd=3,xaxt=\"n\",xaxs=\"i\",xlim=range(time))\n lines(time,mu(time,epsilon=0,alpha,kappa)*24*60/(2*pi),lwd=2,col=\"navy\",lty=\"dotdash\")\n lines(time,mu(time,epsilon,alpha,kappa=0)*24*60/(2*pi),lwd=2,col=\"purple\",lty=\"dashed\")\n #grid\n abline(h=c(-15,-10,-5,5,10,15),lty=\"dotted\",col=\"grey\")\n abline(h=0,lty=\"solid\",col=\"grey33\")\n tage=cumsum(c(0,31,28,31,30,31,30,31,31,30,31,30,31))/365-3/365\n abline(v=tage*2*pi,lty=\"dotted\",col=\"grey\")\n axis(1,at=seq(0,2*pi,length=7)-3*2*pi/365,labels=as.character(da,\"1. %b\"))\n legend(x=5.5,y=-10.9,legend=c(\"Equation of time\",\"Ecliptic\",\"Earth Orbit\"),col=c(\"red\",\"navy\",\"purple\"),lwd=c(3,2,2),lty=c(\"solid\",\"dotdash\",\"dashed\"))\n dev.off()\n\n", "meta": {"hexsha": "1bd5440106650499f0f841116a38e9e40f169fa7", "size": 2408, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/eot_plot.r", "max_stars_repo_name": "kotp/equationoftime", "max_stars_repo_head_hexsha": "bcbc2daacc41db3d2122bb5ef7e9919005559aa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/eot_plot.r", "max_issues_repo_name": "kotp/equationoftime", "max_issues_repo_head_hexsha": "bcbc2daacc41db3d2122bb5ef7e9919005559aa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/eot_plot.r", "max_forks_repo_name": "kotp/equationoftime", "max_forks_repo_head_hexsha": "bcbc2daacc41db3d2122bb5ef7e9919005559aa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5172413793, "max_line_length": 221, "alphanum_fraction": 0.6881229236, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.710713700004864}} {"text": "euclidean <- function(a, b) {\n return (sqrt(sum((a - b) ^ 2)))\n}\n\nkNN <- function(dataset, points, k, dist = euclidean) {\n answer <- array(dim=c(length(points[,1])))\n \n for (i in 1:length(points[,1])) {\n distance <- array(dim=dim(dataset)[1])\n for (j in 1:dim(dataset)[1]) {\n distance[j] <- dist(dataset[j, 3:4], points[i,])\n }\n sortedDataset <- dataset[order(distance),]\n \n classesCount <- c(0, 0, 0)\n names(classesCount) = unique(iris$Species)\n for (j in 1:k) {\n classesCount[sortedDataset$Species[j]] <- classesCount[sortedDataset$Species[j]] + 1\n }\n answer[i] = names(which.max(classesCount))[1]\n }\n \n return (answer)\n}\n\nfast_cvloo_knn <- function() {\n maxK <- length(iris[,1]) - 1\n classes = unique(iris$Species)\n \n ans <- rep(x = 0, times = maxK)\n for (i in 1:length(iris[,1])) {\n # for (i in 1:10) {\n cat(\"\\r\", \"Processing sample \", i, \" of \", length(iris[,1]))\n dataset <- iris[-i,]\n # print(dataset)\n distance <- array(dim=c(length(dataset[,1])))\n for (j in 1:(length(dataset[,1]))) {\n distance[j] <- euclidean(dataset[j, 1:4], iris[i, 1:4])\n }\n sortedDataset <- dataset[order(distance),]\n \n classesCount <- rep(x = 0, times = length(classes))\n names(classesCount) = classes\n for (j in 1:maxK) {\n classesCount[sortedDataset$Species[j]] <- classesCount[sortedDataset$Species[j]] + 1\n \n classForCurrentK = names(which.max(classesCount))[1]\n if (classForCurrentK == iris$Species[i]) {\n ans[j] = ans[j] + 1\n }\n }\n \n }\n cat(\"\\n\")\n # for (i in 1:length(ans)) {\n # \n # ans[i] = ans[i] / length(iris[,1] - 1)\n # }\n \n return (ans)\n}\n\n\n\nfast_cvloo_kwnn <- function() {\n maxK <- 149\n classes = unique(iris$Species)\n qs <- seq(from = 0.0, to = 1.0, by = 0.05)\n \n ans <- array(0L, dim = c(maxK, length(qs)))\n for (i in 1:length(iris[,1])) { # samples\n cat(\"\\r\", \"Processing sample \", i, \" of \", length(iris[,1]))\n dataset <- iris[-i,]\n distance <- array(dim=c(length(dataset[,1])))\n for (j in 1:(length(dataset[,1]))) {\n distance[j] <- euclidean(dataset[j, 1:4], iris[i, 1:4])\n }\n sortedDataset <- dataset[order(distance),]\n distance <- sort(distance)\n \n classesCount <- array(0L, dim = c(length(classes), length(qs)))\n dimnames(classesCount) = list(classes)\n for (j in 1:maxK) { # k's\n index <- 1\n for (q in qs) {\n classesCount[sortedDataset$Species[j],index] <- classesCount[sortedDataset$Species[j],index] + (q ^ j)\n classForCurrentK = names(which.max(classesCount[,index]))[1]\n \n if (classForCurrentK == paste(iris$Species[i])) {\n ans[j,index] = ans[j,index] + 1\n }\n index <- index + 1\n }\n }\n index <- index + 1\n }\n cat(\"\\n\")\n \n # for (i in 1:length(ans)) {\n # \n # ans[i] = ans[i] / (length(iris[,1]) - 1)\n # }\n \n return (ans)\n}\n\nknn_accuracy = fast_cvloo_knn()\nkwnn_accuracy = fast_cvloo_kwnn()\n\ncat(\"Best accuracy for knn: \", max(knn_accuracy) / length(iris[,1]), \";\\nBest accuracy for weighted knn:\", max(kwnn_accuracy) / length(iris[,1]))\n\n", "meta": {"hexsha": "9f3ff9e78dd62ec1cb2bdebc3ab8b063942b7d1f", "size": 3116, "ext": "r", "lang": "R", "max_stars_repo_path": "1 - Nearest neighbors algorithm/knn-vs-kwnn.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1 - Nearest neighbors algorithm/knn-vs-kwnn.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1 - Nearest neighbors algorithm/knn-vs-kwnn.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8214285714, "max_line_length": 145, "alphanum_fraction": 0.567394095, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7106514415243875}} {"text": "## Dale W.R. Rosenthal, 2018\n## You are free to distribute and use this code so long as you attribute\n## it to me or cite the text.\n## The legal disclaimer in _A Quantitative Primer on Investments with R_\n## applies to this code. Use or distribution without these comment lines\n## is forbidden.\nlibrary(MASS)\nlibrary(xts)\nlibrary(quantmod)\nlibrary(Quandl)\nlibrary(PortfolioAnalytics)\nlibrary(ROI)\nlibrary(ROI.plugin.glpk)\nlibrary(ROI.plugin.quadprog)\n\n## risk-free rate (for example purposes)\nrf <- 0.01\n\netf.symbols <- c(\"SPY\", \"IWM\", \"AGG\", \"FEZ\", \"ACWI\", \"IYR\")\nadj.close <- 6 # 6th field is adjusted close\netf.prices <- getSymbols(etf.symbols[1], source=\"yahoo\",\n auto.assign=FALSE, return.class=\"xts\")[,adj.close]\nfor (i in 2:length(etf.symbols)) {\n etf.tmp <- getSymbols(etf.symbols[i], source=\"yahoo\",\n auto.assign=FALSE, return.class=\"xts\")[,adj.close]\n etf.prices <- cbind(etf.prices, etf.tmp)\n}\ncolnames(etf.prices) <- etf.symbols\netf.rets <- diff(log(etf.prices))[\"2012/\"]\n\ncommodity.symbols <- c(\"WTI\", \"Natgas\", \"AU\", \"CU\", \"Corn\")\nsettle <- \"Settle\" # settle field is labeled\ncommodity.tickers <- c(\"CHRIS/CME_CL1\", \"CHRIS/CME_NG1\", \"CHRIS/CME_GC1\",\n \"CHRIS/CME_HG1\", \"CHRIS/CME_C1\")\ncommodity.prices <- Quandl(commodity.tickers[1], type=\"xts\")[,settle]\nfor (i in 2:length(commodity.symbols)) {\n commodity.tmp <- Quandl(commodity.tickers[i], type=\"xts\")[,settle]\n commodity.prices <- cbind(commodity.prices, commodity.tmp)\n}\ncolnames(commodity.prices) <- commodity.symbols\n\nall.returns.tmp <- diff(log(cbind(etf.prices,commodity.prices)))[\"2012/\"]\nall.returns <- na.omit(all.returns.tmp)\n\n## set up portfolio with objective and constraints\nn.assets <- length(colnames(all.returns))\nport.spec <- portfolio.spec(assets = colnames(all.returns))\nport.spec <- add.objective(portfolio=port.spec, type=\"risk\", name=\"StdDev\")\nport.spec <- add.objective(portfolio=port.spec, type=\"return\", name=\"mean\")\nport.spec <- add.constraint(portfolio=port.spec, type=\"full_investment\")\nport.spec <- add.constraint(portfolio=port.spec, type=\"box\", min=-1, max=1)\n\n## map out the efficient frontier (for variance risk)\neff.frontier <- create.EfficientFrontier(R=all.returns, portfolio=port.spec,\n n.portfolios=100, type=\"mean-StdDev\")\n\n## daily Sharpe ratio\nsharpe.ratios <- (eff.frontier$frontier[,\"mean\"]-rf/250)/eff.frontier$frontier[,\"StdDev\"]\nmax.sharpe.ratio <- sharpe.ratios[sharpe.ratios == max(sharpe.ratios)]\noptimal.port.name <- names(max.sharpe.ratio)\noptimal.mean <- eff.frontier$frontier[optimal.port.name,\"mean\"]\noptimal.sd <- eff.frontier$frontier[optimal.port.name,\"StdDev\"]\n\nn.trading.days.per.year <- 252\nprint(sprintf(\"Optimal Sharpe Ratio: %f\", max.sharpe.ratio*sqrt(n.trading.days.per.year)))\nprint(sprintf(\"Optimal E(port return): %f\", optimal.mean*n.trading.days.per.year))\nprint(sprintf(\"Optimal sd(port return): %f\", optimal.sd*sqrt(n.trading.days.per.year)))\nprint(\"Optimal weights\")\nprint(eff.frontier$frontier[optimal.port.name,(1:n.assets)+3])\n", "meta": {"hexsha": "1115bc9ec4cefd4f5aea1d223e58aa2ec42e4f72", "size": 3093, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch9-exercises.r", "max_stars_repo_name": "bmoretz/Quantitative-Investments", "max_stars_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-26T05:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T21:50:54.000Z", "max_issues_repo_path": "Quantitative Primer/samples/ch9-exercises.r", "max_issues_repo_name": "bmoretz/Quantitative-Investments", "max_issues_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quantitative Primer/samples/ch9-exercises.r", "max_forks_repo_name": "bmoretz/Quantitative-Investments", "max_forks_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-03T09:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:50:55.000Z", "avg_line_length": 44.1857142857, "max_line_length": 90, "alphanum_fraction": 0.6983511154, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.7106479123492033}} {"text": "## 2. Combine Vectors ##\n\nharvard <- c(1,1,1,1,3)\nstanford <- c(2,9,3,4,10)\nMIT <- c(3,3,2,2,1)\ncambridge <- c(4,2,6,13,48)\noxford <- c(5,7,12,9,15)\ncolumbia <- c(6,13,13,12,4)\n\nuni_vector <- c(harvard, stanford, MIT, cambridge, oxford, columbia)\n\n## 3. Creating a Matrix ##\n\nuni_vector <- c(harvard, stanford, MIT, cambridge, oxford, columbia)\n\nuni_matrix <- matrix(uni_vector, nrow=6, ncol=5, byrow = TRUE)\nprint(uni_matrix)\n\n## 4. Vector & Matrix Data Types ##\n\ncolumbia_types <- c(\"columbia\",6,13,13,12,4)\ntype <- class(columbia_types)\nprint(type)\n\n## 5. Naming Rows And Columns ##\n\ncategories <- c(\"world_rank\",\"quality_of_education\",\"influence\",\"broad_impact\",\"patents\")\nuniversities <- c(\"Harvard\",\"Stanford\",\"MIT\",\"Cambridge\",\"Oxford\",\"Columbia\")\n\nrownames(uni_matrix) <- universities\ncolnames(uni_matrix) <- categories\nnamed_uni_matrix <- uni_matrix\nprint(named_uni_matrix)\n\n## 6. Finding the dimensions of the matrix ##\n\ntuition <- c(43280,45000,45016,49350,28450,55161)\n\nprint(dim(uni_matrix))\nprint(length(tuition))\nequality <- dim(uni_matrix)[1] == length(tuition)\nprint(equality)\n\n## 7. Creating new columns and rows ##\n\ntuition <- c(43280,45000,45016,49350,28450,55161)\n\nuni_matrix <- cbind(uni_matrix, tuition)\nprint(uni_matrix)\n\n## 8. Subsetting And Indexing A Matrix By Element ##\n\noxford_influence <- uni_matrix[\"Oxford\",\"influence\"]\nstanford_impact <- uni_matrix[\"Stanford\",\"broad_impact\"]\ncambridge_patents <- uni_matrix[\"Cambridge\",\"patents\"]\nMIT_world_rank <- uni_matrix[\"MIT\",\"world_rank\"]\n\n## 9. Subsetting a Matrix by Rows & Columns ##\n\nworld_rank <- uni_matrix[,\"world_rank\"]\ncolumbia <- uni_matrix[\"Columbia\",]\npatents <- uni_matrix[,\"patents\"]\n\n## 10. Sorting a Matrix ##\n\ntop_edu <- sort(uni_matrix[,\"quality_of_education\"])\nlow_cost <- sort(uni_matrix[,\"tuition\"])\n\n## 11. Sorting Then Previewing Data ##\n\ntop_edu <- sort(uni_matrix[,\"quality_of_education\"])\nlow_cost <- sort(uni_matrix[,\"tuition\"])\n\ntop_two_edu <- head(top_edu, 2)\ntwo_low_cost <- head(low_cost, 2)", "meta": {"hexsha": "c98d7f2e466ce5bb6c818cada783f8738a80a808", "size": 1998, "ext": "r", "lang": "R", "max_stars_repo_path": "R Fundamentals/Introduction to Matrices-312.r", "max_stars_repo_name": "nairachyut/dataquest-projects", "max_stars_repo_head_hexsha": "0807564bb35f39df21a84c8d97ab8eb3a428fb19", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-23T20:02:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T13:01:20.000Z", "max_issues_repo_path": "R Fundamentals/Introduction to Matrices-312.r", "max_issues_repo_name": "nairachyut/dataquest-projects", "max_issues_repo_head_hexsha": "0807564bb35f39df21a84c8d97ab8eb3a428fb19", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R Fundamentals/Introduction to Matrices-312.r", "max_forks_repo_name": "nairachyut/dataquest-projects", "max_forks_repo_head_hexsha": "0807564bb35f39df21a84c8d97ab8eb3a428fb19", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.64, "max_line_length": 89, "alphanum_fraction": 0.7132132132, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7103054562953134}} {"text": "## Exercício 10\r\n## Prof. James Hunter\r\n## from: https://rstudio.cloud/project/1181172\r\n## 28 de maio de 2020\r\n##\r\n## Simulação das Camisetas de Sustentare -- Uma Vez\r\n## Todos os dados totalmente inventados\r\n## Similaridade entre esta versão da Sustentare e a verdadeiro é 100% por acaso\r\n\r\n\r\nlibrary(tidyverse)\r\nlibrary(summarytools)\r\n\r\n## Variáveis Básicas (repetido da ex. 9)\r\n\r\npublico_ano1 <- 4000 #número total dos alunos/ex-alunos\r\nnovo_publico <- 250 #número novo de alunos por ano\r\ncusto_ano1 <- 32 #custo da camiseta estampada com logo e nome em reais\r\ninflacao <- .05 #aumento de custos anual (inflação)com\r\nmarkup <- 1 #fator para adicionar ao custo para determinar preço de venda\r\n#ex. 1 = 100%\r\ndesenv_ano1 <- 20000 # cobrança em ano 1 para desenvolver produto, mktg, etc.\r\nanos <- 5L #número de anos para julgar se programa vale a pena\r\nmin_prop <- 0.15 # min e max proporções do público que vai comprar\r\nmax_prop <- 0.40\r\n\r\n# Número de Iterações\r\n\r\nn_sims <- 1000\r\n\r\n\r\n# Repositório dos Resultados\r\n# Guardar vazio\r\n\r\ntotal_camis <- tibble(sim = integer(n_sims),\r\n media_prop = double(n_sims),\r\n tot_compras = double(n_sims),\r\n tot_renda = double(n_sims),\r\n tot_lucro = double(n_sims))\r\n\r\n\r\n\r\n# Funcao do Modelo - Simulação Individual\r\n\r\ncamis_modelo <- function() {\r\n # colocar as variáveis num tibble\r\n \r\n camis <- tibble(desenv = numeric(length = anos), \r\n publico = numeric(length = anos),\r\n custo = numeric(length = anos),\r\n preco = numeric(length = anos),\r\n compras = numeric(length = anos),\r\n renda = numeric(length = anos),\r\n lucro = numeric(length = anos)) \r\n \r\n \r\n # Carregar camis com os valores\r\n \r\n camis$desenv[1] <- desenv_ano1\r\n \r\n ## Outras precisam loop\r\n \r\n for (i in 1:anos) {\r\n camis$publico[i] <- publico_ano1 + (i - 1) * novo_publico\r\n camis$custo[i] <- custo_ano1 * (1 + inflacao)^(i-1)\r\n camis$preco[i] <- camis$custo[i] * (1 + markup)\r\n }\r\n \r\n # variável probabilística -- qual proporção do público vai comprar\r\n # aleatórico entre 15% e 40%\r\n # usar distribuição uniforme -- runif()\r\n # premissa: que pode comprar mais de uma vez\r\n \r\n prop_compras <- runif(5, min = min_prop, max = max_prop)\r\n \r\n camis <- camis %>% \r\n mutate(compras = publico * prop_compras,\r\n renda = compras * preco,\r\n lucro = renda - desenv - custo * compras)\r\n \r\n # Calcular os Totais\r\n \r\n sum_camis <- camis %>% \r\n summarise(media_prop = mean(prop_compras),\r\n tot_compras = sum(compras),\r\n tot_renda = sum(renda),\r\n tot_lucro = sum(lucro))\r\n \r\n # Salvar os resultados\r\n \r\n return(sum_camis)\r\n}\r\n\r\n## Executar a Simulação\r\n\r\n# set.seed() para tudo mundo tem o mesmo resultado\r\n\r\nset.seed(42)\r\n\r\n# iniciar sum_camis para receber dados da função\r\n\r\nsum_camis <- tibble(sim = integer(n_sims),\r\n media_prop = double(n_sims),\r\n tot_compras = double(n_sims),\r\n tot_renda = double(n_sims),\r\n tot_lucro = double(n_sims))\r\n\r\n# Loop\r\n\r\ninicio_loop = Sys.time()\r\n\r\nfor (n in 1:n_sims){\r\n sum_camis <- camis_modelo() \r\n \r\n # Carregar resultados\r\n \r\n total_camis$sim[n] = n\r\n total_camis$media_prop[n] = sum_camis$media_prop\r\n total_camis$tot_compras[n] = sum_camis$tot_compras\r\n total_camis$tot_renda[n] = sum_camis$tot_renda\r\n total_camis$tot_lucro[n] = sum_camis$tot_lucro\r\n}\r\n\r\ntermino_loop = Sys.time()\r\n\r\nprint(glue::glue(\"Tempo de execução = \", round(termino_loop - inicio_loop, 2), \" segundos\"))\r\n\r\n## Analisar Resultados\r\n\r\nsummarytools::descr(total_camis[, 2:5], stats = c(\"mean\", \"sd\", \"min\", \"med\",\r\n \"max\", \"iqr\", \"cv\"))\r\n", "meta": {"hexsha": "eae7dddb38ec992a6eee93dc5d0d2f7e6cbfd22a", "size": 3857, "ext": "r", "lang": "R", "max_stars_repo_path": "exercicio_10.r", "max_stars_repo_name": "jameshunterbr/Sustentare_MAD_2020", "max_stars_repo_head_hexsha": "299a7f0af7e999e59cc53c57cf22618b6eb68092", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercicio_10.r", "max_issues_repo_name": "jameshunterbr/Sustentare_MAD_2020", "max_issues_repo_head_hexsha": "299a7f0af7e999e59cc53c57cf22618b6eb68092", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercicio_10.r", "max_forks_repo_name": "jameshunterbr/Sustentare_MAD_2020", "max_forks_repo_head_hexsha": "299a7f0af7e999e59cc53c57cf22618b6eb68092", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2196969697, "max_line_length": 93, "alphanum_fraction": 0.6074669432, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7103054544373525}} {"text": "#'@title calcCb\n#'\n#'@description Calculates the maximum block coefficient (\\code{Cb})\n#'(dimensionless) based on a ship's maximum displacement and and maximum draft.\n#'\n#'@param maxDisplacement Maximum ship displacement (vector of numericals, m^3)\n#'@param lwl Waterline length (vector of numericals, m) (see \\code{\\link{calclwl}})\n#'@param breadth Moulded breadth (vector of numericals, m)\n#'@param maxDraft Maximum summer load line draft (vector of numericals, m)\n#'\n#'@details\n#'The block coefficient is the ratio of the vessel's displacement and its\n#'volume, defined by its waterline length (\\code{lwl}), breadth, and draft:\n#'\\deqn{Cb=\\frac{displacement}{lwl*breadth*draft}}{Cb=displacement/(lwl*breadth*draft)}\n#'\n#'This function returns the maximum block coefficient (\\code{Cb}), which is the\n#'ratio of the vessel's maximum displacement and it's maximum volume, defined by\n#'its waterline length (\\code{lwl}), breadth, and maximum draft:\n#'\\deqn{Cb=\\frac{maxDisplacement}{lwl*breadth*maxDraft}}{Cb=maxDisplacement/(lwl*breadth*maxDraft)}\n#'\n#'@return \\code{Cb} (vector of numericals, dimensionless)\n#'\n#'@references\n#'\\href{https://www.man-es.com/marine/products/propeller-aft-ship}{MAN Energy\n#' Solutions. 2011. \"Basic Principles of Propulsion.\"}\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calclwl}}\n#'\\item \\code{\\link{calcCbw}}\n#'}\n#'\n#'@examples\n#'calcCb(c(80097.00,52382.04), c(218.75,209.25), c(32.25,32.2), c(13.6,11.5))\n#'\n#'@export\n\n\ncalcCb<- function(maxDisplacement, lwl, breadth, maxDraft){\n\n Cb <- pmin(1,\n maxDisplacement/(lwl*breadth*maxDraft)\n )\n return(Cb)\n\n}\n", "meta": {"hexsha": "3c3a6132ce28044aa4904ff8a10ac998f4532c8d", "size": 1604, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcCb.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipPowerModel/R/calcCb.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipPowerModel/R/calcCb.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 34.8695652174, "max_line_length": 99, "alphanum_fraction": 0.716957606, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7102006348080665}} {"text": "# Do growth accounting and prepare figures of results\n\n#########################################################################\n# Pull PWT into dataframe\ndata(\"pwt9.1\") # extract PWT data\n\n#########################################################################\n# Accounting calculation\n#########################################################################\np <- pwt9.1 # copy dataframe for manipulation\np$lngdppc <- round(log(p$rgdpna) - log(p$pop),digits=2) # create log GDP per capita\np$ky <- round(p$rnna/p$rgdpna,digits=2) # create K/Y ratio\np$acctky <- (.3/(1-.3))*log(p$ky) # just the K/Y part\np$accthc <- log(p$hc) + log(p$emp/p$emp) # just the labor/HC part\np$accttfp <- p$lngdppc - p$acctky - p$accthc # just the TFP part\n\ns <- p # save initial dataset for use later\n\n# Get initial values of TFP, HC, and KY terms from 1960\np <- p[which(p$year>1959),]\np$inittfp <- with(p, accttfp[year == \"1960\"][match(isocode, isocode[year == \"1960\"])])\np$inithc <- with(p, accthc[year == \"1960\"][match(isocode, isocode[year == \"1960\"])])\np$initky <- with(p, acctky[year == \"1960\"][match(isocode, isocode[year == \"1960\"])])\n\n# Calcualte the counterfactual series of GDP p.c. with KY only, TFP only, HC only\np$kyonly <- round(p$inittfp + p$inithc + p$acctky,digits=2)\np$hconly <- round(p$inittfp + p$accthc + p$initky,digits=2)\np$tfponly <- round(p$accttfp + p$inithc + p$initky,digits=2)\np$input <- round(p$inittfp + p$accthc + p$acctky,digits=2)\n\n# Grab data for only specific countries\nusa <- p[which(p$isocode %in% c(\"USA\")),]\ndeu <- p[which(p$isocode %in% c(\"DEU\")),]\nkor <- p[which(p$isocode %in% c(\"KOR\")),]\njpn <- p[which(p$isocode %in% c(\"JPN\")),]\nchn <- p[which(p$isocode %in% c(\"CHN\")),]\n\n#########################################################################\n# Figure for USA and KOR accounting showing CF log GDP per capita\n#########################################################################\n#,color = I('black'),\n#color_discrete_sequence= px.colors.sequential.Plasma_r\n\nfig <- plot_ly(usa, x = ~year, y = ~kyonly, name = 'K/Y only', type = 'scatter', \n mode = 'lines'\n )\nfig <- fig %>% add_trace(y = ~hconly, name = 'HC only',mode = 'lines')\nfig <- fig %>% add_trace(y = ~tfponly, name = 'Prod only',mode = 'lines')\nfig <- fig %>% add_trace(y = ~lngdppc, name = 'Actual GDP p.c.',mode = 'lines')\nfig <- layout(fig, title = list(text = 'Accounting for United States', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Log GDP per capita',range=c(9,11)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-account-usa\")\n\nfig <- plot_ly(kor, x = ~year, y = ~kyonly, name = 'K/Y only', type = 'scatter', mode = 'lines')\nfig <- fig %>% add_trace(y = ~hconly, name = 'HC only',mode = 'lines')\nfig <- fig %>% add_trace(y = ~tfponly, name = 'Prod only',mode = 'lines')\nfig <- fig %>% add_trace(y = ~lngdppc, name = 'Actual GDP p.c.',mode = 'lines')\nfig <- layout(fig, title = list(text = 'Accounting for South Korea', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Log GDP per capita'),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-account-kor\")\n\n#########################################################################\n# Create alternative figure with breakdown of growth rate by 10-year period\n#########################################################################\n\n# Get 10-year lags for accounting terms\ns <- \n s %>%\n group_by(isocode) %>%\n mutate(lag10.acctky = dplyr::lag(acctky, n = 10, default = NA))\ns <- \n s %>%\n group_by(isocode) %>%\n mutate(lag10.accthc = dplyr::lag(accthc, n = 10, default = NA))\ns <- \n s %>%\n group_by(isocode) %>%\n mutate(lag10.accttfp = dplyr::lag(accttfp, n = 10, default = NA))\ns <- \n s %>%\n group_by(isocode) %>%\n mutate(lag10.lngdppc = dplyr::lag(lngdppc, n = 10, default = NA))\n\n# Calculate 10-year growth rate of accounting terms\ns$g10.acctky <- round((s$acctky - s$lag10.acctky)/10,digits=4)\ns$g10.accthc <- round((s$accthc - s$lag10.accthc)/10,digits=4)\ns$g10.accttfp <- round((s$accttfp - s$lag10.accttfp)/10,digits=4)\ns$g10.lngdppc <- round((s$lngdppc - s$lag10.lngdppc)/10,digits=4)\n\ncomp <- s[which(s$isocode %in% c(\"USA\",\"CHN\",\"KOR\",\"JPN\",\"DEU\",\"GBR\")),]\ns <- s[which(s$isocode %in% c(\"USA\")),]\n\n#########################################################################\n# Figure for US growth rate breakdown\n#########################################################################\nfig <- plot_ly(s, x = ~year, y = ~g10.acctky, type = 'bar', name = 'K/Y growth')\nfig <- fig %>% add_trace(y = ~g10.accthc, name = 'HC growth')\nfig <- fig %>% add_trace(y = ~g10.accttfp, name = 'Prod growth')\nfig <- fig %>% layout(yaxis = list(title = '10-year growth contribution'), \n barmode = 'stack',\n xaxis = list(title = 'Year', tick0=1960, dtick=10),\n title = list(text = 'Growth accounting', x=0),\n hovermode=\"x unified\"\n )\napi_create(fig, filename = \"pwt-growth-acct-usa\")\n\n#########################################################################\n# Figure of growth rate of productivity for set of countries\n#########################################################################\nfig <- plot_ly(comp, x = ~year, y = ~g10.accttfp, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Productivity growth', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list(title = '10-year productivity growth rate'),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-growth-tfp-comp\")\n\n#########################################################################\n# Merge OECD R&D data with productivity growth data\n#########################################################################\n# Pull OECD into dataframe\nwork <- get_dataset(\"PERS_FUNC\")\n\n# Get log of R&D workers\nfte <- work\nfte <- fte[which(fte$SECTPERF %in% c(\"_T\")),]\nfte <- fte[which(fte$FUNCTION %in% c(\"RSE\")),]\nfte <- fte[which(fte$GENDER %in% c(\"_T\")),]\nfte <- fte[which(fte$MEASURE %in% c(\"FTE\")),]\nfte <- fte[which(fte$COUNTRY %in% c(\"USA\",\"JPN\",\"KOR\",\"CHN\",\"DEU\",\"GBR\")),]\nfte$lnrdworker <- log(fte$obsValue)\n\n# Calculate 10-year growth rate of R&D workers\nfte <- \n fte %>%\n group_by(COUNTRY) %>%\n mutate(lag10.lnrdworker = dplyr::lag(lnrdworker, n = 10, default = NA))\nfte$g10.lnrdworker <- (fte$lnrdworker - fte$lag10.lnrdworker)/10\n\n# Join the R&D worker data to the productivity growth data for set of countries\nmatch <- data.frame(comp$isocode,comp$g10.accttfp,comp$year,comp$pop,comp$accttfp)\ncolnames(match) <- c(\"COUNTRY\",\"g10.accttfp\",\"obsTime\",\"pop\",\"accttfp\")\nmatch$lnpop <- log(match$pop)\njoined <- merge(match,fte,by=c('COUNTRY','obsTime'))\n\n#########################################################################\n# Figure for R&D workers and growth in productivity\n#########################################################################\npal <- c('#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00','#ffff33')\npal <- setNames(pal, c(\"USA\",\"JPN\",\"KOR\",\"CHN\",\"DEU\",\"GBR\"))\nfig <- plot_ly(joined, x = ~lnrdworker, y = ~g10.accttfp, color = ~COUNTRY, \n type = 'scatter', mode = 'markers',colors = pal,\n hovertemplate = paste(\"
\",\n \"%{yaxis.title.text}: %{y:.2f}
\",\n \"%{xaxis.title.text}: %{x:.2f}
\")\n)\nfig <- layout(fig, title = list(text = 'Relationship of R&D work and prod growth', x=0),\n xaxis = list(title = 'Log R&D FTE workers'),\n yaxis = list(title = '10-year productivity growth rate'),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-oecd-rd-tfp\")\n\n#########################################################################\n# Figure for growth in R&D workers and growth in productivity\n#########################################################################\nfig <- plot_ly(joined, x = ~g10.lnrdworker, y = ~g10.accttfp, color = ~COUNTRY, \n type = 'scatter', mode = 'markers',colors = pal,\n hovertemplate = paste(\"
\",\"%{yaxis.title.text}: %{y:.2f}
\",\n \"%{xaxis.title.text}: %{x:.2f}
\")\n)\nfig <- layout(fig, title = list(text = 'Relationship of R&D growth and prod growth', x=0),\n xaxis = list(title = '10-year growth rate of R&D FTE'),\n yaxis = list(title = '10-year productivity growth rate'),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-oecd-rd-gtfp\")\n\n#########################################################################\n# Figure for level of R&D workers and level of productivity\n#########################################################################\nfig <- plot_ly(joined, x = ~lnrdworker, y = ~accttfp, color = ~COUNTRY, \n type = 'scatter', mode = 'markers',colors = pal,\n hovertemplate = paste(\"
\",\"%{yaxis.title.text}: %{y:.2f}
\",\n \"%{xaxis.title.text}: %{x:.2f}
\")\n)\nfig <- layout(fig, title = list(text = 'Relationship of R&D level and prod level', x=0),\n xaxis = list(title = 'Log R&D FTE'),\n yaxis = list(title = 'Log productivity'),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-oecd-level-rd\")", "meta": {"hexsha": "99caae3bea1d5c38c03892e0c72e4fd39ed6b635", "size": 9458, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Guide_PWT_Account.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/Guide_PWT_Account.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Guide_PWT_Account.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 49.2604166667, "max_line_length": 112, "alphanum_fraction": 0.515013745, "num_tokens": 2611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7101192428386707}} {"text": "#!/usr/bin/Rscript\n\n# Copyright © 2016 Martin Ueding \n# Licensed under the MIT license.\n\nrsurf = function(dim=3) {\n # Generate random vector components.\n x = rnorm(dim)\n\n # Normalize by the radius.\n r = sqrt(sum(x^2))\n y = x / r\n\n return(y)\n}\n\nrbulk = function(dim=3) {\n # Generate random vector components.\n x = rnorm(dim)\n\n # Normalize by the radius.\n r = sqrt(sum(x^2))\n x_normalized = x / r\n\n # Sample a new radius and adjust it for the Jacobian on that dimension.\n r_new = runif(1)^(1/dim)\n y = r_new * x_normalized\n\n return(y)\n}\n\n# Generate points and show them in a sensible fashion.\n\n# 2D Surface.\nsamples_2d_surf = replicate(100, rsurf(2))\nplot(samples_2d_surf[1,], samples_2d_surf[2,])\n\n# 3D Surface.\nsamples_3d_surf = replicate(2000, rsurf(3))\nx = samples_3d_surf[1,]\ny = samples_3d_surf[2,]\nz = samples_3d_surf[3,]\n\nplot(x, y)\n\nlambda = atan2(y, x)\nr = sqrt(x^2 + y^2)\nphi = atan2(z, r)\n\npx = 2 * sqrt(2) * cos(phi) * sin(lambda/2) / sqrt(1 + cos(phi) * cos(lambda/2))\npy = sqrt(2) * sin(phi) / sqrt(1 + cos(phi) * cos(lambda/2))\n\nplot(px, py)\n\n\n# 2D Bulk\nsamples_2d_bulk = replicate(2000, rbulk(2))\nplot(samples_2d_bulk[1,], samples_2d_bulk[2,])\n\n# 3D Bulk\nsamples_3d_bulk = replicate(2000, rbulk(3))\nplot(samples_3d_bulk[1,], samples_3d_bulk[2,])\n", "meta": {"hexsha": "77e3c08781de223664324b9ab9ca8bdc0a833209", "size": 1328, "ext": "r", "lang": "R", "max_stars_repo_path": "02/R/sphere.r", "max_stars_repo_name": "martin-ueding/exercides-2016", "max_stars_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02/R/sphere.r", "max_issues_repo_name": "martin-ueding/exercides-2016", "max_issues_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02/R/sphere.r", "max_forks_repo_name": "martin-ueding/exercides-2016", "max_forks_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0793650794, "max_line_length": 80, "alphanum_fraction": 0.6513554217, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7098911825664722}} {"text": "# Program to check if\n# the input number is\n# prime or not\n\n# take input from the user\nnum = as.integer(readline(prompt=\"Enter a number: \"))\n\nflag = 0\n# prime numbers are greater than 1\nif(num > 1) {\n # check for factors\n flag = 1\n for(i in 2:(num-1)) {\n if ((num %% i) == 0) {\n flag = 0\n break\n }\n }\n} \n\nif(num == 2) flag = 1\nif(flag == 1) {\n print(paste(num,\"is a prime number\"))\n} else {\n print(paste(num,\"is not a prime number\"))\n}\n", "meta": {"hexsha": "fcd8658696f9205fbc50116f3383a0d39e211eae", "size": 493, "ext": "r", "lang": "R", "max_stars_repo_path": "Prime-Number/prime.r", "max_stars_repo_name": "StuWares/Hacktoberfest2018", "max_stars_repo_head_hexsha": "fb1efa15c37cd03bb9da89981aa26d152414a273", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-06T11:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-06T11:10:21.000Z", "max_issues_repo_path": "Prime-Number/prime.r", "max_issues_repo_name": "StuWares/Hacktoberfest2018", "max_issues_repo_head_hexsha": "fb1efa15c37cd03bb9da89981aa26d152414a273", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prime-Number/prime.r", "max_forks_repo_name": "StuWares/Hacktoberfest2018", "max_forks_repo_head_hexsha": "fb1efa15c37cd03bb9da89981aa26d152414a273", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2592592593, "max_line_length": 53, "alphanum_fraction": 0.537525355, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382006, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7097391873419513}} {"text": "TernarySearch <- function(left, right, f, eps=1e-4){\r\n while(TRUE){\r\n if (abs(left - right) < eps) return((left + right) / 2)\r\n \r\n leftThird <- left + (right - left) / 3\r\n rightThird <- right - (right - left) / 3\r\n \r\n if (f(leftThird) > f(rightThird)) \r\n left <- leftThird\r\n else\r\n right <- rightThird\r\n }\r\n \r\n}\r\n", "meta": {"hexsha": "0538bc6a908173e1501ee6d14133b61dc11be65c", "size": 349, "ext": "r", "lang": "R", "max_stars_repo_path": "DySyn_synthetic/functions/TernarySearch.r", "max_stars_repo_name": "andregustavom/icdm21_paper", "max_stars_repo_head_hexsha": "ee4f5247ae6574ab69f5a29134846d50d9e305b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DySyn_synthetic/functions/TernarySearch.r", "max_issues_repo_name": "andregustavom/icdm21_paper", "max_issues_repo_head_hexsha": "ee4f5247ae6574ab69f5a29134846d50d9e305b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DySyn_synthetic/functions/TernarySearch.r", "max_forks_repo_name": "andregustavom/icdm21_paper", "max_forks_repo_head_hexsha": "ee4f5247ae6574ab69f5a29134846d50d9e305b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2666666667, "max_line_length": 60, "alphanum_fraction": 0.5214899713, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7097391689651988}} {"text": "# Example : 1 Chapter : 10.2 Page No: 502\r\n# Orthogonal Complex vectors\r\ni<-complex(real=0,imaginary=1)\r\nu<-matrix(c(1,i),ncol=1)\r\nut<-t(u)\r\n#take conjugate of ut\r\nut[1,2]<-Conj(ut[1,2])\r\nv<-matrix(c(i,1),ncol=1)\r\nprint(\"inner product of u and v is conj(u tanspose )* v is \")\r\ninnerproduct<-ut%*%v\r\nprint(innerproduct)\r\nprint(\"As innerproduct is zero , they are orthogonal complex vectors\")\r\n\r\n", "meta": {"hexsha": "2c71d894e068c095ad80b587430bded415b694bc", "size": 401, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH10/EX10.2.1/EX10.2_1.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH10/EX10.2.1/EX10.2_1.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH10/EX10.2.1/EX10.2_1.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 28.6428571429, "max_line_length": 71, "alphanum_fraction": 0.6658354115, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7097210046011482}} {"text": "#' Function to calculate weighted standard deviation\n#' \n#' Calculates the standard deviation of a weighted sample set\n#' while propagating sample weights through the calculation.\n#' @param x Vector containing the values in the set\n#' @param w Vector containing the weights to each value (in \n#' the same order as \\code{x}\n#' the optimized growth model\n#' @param na.rm Should NA values be removed from the set prior\n#' to calculation? \\code{TRUE/FALSE}\n#' @return The standard deviation of the weighted set of \\code{x} values\n#' @examples\n#' # Create dummy data\n#' x <- seq(1, 10, 0.5)\n#' w <- c(seq(0.1, 1, 0.1), seq(0.9, 0.1, -0.1))\n#' SDw <- sd_wt(x, w, na.rm = TRUE) # Run the function\n#' @export\nsd_wt<-function(x, w, na.rm = FALSE){ # Formula for weighted standard deviation\n if(na.rm == TRUE){ # Remove NA containing x/w pairs\n x<-x[!(is.na(x) | is.na(w))]\n w<-w[!(is.na(x) | is.na(w))]\n }\n mean.wt <- mean(x * w, na.rm = TRUE) / mean(w) # Calculate weighted mean\n stdev <- sqrt(sum(w * (x - mean.wt) ^ 2) / ((length(w) - 1) / length(w) * sum(w)))\n return(stdev)\n}", "meta": {"hexsha": "c2b5d18f889d79b04a2d9409bc85f51031008d59", "size": 1100, "ext": "r", "lang": "R", "max_stars_repo_path": "R/sd_wt.r", "max_stars_repo_name": "nhoeche/ShellChron.jl", "max_stars_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/sd_wt.r", "max_issues_repo_name": "nhoeche/ShellChron.jl", "max_issues_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/sd_wt.r", "max_forks_repo_name": "nhoeche/ShellChron.jl", "max_forks_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3076923077, "max_line_length": 86, "alphanum_fraction": 0.6381818182, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7096126545179433}} {"text": "\r\n#####################################################################################################################################\r\n#ABCDE model2: Model 2 is the model to be run in order to spin up the models initial states\r\nABCDE_SCE_CALIBRATE <- function(parameters,P,PE,T,Qobs,calib_num) {\r\n\r\n\t\t\r\n\t#parameters = a vector with a,b,c,d\r\n\t#P\t= a vector with precip time series for current station\r\n\t#PE\t= a vector with potential evapotranspiration time series for current station\r\n\t#P\t= a vector with tavg time series for current statio\r\n\t#Qobs\t= a vector with observed streamflow time series for current station\t\t\t#Sint = initial soil moisture\r\n\t#Gint = initial groundwater storage\r\n\t#Aint = initial snow accumulation\r\n\t\t\r\n\tparm <- parameters\r\n\tPeff <- array(0,calib_num) \t#snow storage\r\n\tETeff <- array(0,calib_num) \t#snow storage\r\n\tA <- array(0,calib_num) \t#snow storage\r\n\tW <- array(0,calib_num) \t#available water\r\n\tY <- array(0,calib_num) \t#evapotranspiration opportunity\r\n\tS <- array(0,calib_num) \t#soil moisture\r\n\tE <- array(0,calib_num) \t#actual evaporation\r\n\tG <- array(0,calib_num) \t#groundwater storage \r\n\tQest <- array(0,calib_num) #estimated runoff\r\n\tS[1] <- parm[7]\r\n\tG[1] <- parm[8]\r\n\tA[1] <- parm[9]\r\n\t\t\r\n\tfor (i in 2:calib_num) {\r\n\t\t#Begin snow component\r\n\t\tif (T[i] > parm[6]) {\r\n\t\t\tmt <- min(parm[5]*(T[i]-parm[6])*A[i-1],A[i-1])\r\n\t\t\tPeff[i] <- P[i]+mt\r\n\t\t\tETeff[i] <- PE[i]\r\n\t\t\tA[i] <- A[i-1] - mt\r\n\t\t} else {\r\n\t\t\tmt <- 0\r\n\t\t\tPeff[i] <- 0\r\n\t\t\tETeff[i] <- 0\r\n\t\t\tA[i] <- A[i-1]+P[i]\t\r\n\t\t}\r\n\t\t\r\n\t\tW[i] <- Peff[i] + S[i-1]\r\n\t\t#w1 and w2 are intermediate values used to calculate Y\r\n\t\tw1 <- (W[i]+parm[2])/(2*parm[1])\r\n\t\tw2 <- W[i]*parm[2]/parm[1]\r\n\t\tY[i] <- w1 - sqrt((w1^2)-w2)\r\n\t\tS[i] <- Y[i]*exp(-1*ETeff[i]/parm[2])\r\n\t\tE[i] <- Y[i]*(1-exp(-1*(ETeff[i]/parm[2])))\r\n\t\tG[i] <- (G[i-1] + parm[3]*round((W[i]-Y[i]),2))/(1+parm[4])\r\n\t\tQest[i] <- (1-parm[3])*round((W[i]-Y[i]),2)+parm[4]*G[i]\r\n\t}\r\n\tSSE <- (sum(((Qobs) - (Qest))^2))\r\n\treturn(SSE)\t\r\n}\r\n#################################################################################################################\r\n", "meta": {"hexsha": "288e07a487342107bf02b53c0ea9852d8531cad0", "size": 2100, "ext": "r", "lang": "R", "max_stars_repo_path": "app/ABCDE_SCE_CALIBRATE.r", "max_stars_repo_name": "HydrosystemsGroup/ViRTUE", "max_stars_repo_head_hexsha": "dad195643311dd5421e680794301ef92ec228224", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/ABCDE_SCE_CALIBRATE.r", "max_issues_repo_name": "HydrosystemsGroup/ViRTUE", "max_issues_repo_head_hexsha": "dad195643311dd5421e680794301ef92ec228224", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/ABCDE_SCE_CALIBRATE.r", "max_forks_repo_name": "HydrosystemsGroup/ViRTUE", "max_forks_repo_head_hexsha": "dad195643311dd5421e680794301ef92ec228224", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8421052632, "max_line_length": 134, "alphanum_fraction": 0.5242857143, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.709612649516073}} {"text": "# Chaper 5 Lab: Cross-Validation and the Bootstrap\n\n# This code is quoted from\n# http://faculty.marshall.usc.edu/gareth-james/ISL/code.html\n\n# The Validation Set Approach\n\nlibrary(ISLR)\nset.seed(1)\ntrain=sample(392,196)\nlm.fit=lm(mpg~horsepower,data=Auto,subset=train)\nattach(Auto)\nmean((mpg-predict(lm.fit,Auto))[-train]^2)\nlm.fit2=lm(mpg~poly(horsepower,2),data=Auto,subset=train)\nmean((mpg-predict(lm.fit2,Auto))[-train]^2)\nlm.fit3=lm(mpg~poly(horsepower,3),data=Auto,subset=train)\nmean((mpg-predict(lm.fit3,Auto))[-train]^2)\nset.seed(2)\ntrain=sample(392,196)\nlm.fit=lm(mpg~horsepower,subset=train)\nmean((mpg-predict(lm.fit,Auto))[-train]^2)\nlm.fit2=lm(mpg~poly(horsepower,2),data=Auto,subset=train)\nmean((mpg-predict(lm.fit2,Auto))[-train]^2)\nlm.fit3=lm(mpg~poly(horsepower,3),data=Auto,subset=train)\nmean((mpg-predict(lm.fit3,Auto))[-train]^2)\n\n# Leave-One-Out Cross-Validation\n\nglm.fit=glm(mpg~horsepower,data=Auto)\ncoef(glm.fit)\nlm.fit=lm(mpg~horsepower,data=Auto)\ncoef(lm.fit)\nlibrary(boot)\nglm.fit=glm(mpg~horsepower,data=Auto)\ncv.err=cv.glm(Auto,glm.fit)\ncv.err$delta\ncv.error=rep(0,5)\nfor (i in 1:5){\n glm.fit=glm(mpg~poly(horsepower,i),data=Auto)\n cv.error[i]=cv.glm(Auto,glm.fit)$delta[1]\n }\ncv.error\n\n# k-Fold Cross-Validation\n\nset.seed(17)\ncv.error.10=rep(0,10)\nfor (i in 1:10){\n glm.fit=glm(mpg~poly(horsepower,i),data=Auto)\n cv.error.10[i]=cv.glm(Auto,glm.fit,K=10)$delta[1]\n }\ncv.error.10\n\n# The Bootstrap\n\nalpha.fn=function(data,index){\n X=data$X[index]\n Y=data$Y[index]\n return((var(Y)-cov(X,Y))/(var(X)+var(Y)-2*cov(X,Y)))\n }\nalpha.fn(Portfolio,1:100)\nset.seed(1)\nalpha.fn(Portfolio,sample(100,100,replace=T))\nboot(Portfolio,alpha.fn,R=1000)\n\n# Estimating the Accuracy of a Linear Regression Model\n\nboot.fn=function(data,index)\n return(coef(lm(mpg~horsepower,data=data,subset=index)))\nboot.fn(Auto,1:392)\nset.seed(1)\nboot.fn(Auto,sample(392,392,replace=T))\nboot.fn(Auto,sample(392,392,replace=T))\nboot(Auto,boot.fn,1000)\nsummary(lm(mpg~horsepower,data=Auto))$coef\nboot.fn=function(data,index)\n coefficients(lm(mpg~horsepower+I(horsepower^2),data=data,subset=index))\nset.seed(1)\nboot(Auto,boot.fn,1000)\nsummary(lm(mpg~horsepower+I(horsepower^2),data=Auto))$coef\n\n", "meta": {"hexsha": "1a591b2820c251ede0b83f4033e49b0128000113", "size": 2183, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 5/R/Chapter 5.r", "max_stars_repo_name": "borisgarbuzov/schulich_data_science_1", "max_stars_repo_head_hexsha": "fd05ec2bbbe35408f90ebfcf10bb4ca588e7871c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter 5/R/Chapter 5.r", "max_issues_repo_name": "borisgarbuzov/schulich_data_science_1", "max_issues_repo_head_hexsha": "fd05ec2bbbe35408f90ebfcf10bb4ca588e7871c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 5/R/Chapter 5.r", "max_forks_repo_name": "borisgarbuzov/schulich_data_science_1", "max_forks_repo_head_hexsha": "fd05ec2bbbe35408f90ebfcf10bb4ca588e7871c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-25T05:26:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T08:25:58.000Z", "avg_line_length": 26.6219512195, "max_line_length": 72, "alphanum_fraction": 0.7333944114, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7093955041100427}} {"text": "x <- c(1,2,3,4,5,6) # Create ordered collection (vector)\ny <- x^2 # Square the elements of x\nprint(y) # print (vector) y\nmean(y) # Calculate average (arithmetic mean) of (vector) y; result is scalar\nvar(y) # Calculate sample variance\nlm_1<- lm(y ~ x) # Fit a linear regression model \"y = f(x)\" or \"y = B0 + (B1 * x)\" \n# store the results as lm_1\nprint(lm_1) # Print the model from the (linear model object) lm_1\n", "meta": {"hexsha": "e6f6a6d3b26afb629c8b9bc186ece9f96eae16e2", "size": 483, "ext": "r", "lang": "R", "max_stars_repo_path": "ml-cv/data_mining/R/test.r", "max_stars_repo_name": "zaqwes8811/coordinator-tasks", "max_stars_repo_head_hexsha": "7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ml-cv/data_mining/R/test.r", "max_issues_repo_name": "zaqwes8811/coordinator-tasks", "max_issues_repo_head_hexsha": "7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2015-03-07T12:46:41.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-11T09:08:36.000Z", "max_forks_repo_path": "ml-cv/data_mining/R/test.r", "max_forks_repo_name": "zaqwes8811/micro-apps", "max_forks_repo_head_hexsha": "7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.6666666667, "max_line_length": 91, "alphanum_fraction": 0.5755693582, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.7092712201794934}} {"text": "library(\"ggplot2\")\nheights <- c(170, 151, 174, 197, 177, 194, 173, 180, 186, 185, 175, 163, 160, 178, 190, 170, 169, 183, 182, 180, 176, 176, 164, 180, 166, 168, 167, 186, 165)\n\ngetmode <- function(v) {\n uniqv <- unique(v)\n uniqv[which.max(tabulate(match(v, uniqv)))]\n}\n\nresult.mean <- mean(heights)\nprint(result.mean)\n\nresult.med <- median(heights)\nprint(result.med)\n\nresult.mode <- getmode(heights)\nprint(result.mode)\n\nresult.var <- sd(heights)\nprint(result.var)\n\nresult.gm_mean <- prod(heights)^(1/(length(heights)))\nprint(result.gm_mean)\n\nresult.hm_mean <- 1/mean(1/heights)\nprint(result.hm_mean)\n\nhist(heights, plot=TRUE, xlab=\"Students' heights\")\n\nboxplot(heights, xlab=\"Students' heights\", horizontal=TRUE)\n\nn <- length(heights)\np <- (1 : n) / n - 0.5 / n\n\nPP = data.frame(emp=(1:n)/n, theor=pnorm(sort(heights), result.mean, result.var))\nggplot(PP,aes(x=emp, y=theor)) + geom_abline(intercept=0, slope=1, colour=\"blue\") + geom_point() + labs(y=\"\", x=\"\", title=\"P-P plot\")\n\nQQ = data.frame(emp=sort(heights), theor=qnorm((1:n)/n, result.mean, result.var))\nQQ_plot <- ggplot(QQ, aes(x = emp, y = theor), colour = \"blue\")\nQQ_plot + geom_abline(intercept=0, slope=1, colour=\"red\") + geom_point() + labs(y=\"\", x=\"\", title=\"Q-Q plot\")", "meta": {"hexsha": "49c726fd530c6b889ce4f06d88d7ca31ca966293", "size": 1240, "ext": "r", "lang": "R", "max_stars_repo_path": "lab1.r", "max_stars_repo_name": "Via-R/data_analysis_labs", "max_stars_repo_head_hexsha": "3e4736d4d5a9648e6b06f55d6156e2517bb6f70e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab1.r", "max_issues_repo_name": "Via-R/data_analysis_labs", "max_issues_repo_head_hexsha": "3e4736d4d5a9648e6b06f55d6156e2517bb6f70e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab1.r", "max_forks_repo_name": "Via-R/data_analysis_labs", "max_forks_repo_head_hexsha": "3e4736d4d5a9648e6b06f55d6156e2517bb6f70e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7948717949, "max_line_length": 157, "alphanum_fraction": 0.6653225806, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7092712179757382}} {"text": "library(signal)\n\n# CIC filter parameters\nR <- 5 # Decimation factor\nM <- 1 # Differential delay\nN <- 6 # Number of stages\n\nFo <- 0.22 # Pass band edge\n\n# fir2 parameters\nk <- kaiserord(c(Fo, Fo+0.02), c(1, 0), 1/(2^16), 1)\nL <- k$n # Filter order\nBeta <- k$beta # Kaiser window parameter\n\n# FIR filter design using fir2\ns <- 0.001 # Step size\nfp <- seq(0.0, Fo, by=s) # Pass band frequency samples\nfs <- seq(Fo+0.02, 0.5, by=s) # Stop band frequency samples\nf <- c(fp, fs)*2 # Normalized frequency samples; 0<=f<=1\n\nMp <- matrix(1, 1, length(fp)) # Pass band response; Mp[1]=1\nMp[-1] <- abs(M*R*sin(pi*fp[-1]/R)/sin(pi*M*fp[-1]))^N\nMf <- c(Mp, matrix(0, 1, length(fs)))\n\nh <- fir2(L, f, Mf, window=kaiser(L+1, Beta))\n\n# Print filter coefficients\npaste(as.character(h), collapse=\", \")\n\nfh <- freqz(h)\n\nop <- par(mfrow = c(1, 2))\n\nplot(f, Mf, type = \"b\", ylab = \"magnitude\", xlab = \"Frequency\", xlim = c(0, 0.5))\nlines(fh$f / pi, abs(fh$h), col = \"blue\")\n\nplot(f, 20*log10(Mf+1e-5), type = \"b\", ylab = \"dB\", xlab = \"Frequency\", xlim = c(0, 0.5))\nlines(fh$f / pi, 20*log10(abs(fh$h)), col = \"blue\")\n\npar(op)\n", "meta": {"hexsha": "f8212e7bef1a8f1fcf71735e92a3051415f0d633", "size": 1276, "ext": "r", "lang": "R", "max_stars_repo_path": "projects/adc_recorder_trigger/fir_0.r", "max_stars_repo_name": "pjsg/red-pitaya-notes", "max_stars_repo_head_hexsha": "85faf2ed717c1bb08d350376fe4b366fdc5c56a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 240, "max_stars_repo_stars_event_min_datetime": "2015-02-28T19:14:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:52:30.000Z", "max_issues_repo_path": "projects/adc_recorder_trigger/fir_0.r", "max_issues_repo_name": "pjsg/red-pitaya-notes", "max_issues_repo_head_hexsha": "85faf2ed717c1bb08d350376fe4b366fdc5c56a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 402, "max_issues_repo_issues_event_min_datetime": "2015-05-08T11:51:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T21:28:43.000Z", "max_forks_repo_path": "projects/adc_recorder_trigger/fir_0.r", "max_forks_repo_name": "pjsg/red-pitaya-notes", "max_forks_repo_head_hexsha": "85faf2ed717c1bb08d350376fe4b366fdc5c56a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 179, "max_forks_repo_forks_event_min_datetime": "2015-01-08T22:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T16:42:18.000Z", "avg_line_length": 31.1219512195, "max_line_length": 89, "alphanum_fraction": 0.5242946708, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.7090834604953935}} {"text": "#' Compress lpo using Haar-wavelet transform.\n#'\n#' The time series is transformed using Haar-wavelet transform, \n#' then the near-zero-values will be rounded to zero to an extend \n#' and the series will be decoded, creating a new, compressed \n#' version of the original series.\n#' @param lpo Times series as numeric vector\n#' @param level Compression level, from 0 to 1\n#' @export\n#' \n#' @importFrom stats ts quantile\n#' \n#' @examples \n#' set.seed(1)\n#' d <- squares(100)\n#' lpo <- d[, 1]\n#' lpm <- compress.lpo(lpo, 0.9)\n#' plot(ts(lpo))\n#' lines(ts(lpm), col = \"red\")\n\ncompress.lpo <- function(lpo, level = 0.99) {\n \n l <- length(lpo)\n lpo <- ts(c(lpo, rep(0, 2^ceiling(log(l, base = 2)) - l)))\n trans <- wavelets::dwt(lpo, filter=\"haar\")\n w.vector.length <- l / 2\n w.vector <- numeric()\n for (i in 1:trans@level) {\n w.vector <- append(abs(trans@W[i][[1]]), w.vector)\n }\n limit <- quantile(w.vector, level)\n \n for (i in 1:trans@level) {\n trans@W[i][[1]][abs(trans@W[i][[1]]) <= limit] <- 0\n }\n \n res <- wavelets::idwt(trans)\n res <- res[1:l]\n return (res)\n}\n", "meta": {"hexsha": "f5cee1ebae272f38d2f3a4d79ee7b506a5b6c71f", "size": 1083, "ext": "r", "lang": "R", "max_stars_repo_path": "R/alg_HaarWaveletTransform.r", "max_stars_repo_name": "Arzik1987/bpriv", "max_stars_repo_head_hexsha": "1ffc92c7989c37b2bbaf6a440fb4346bd054cddb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/alg_HaarWaveletTransform.r", "max_issues_repo_name": "Arzik1987/bpriv", "max_issues_repo_head_hexsha": "1ffc92c7989c37b2bbaf6a440fb4346bd054cddb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/alg_HaarWaveletTransform.r", "max_forks_repo_name": "Arzik1987/bpriv", "max_forks_repo_head_hexsha": "1ffc92c7989c37b2bbaf6a440fb4346bd054cddb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4146341463, "max_line_length": 66, "alphanum_fraction": 0.6149584488, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.708825048189675}} {"text": "library(\"modreg\")\n###CHAPTER 5: BIAS VARIANCE TRADE-OFF \n##plot 01\nN <- 100\nx <- seq(.09,.5,len=N)\nf <- 2*sin(1/x)\nsigma2 <- 1\ny <- f + rnorm(N,0,sigma2)\npostscript(\"Plots/plot-05-01.ps\")\nplot(x,y,main=\"True f(x)=5 sin(1/x) and observations\")\nlines(x,f,type=\"l\")\ndev.off() \n####plot02\nNN <- 5\npostscript(\"Plots/plot-05-02.ps\")\nresults <- sapply(1:NN,function(i){\n y <- f + rnorm(N,0,sigma2)\n ksmooth(x,y,kernel=\"box\",bandwidth=.01)$y\n })\npar(mfrow=c(2,2),mai=c(0,0,0,0),oma=c(1,1,1,1))\nplot(x,f,type=\"l\",lwd=1.5,ylim=range(c(f,as.vector(results))))\nlines(x,results[,1],lty=4)\n\nplot(x,f,ylim=range(results),type=\"l\",lwd=1.5)\napply(results,2,function(aux) lines(x,aux,lty=4))\nresults <- sapply(1:NN,function(i){\n y <- f + rnorm(N,0,sigma2)\n ksmooth(x,y,kernel=\"box\",bandwidth=.1)$y\n })\nplot(x,f,type=\"l\",lwd=1.5)\nlines(x,results[,1],lty=4)\n\t\nplot(x,f,type=\"l\",lwd=1.5)\napply(results,2,function(aux) lines(x,aux,lty=4))\ndev.off()\n\n\n##plot03\npostscript(\"Plots/plot-05-03.ps\")\npar(mfrow=c(1,2))\n\nx <- seq(1,100,len=N)\nf <- 2*sin(1/(x+18.62)*218)\ny <- f + rnorm(N,0,sigma2)\nplot(x,y)\nlines(x,f)\n\n#N <- 500\nx <- seq(1,100,len=N)\nf <- sin(2*pi*x/100)\ny <- f + rt(N,3)\nplot(x,y)\nlines(x,f)\ndev.off()\n\n########## plot04\nNl <- 50\n#N <- 500\nx <- seq(1,100,len=N)\nf <- 2*sin(1/(x+18.62)*218)\ny <- f + rnorm(N,0,sigma2)\nlambdas <- seq(.01,2.2,len=Nl)\ncvs <- sapply(lambdas,function(l) smooth.spline(x,y,all.knots=T,spar=l,cv=T)$cv.crit) \nNN <- 200\nAUX <-matrix(rnorm(N*NN,0,sigma2),ncol=N)\nAUX <- sweep(AUX,2,f,FUN=\"+\")\nmse <- sapply(lambdas,function(l){\n cat(\".\")\n aux <- cbind(rep(l,NN),AUX)\n aux<-apply(aux,1,function(yy)\n\t sum((f-smooth.spline(x,yy[-1],all.knots=T,spar=yy[1])$y)^2)/500)\n mean(aux)\n})\nfit0 <- smooth.spline(x,y,all.knots=T,spar=lambdas[order(mse)[1]])\nfit1 <- smooth.spline(x,y,all.knots=T,spar=lambdas[order(cvs)[1]])\npostscript(\"Plots/plot-05-04.ps\")\npar(mfrow=c(2,3),oma=c(0,0,2,0))\nplot(lambdas,cvs,xlab=\"lambdas\",type=\"l\")\nabline(v=lambdas[order(cvs)[1]],lty=1)\nplot(lambdas,mse+1,xlab=\"lambdas\",type=\"l\")\nabline(v=lambdas[order(mse)[1]],lty=2)\no <- sort(sample(1:length(x),50))\nplot(x,f,type=\"l\",ylim=range(c(fit1$y,fit0$y[o])))\nlines(x[o],fit1$y[o],lty=2,col=2)\nlines(x[o],fit0$y[o],lty=3,col=3)\nlegend(70,0,c(\"truth\",\"CV\",\"MSE\"),lty=c(1,2,3),col=c(1,2,3))\n\n#N <- 500\nx <- seq(1,100,len=N)\nf <- sin(2*pi*x/100)\ny <- f + rt(N,3)\nN1 <- 50\ncvs2 <- sapply(lambdas,function(l) smooth.spline(x,y,all.knots=T,spar=l,cv=T)$cv.crit) \nNN <- 20\nAUX <-matrix(rt(N*NN,3),ncol=N)\nAUX <- sweep(AUX,2,f,FUN=\"+\")\nmse2 <- sapply(lambdas,function(l){\n cat(\".\")\n aux <- cbind(rep(l,NN),AUX)\n aux<-apply(aux,1,function(yy)\n\t sum((f-smooth.spline(x,yy[-1],all.knots=T,spar=yy[1])$y)^2)/500)\n mean(aux)\n})\nfit00 <- smooth.spline(x,y,all.knots=T,spar=lambdas[order(mse2)[1]])\nfit11 <- smooth.spline(x,y,all.knots=T,spar=lambdas[order(cvs2)[1]])\nplot(lambdas,cvs2,xlab=\"lambdas\",type=\"l\")\nabline(v=lambdas[order(cvs2)[1]],lty=1)\nplot(lambdas,mse2+sigma2,xlab=\"lambdas\",type=\"l\")\nabline(v=lambdas[order(mse2)[1]],lty=2)\no <- sort(sample(1:length(x),100))\nplot(x,f,type=\"l\",ylim=range(c(f,fit11$y,fit00$y[o])))\nlines(x[o],fit11$y[o],lty=2,col=2)\nlines(x[o],fit00$y[o],lty=3,col=3)\nlegend(70,1,c(\"truth\",\"CV\",\"MSE\"),lty=c(1,2,3),col=c(1,2,3))\nmtext(side=3,paste(\"N =\",N),cex=1.2,line=0,outer=T)\ndev.off()\n\n###NOW for N=500\nNl <- 50\nN <- 500\nx <- seq(1,100,len=N)\nf <- 2*sin(1/(x+18.62)*218)\ny <- f + rnorm(N,0,sigma2)\nlambdas <- seq(.01,2.2,len=Nl)\ncvs <- sapply(lambdas,function(l) smooth.spline(x,y,all.knots=T,spar=l,cv=T)$cv.crit) \nNN <- 20\nAUX <-matrix(rnorm(N*NN,0,sigma2),ncol=N)\nAUX <- sweep(AUX,2,f,FUN=\"+\")\nmse <- sapply(lambdas,function(l){\n cat(\".\")\n aux <- cbind(rep(l,NN),AUX)\n aux<-apply(aux,1,function(yy)\n\t sum((f-smooth.spline(x,yy[-1],all.knots=T,spar=yy[1])$y)^2)/500)\n mean(aux)\n})\nfit0 <- smooth.spline(x,y,all.knots=T,spar=lambdas[order(mse)[1]])\nfit1 <- smooth.spline(x,y,all.knots=T,spar=lambdas[order(cvs)[1]])\npostscript(\"Plots/plot-05-05.ps\")\npar(mfrow=c(2,3),oma=c(0,0,2,0))\nplot(lambdas,cvs,xlab=\"lambdas\",type=\"l\")\nabline(v=lambdas[order(cvs)[1]],lty=1)\nplot(lambdas,mse+1,xlab=\"lambdas\",type=\"l\")\nabline(v=lambdas[order(mse)[1]],lty=2)\no <- sort(sample(1:length(x),50))\nplot(x,f,type=\"l\",ylim=range(c(fit1$y,fit0$y[o])))\nlines(x[o],fit1$y[o],lty=2,col=2)\nlines(x[o],fit0$y[o],lty=3,col=3)\nlegend(70,0,c(\"truth\",\"CV\",\"MSE\"),lty=c(1,2,3),col=c(1,2,3))\n\n#N <- 500\nx <- seq(1,100,len=N)\nf <- sin(2*pi*x/100)\ny <- f + rt(N,3)\nN1 <- 50\ncvs2 <- sapply(lambdas,function(l) smooth.spline(x,y,all.knots=T,spar=l,cv=T)$cv.crit) \nNN <- 20\nAUX <-matrix(rt(N*NN,3),ncol=N)\nAUX <- sweep(AUX,2,f,FUN=\"+\")\nmse2 <- sapply(lambdas,function(l){\n cat(\".\")\n aux <- cbind(rep(l,NN),AUX)\n aux<-apply(aux,1,function(yy)\n\t sum((f-smooth.spline(x,yy[-1],all.knots=T,spar=yy[1])$y)^2)/500)\n mean(aux)\n})\nfit00 <- smooth.spline(x,y,all.knots=T,spar=lambdas[order(mse2)[1]])\nfit11 <- smooth.spline(x,y,all.knots=T,spar=lambdas[order(cvs2)[1]])\nplot(lambdas,cvs2,xlab=\"lambdas\",type=\"l\")\nabline(v=lambdas[order(cvs2)[1]],lty=1)\nplot(lambdas,mse2+sigma2,xlab=\"lambdas\",type=\"l\")\nabline(v=lambdas[order(mse2)[1]],lty=2)\no <- sort(sample(1:length(x),100))\nplot(x,f,type=\"l\",ylim=range(c(f,fit11$y,fit00$y[o])))\nlines(x[o],fit11$y[o],lty=2,col=2)\nlines(x[o],fit00$y[o],lty=3,col=3)\nlegend(70,1,c(\"truth\",\"CV\",\"MSE\"),lty=c(1,2,3),col=c(1,2,3))\nmtext(side=3,paste(\"N =\",N),cex=1.2,line=0,outer=T)\ndev.off()\n\npostscript(\"Plots/plot-05-06.ps\")\ny <- read.table(\"Data/cholostyramine.dat\",header=T)\nattach(y)\nplot(compliance,improvement)\nabline(lm(improvement~compliance,data=y),col=4,lty=1)\no <- order(compliance)\nlines(compliance[o],loess(improvement~compliance,data=y)$fitted[o],col=2,lty=2)\ndev.off()\n\n\n\n###bootsrap.. there is bootstrap function in R, but we need to download library\npostscript(\"Plots/plot-05-07.ps\")\nB <- 50\nN <- length(compliance)\nfit1 <- lm(improvement~compliance,data=y)\nfit2 <- loess(improvement~compliance,data=y)\nthetas <- c(predict(fit1,data.frame(compliance=c(60,80,100))),\n predict(fit2,data.frame(compliance=c(60,80,100))))\npar(mfrow=c(1,2))\naux <- matrix(sample(1:N,B*N,replace=T),B,N)\nplot(compliance,improvement,type=\"n\")\nabline(h=0,v=60)\nplot(compliance,improvement,type=\"n\")\nabline(h=0,v=60)\nthetastars <- apply(aux,1,function(o){\n fit1 <- lm(improvement~compliance,data=y,subset=o)\n fit2 <- loess(improvement~compliance,data=y,subset=o)\n par(mfg=c(1,1,1,2))\n abline(fit1)\n par(mfg=c(1,2,1,2))\n oo <- order(compliance[o])\n lines(compliance[o][oo],fit2$fitted[oo])\n c(predict(fit1,data.frame(compliance=c(60,80,100))),\n predict(fit2,data.frame(compliance=c(60,80,100))))\n})\ndev.off()\ndetach(\"y\")\n\n##this prints out the results\njunk <- rbind(thetas,\n apply(thetastars,1,function(x) sqrt(var(x))))\n\nprint(round(junk))\n\n\n\n############\n#### CONFIDENCE BANDS STUFF\n###############\nN <- 100\nx <- sort(runif(N,1,100))#seq(1,100,len=N)\nf <- sin(2*pi*x/100)\ny <- f+rnorm(N,0,1)\nY <- diag(N)\nl <- .7\nS <- apply(Y,1,function(yy) loess(yy~x,span=l)$fitted)\naux <- svd(S) ##then ss' is ud^2u'\nSS <- aux$u%*%diag(aux$d^2)%*%t(aux$u) ##this is ss'\ndfvar <- sum(diag(SS))\ndferr <- N - 2*sum(diag(S)) + dfvar\n###TRUE \nNN <- 5000\nAUX <- matrix(rnorm(NN*N,0,1),ncol=N)\nGtrue <- apply(AUX,1,function(error){\n yy <- error+f;resid <- yy-S%*%yy\n sum(error^2)/(sum(resid^2)/dferr)})\nfit1 <- S%*%y\nresidstar <- y - fit1\nB <- 500\nGboot <- rep(0,B)\nfor(i in 1:B){\n \terror <- sample(residstar,N,replace=T)\n yy <- error+fit1;resid <- yy-S%*%yy\n Gboot[i] <- sum(error^2)/(sum(resid^2)/dferr)\n }\nGapprox <-dferr+ dfvar*rf(NN,dfvar,dferr) \n\n\npostscript(\"Plots/plot-05-08.ps\")\npar(mfrow=c(1,1))\nplot(x,y)\nlines(x,f,col=3)\nlines(x,fit1,lty=2,col=4)\ndev.off()\n\npostscript(\"Plots/plot-05-09.ps\")\npar(mfrow=c(1,2))\nRANGE <- range(Gtrue,Gapprox,Gboot)\nqqplot(Gtrue,Gboot,ylim=RANGE,xlim=RANGE,pch=\"B\",col=3)\nlines(sort(Gtrue),sort(Gapprox),pch=\"F\",col=4)\nabline(0,1)\n##NOW we make bootstrap curves\nNNN <- 7\nsigmahat <- sqrt((sum(((diag(N)-S)%*%y)^2)/dferr))\nG <- Gboot ##we can use others here like Gapprox\nqG <- quantile(G,.95)\nfs <- sapply(1:NNN,function(i){\n\tresid<- rnorm(N,0,sigmahat)\n auxG <- sum(resid^2)/(sigmahat^2)\n ##notice SS' = [UD][UD]'\n newf <- fit1+ aux$u%*%diag(aux$d)%*%resid\n if(auxG < qG) return(c(1,newf))\n else return(c(0,newf))\n}\n)\nci <- 2*sqrt(diag(SS)*sigmahat^2)\nplot(x,fit1,ylim=range(c(fit1+ci,fit1-ci,as.vector(fs[-1,]))),type=\"l\")\npolygon(c(x,rev(x)),c(fit1+ci,rev(fit1-ci)),col=655,border=F)\nlines(x,fit1)\napply(fs,2,function(yy) lines(x,yy[-1],col=3+yy[1],lty=3-yy[1]))\ndev.off()\n\n\n###NOW for t-distribution\nN <- 100\nx <- sort(runif(N,1,100))#seq(1,100,len=N)\nf <- sin(2*pi*x/100)\ny <- f+rt(N,3)\nY <- diag(N)\nl <- .7\nS <- apply(Y,1,function(yy) loess(yy~x,span=l)$fitted)\naux <- svd(S) ##then ss' is ud^2u'\nSS <- aux$u%*%diag(aux$d^2)%*%t(aux$u) ##this is ss'\ndfvar <- sum(diag(SS))\ndferr <- N - 2*sum(diag(S)) + dfvar\n###TRUE \nNN <- 5000\nAUX <- matrix(rt(NN*N,3),ncol=N)\nGtrue <- apply(AUX,1,function(error){\n yy <- error+f;resid <- yy-S%*%yy\n sum(error^2)/(sum(resid^2)/dferr)})\nfit1 <- S%*%y\nresidstar <- y - fit1\nB <- 1000\nGboot <- rep(0,B)\nfor(i in 1:B){\n \terror <- sample(residstar,N,replace=T)\n yy <- error+fit1;resid <- yy-S%*%yy\n Gboot[i] <- sum(error^2)/(sum(resid^2)/dferr)\n }\nGapprox <-dferr+ dfvar*rf(NN,dfvar,dferr) \n\n\n\npostscript(\"Plots/plot-05-10.ps\")\npar(mfrow=c(1,2))\nRANGE <- range(Gtrue,Gapprox,Gboot)\nqqplot(Gtrue,Gboot,ylim=RANGE,xlim=RANGE,pch=\"B\",col=3)\nlines(sort(Gtrue),sort(Gapprox),pch=\"F\",col=4)\nabline(0,1)\n##NOW we make bootstrap curves\nNNN <- 7\nsigmahat <- sqrt((sum(((diag(N)-S)%*%y)^2)/dferr))\nG <- Gboot ##we can use others here like Gapprox\nqG <- quantile(G,.95)\nfs <- sapply(1:NNN,function(i){\n\tresid<- rnorm(N,0,sigmahat)\n auxG <- sum(resid^2)/(sigmahat^2)\n ##notice SS' = [UD][UD]'\n newf <- fit1+ aux$u%*%diag(aux$d)%*%resid\n if(auxG < qG) return(c(1,newf))\n else return(c(0,newf))\n}\n)\nci <- 2*sqrt(diag(SS)*sigmahat^2)\nplot(x,fit1,ylim=range(c(fit1+ci,fit1-ci,as.vector(fs[-1,]))),type=\"l\")\npolygon(c(x,rev(x)),c(fit1+ci,rev(fit1-ci)),col=655,border=F)\nlines(x,fit1)\napply(fs,2,function(yy) lines(x,yy[-1],col=3+yy[1],lty=3-yy[1]))\ndev.off()\n\n\n", "meta": {"hexsha": "9d0d6f1d305f49170a16bb1c49db95a7cb31ad7a", "size": 10313, "ext": "r", "lang": "R", "max_stars_repo_path": "pages/754/code-05.r", "max_stars_repo_name": "igrabski/rafalab.github.io", "max_stars_repo_head_hexsha": "2f27ea0d9e0b8a2342bb851ae7415ba3268fd00f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2016-08-17T23:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T19:21:02.000Z", "max_issues_repo_path": "pages/754/code-05.r", "max_issues_repo_name": "igrabski/rafalab.github.io", "max_issues_repo_head_hexsha": "2f27ea0d9e0b8a2342bb851ae7415ba3268fd00f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-08-18T00:41:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T22:35:40.000Z", "max_forks_repo_path": "pages/754/code-05.r", "max_forks_repo_name": "igrabski/rafalab.github.io", "max_forks_repo_head_hexsha": "2f27ea0d9e0b8a2342bb851ae7415ba3268fd00f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2016-08-17T22:17:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T12:17:08.000Z", "avg_line_length": 29.2152974504, "max_line_length": 87, "alphanum_fraction": 0.6260060118, "num_tokens": 4234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7084211756269461}} {"text": "source('./knn.r', chdir = T)\n\nfast_cvloo_knn <- function() {\n maxK <- length(iris[,1]) - 1\n classes = unique(iris$Species)\n \n ans <- rep(x = 0, times = maxK)\n for (i in 1:length(iris[,1])) {\n # for (i in 1:10) {\n cat(\"\\r\", \"Processing sample \", i, \" of \", length(iris[,1]))\n dataset <- iris[-i,]\n # print(dataset)\n distance <- array(dim=c(length(dataset[,1])))\n for (j in 1:(length(dataset[,1]))) {\n distance[j] <- euclidean(dataset[j, 3:4], iris[i, 3:4])\n }\n sortedDataset <- dataset[order(distance),]\n \n classesCount <- rep(x = 0, times = length(classes))\n names(classesCount) = classes\n for (j in 1:maxK) {\n classesCount[sortedDataset$Species[j]] <- classesCount[sortedDataset$Species[j]] + 1\n \n classForCurrentK = names(which.max(classesCount))[1]\n if (classForCurrentK == iris$Species[i]) {\n ans[j] = ans[j] + 1\n }\n }\n \n }\n cat(\"\\n\")\n for (i in 1:length(ans)) {\n \n ans[i] = ans[i] / length(iris[,1] - 1)\n }\n \n return (ans)\n}\n\npar(mfrow=c(1,1), pty=\"s\")\n# LOO CV, looking for the best k\nstats <- fast_cvloo_knn()\nplot(1:(length(iris[,1]) - 1), stats, type=\"l\", xlab=\"k\", ylab=\"Accuracy\")\n\nmaxPoint = which(stats == max(stats))\npoints((1:(length(iris[,1]) - 1))[maxPoint], stats[maxPoint], pch = 19, col = \"red\")\n\nbestK <- which.max(stats)\ncat(\"Best K =\", bestK, \"\\n\")", "meta": {"hexsha": "555fa09f68ee39abedabd9a0540cf4eb82a45570", "size": 1367, "ext": "r", "lang": "R", "max_stars_repo_path": "1 - Nearest neighbors algorithm/knn-loocv.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1 - Nearest neighbors algorithm/knn-loocv.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1 - Nearest neighbors algorithm/knn-loocv.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8979591837, "max_line_length": 90, "alphanum_fraction": 0.5683979517, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.70836981245345}} {"text": "#' @title findMoments \n#' @description to find the first two moments of a distrbution from quantile breaks (defined by the upper and lower percent)\n#' @note Gamma distribution returns shape and scale rather than rate (as per winbugs distribution) for use in r rate=1/scale lo and l.perc are the value and percentile for the low end of the distribution, up and u.perc are the upper values and percentiles\n#' @family abysmally documented\n#' @author Adam Cook, \\email{Adam.Cook@@dfo-mpo.gc.ca}\n#' @export\n#source('C:/Documents and Settings/cooka/Desktop/Scripts/Surplus Production dec 2011/bugs/finding moments of distributions.R')\n####Date:\t\t\tFebruary 10, 2012 \n\t\n\n\nfindMoments <- function(lo=0.1,up=0.8,l.perc=0.025,u.perc=0.975,dist=c('norm','lnorm','weibull','gamma','inv.gamma'),plot=T) {\n\tif(dist=='norm') {\n\t\t\t sig2 = ((up-lo)/(qnorm(u.perc)-qnorm(l.perc)))^2\n\t\t\t xbar = (lo*qnorm(u.perc)-up*qnorm(l.perc))/(qnorm(u.perc)-qnorm(l.perc))\n\t\t\t if(plot) {\n\t\t\t plot(density(rnorm(10000,xbar,sqrt(sig2))),main='')\n\t\t\t abline(v=lo)\n\t\t\t abline(v=up)\n\t\t\t }\n\t\t\t return(list(xbar=xbar,sig2=sig2))\n\t }\n\tif(dist=='lnorm') {\n\t\t\t sig2 = ((log(up)-log(lo))/(qnorm(u.perc)-qnorm(l.perc)))^2\n\t\t\t xbar = (log(lo)*qnorm(u.perc)-log(up)*qnorm(l.perc))/(qnorm(u.perc)-qnorm(l.perc))\n\t\t\t if(plot) {\n\t\t\t plot(density(rlnorm(10000,xbar,sqrt(sig2))),main='')\n\t\t\t abline(v=lo)\n\t\t\t abline(v=up)\n\t\t\t }\n\t\t\t return(list(xbar=xbar,sig2=sig2))\n\t }\n\tif(dist=='weibull') {\n\t\t\tgam = (log(-log(1-u.perc))-log(-log(1-l.perc)))/(log(up)-log(lo))\n\t\t\tbeta = lo/(-log(1-l.perc))^(1/gam)\n\t\t\tif(plot) {\n\t\t \tplot(density(rweibull(10000,gam,beta)),main='')\n\t\t \tabline(v=lo)\n\t\t \tabline(v=up)\n\t\t }\n\t\t\treturn(list(shape=gam,beta=beta))\n\t}\n\tif(dist=='gamma') {\n\t\t\ta=mean(c(lo,up))\n\t\t\talpha <- function(a) {\n\t\t\tb <- qgamma(u.perc,a,1) / qgamma(l.perc,a,1) \n\t\t\to = (b-(up/lo))^2\n\t\t\treturn(list(a=a,o=o))\n\t\t\t}\n\t\t\top<-function(a) alpha(a)$o\n\t\t\tot <- optimize(f=op,interval=c(0,up))\n\t\t\talp <- ot$minimum\n\t\t\ten <- lo/qgamma(l.perc,alp,1)\n\t\t\tif(plot) {\n\t\t \tplot(density(rgamma(10000,alp,scale=en)),main='')\n\t\t \tabline(v=lo)\n\t\t \tabline(v=up)\n\t\t }\n\t\t\treturn(list(shape=alp,scale=en))\n\t}\n\t\tif(dist=='inv.gamma') {\n\t\t\ta=mean(c(1/lo,1/up))\n\t\t\tilo<-1/lo\n\t\t\tiup<-1/up\n\t\t\talpha <- function(a) {\n\t\t\tb <- qgamma((1-u.perc),a,1) / qgamma((1-l.perc),a,1) \n\t\t\to = (b-(iup/ilo))^2\n\t\t\treturn(list(a=a,o=o))\n\t\t\t}\n\t\t\top<-function(a) alpha(a)$o\n\t\t\tot <- optimize(f=op,interval=c(0,up))\n\t\t\talp <- ot$minimum\n\t\t\ten <- ilo/(1/qgamma((1-l.perc),alp,1))\n\t\t\tif(plot) {\n\t\t \tplot(density(1/rgamma(10000,alp,scale=1/en)),main='') \n\t\t \tabline(v=lo)\n\t\t \tabline(v=up)\n\t\t }\n\t\t\treturn(list(shape=alp,scale=en))\n\t}\n}\n", "meta": {"hexsha": "25c5ee15f6a1ea7d5a6913a3f2674b8d224ecafa", "size": 2634, "ext": "r", "lang": "R", "max_stars_repo_path": "R/findMoments.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/findMoments.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/findMoments.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1219512195, "max_line_length": 255, "alphanum_fraction": 0.6138952164, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.70816399529686}} {"text": "#' Probability of path choices\r\n#'\r\n#' This function calculates probabilities for selection of each path on the network based on set of path disutilities (costs). The function uses either a logit or probit random utility model.\r\n#' @param u Vector of utlities on each path\r\n#' @param ODpair Vector indicating the OD pair serviced by each route (ordered by columns of the path-link incidence matrix, A).\r\n#' @param A Path-link incidence matrix\r\n#' @param RUM Choice of random utility model. Can be \"logit\" (the default) or \"probit\".\r\n#' @param theta A dispersion parameter. For the logit model, a single value specifying the logit parameter. For the probit model, a vector of standard deviations for the individual link cost errors. Defaults to 1.\r\n#' @return Vector of route choice probabilities\r\n#' @keywords path route probability\r\n#' @examples\r\n#' A <- matrix(c(0,1,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,1),ncol=4,byrow=T)\r\n#' ODpair <- c(1,1,2,2)\r\n#' Alpha <- rep(10,7)\r\n#' Beta <- rep(2,7)\r\n#' pow <- rep(4,7)\r\n#' path_flow <- c(10,20,15,15)\r\n#' x <- A%*%path_flow\r\n#' u <- PathCost(x,A,Alpha,Beta)\r\n#' PathProb(u,ODpair,A,RUM=\"logit\",theta=0.7)\r\n#' @export\r\n\r\nPathProb <- function(u,ODpair,A,RUM=\"logit\",theta=1){\r\n\tif(RUM==\"logit\"){\r\n\t\tp <- LogitPathProb(u=u,ODpair=ODpair,theta=theta)\t\t\r\n\t}\r\n\tif(RUM==\"probit\"){\r\n\t\tp <- ProbitPathProb(u=u,ODpair=ODpair,A=A,theta=theta)\t\t\t\r\n\t}\r\n\tp\r\n}", "meta": {"hexsha": "68f7b466aba726d16c9a08da96a0024220f33bd6", "size": 1403, "ext": "r", "lang": "R", "max_stars_repo_path": "R/PathProb.r", "max_stars_repo_name": "MartinLHazelton/transportation", "max_stars_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/PathProb.r", "max_issues_repo_name": "MartinLHazelton/transportation", "max_issues_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/PathProb.r", "max_forks_repo_name": "MartinLHazelton/transportation", "max_forks_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2580645161, "max_line_length": 214, "alphanum_fraction": 0.6821097648, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.7080794021731747}} {"text": "#' f_loss\n#'\n#' Return the quantile loss criteria\n#'\n#' @param til_beta the current estimation fro $\\tilde{\\beta}$\n#' @param taustar vector of estimated tau for each observations\n#' @param v_y vector of y\n#'\n#' @param m_sigma $K_1K_2 \\times K_1K_2 \\Sigma$ diagonal block matix.\n#' @param h1 $K_1K_2$ vector $H_1$\n#' @param h2 $K_1K_2$ vector $H_2$\n#'\n#' @return the quantile loss\n#'\nf_loss <- function(til_beta, taustar, v_y, m_sigma, h1, h2) {\n loss <- crossprod((taustar - 0.5), v_y)\n loss <- loss - crossprod((h1 + h2), m_sigma %*% til_beta)\n loss <- loss / length(v_y)\n return(c(loss))\n}\n\n\n#' f_criteria\n#'\n#' Return the QR criteria\n#'\n#' @param beta the current estimation for $\\beta$\n#' @param til_beta the current estimation fro $\\tilde{\\beta}$\n#' @param taustar vector of estimated tau for each observations\n#' @param v_y vector of y\n#'\n#' @param m_sigma $K_1K_2 \\times K_1K_2 \\Sigma$ diagonal block matix.\n#' @param h1 $K_1K_2$ vector $H_1$\n#' @param h2 $K_1K_2$ vector $H_2$\n#' @param s $K_1K_2 \\times K_1K_2$ $S$ matrix\n#'\n#' @return the quantile loss\n#'\nf_criteria <- function(beta, til_beta, taustar, v_y, m_sigma, h1, h2, s) {\n loss <- f_loss(til_beta, taustar, v_y, m_sigma, h1, h2)\n criteria <- loss + crossprod(beta, s %*% beta)\n return(c(criteria))\n}", "meta": {"hexsha": "a158e1f0808f413029438a6d06cda7cad6854cbb", "size": 1289, "ext": "r", "lang": "R", "max_stars_repo_path": "R/criteria.r", "max_stars_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_stars_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/criteria.r", "max_issues_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_issues_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/criteria.r", "max_forks_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_forks_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.976744186, "max_line_length": 74, "alphanum_fraction": 0.6656322731, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7080268206751622}} {"text": "library(rstudioapi)\nlibrary(ellipse)\nthis.dir <- dirname(rstudioapi::getActiveDocumentContext()$path)\nsetwd(this.dir)\n\n##### DATA #####\n\n################\n\n##### 8.3 ######\neigen(as.matrix(rbind(c(2,0,0),c(0,4,0),c(0,0,4))))\n\n\n##### 8.6 #####\ns = as.matrix(cbind(c(7476.45,303.62),c(303.62,26.19)))\neigen = eigen(s)\n\nxbar =c(155.6,14.7)\nplot(ellipse(s,centre =xbar),type = 'l',xlim=c(-100,400),ylim=c(0,30),xlab = \"X1\",ylab = \"X2\",main = \"constant density ellipse\")\npoints(xbar[1],xbar[2],pch = 17)\nc = sqrt(1.4)\nax1=c*sqrt(eigen$values[1])*eigenS$vectors[,1]\nax2=c*sqrt(eigen$values[2])*eigenS$vectors[,2]\nlines(c(xbar[1]-ax1[1],xbar[1]+ax1[1]),c(xbar[2]-ax1[2],xbar[2]+ax1[2]),lty=1)\nlines(c(xbar[1]-ax2[1], xbar[1]+ax2[1]),c(xbar[2]-ax2[2],xbar[2]+ax2[2]),lty=2)\nlegend(x = \"topleft\", c(\"y1\",\"y2\"), lty = c(1,2))\t\n\n##### 8.7 #####\np = cov2cor(s)\neigen = eigen(p)\n\n##### 8.18 #####\ne8_18 = read.table(\"e8_18.txt\",header = TRUE)\n#assuming PCA output is based on correlation matrix (or variables of unit variance)\npc_correlations <- function(pca_output) { \n p <- ncol(pca_output$rotation)\n pccor=matrix(NA, nrow=p, ncol=p)\n for(i in 1:p){\n for(k in 1:p){\n pccor[k,i]=pca_output$rotation[k,i]*pca_output$sdev[i] \n }\n }\n colnames(pccor) <- paste0(\"PC\", 1:p)\n rownames(pccor) <- rownames(pca_output$rotation)\n pccor\n}\ndata(\"iris\")\npca <- prcomp(iris[,1:4])\nsummary(pca)\npc_correlations(pca)", "meta": {"hexsha": "eba48db78d4b9a06ef3747fef77a024347b355f9", "size": 1405, "ext": "r", "lang": "R", "max_stars_repo_path": "Statistics/STA 135/hw4/hw5.r", "max_stars_repo_name": "HaozheGuAsh/Undergrate", "max_stars_repo_head_hexsha": "2b75ef3ae06b6c2350edc4b0b03f516a194cca99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/STA 135/hw4/hw5.r", "max_issues_repo_name": "HaozheGuAsh/Undergrate", "max_issues_repo_head_hexsha": "2b75ef3ae06b6c2350edc4b0b03f516a194cca99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/STA 135/hw4/hw5.r", "max_forks_repo_name": "HaozheGuAsh/Undergrate", "max_forks_repo_head_hexsha": "2b75ef3ae06b6c2350edc4b0b03f516a194cca99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1, "max_line_length": 128, "alphanum_fraction": 0.6199288256, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7078890273011617}} {"text": "# Authors: Grzegorz Protaziuk, Robert Bembenik\n# Script EDAMI lab6\n# Clustering\n\n#setting working directory - adjust a path to your directory with a dataset\n\ninstall.packages(\"fpc\")\n\n\n\nlibrary(dbscan)\nlibrary(fpc)\nlibrary(cluster)\nlibrary(factoextra)\n\n##### kmeans ##################\nset.seed(7777)\n\ndata(\"iris\")\nsummary(iris)\niris2 = iris[,-5]\niris2\n\n\n?kmeans\niris2.kmeans = kmeans(iris2,3, iter.max = 20, nstart=20)\n\n#getting information about clustering\nprint(iris2.kmeans)\nprint(iris2.kmeans$iter)\nprint(iris2.kmeans$centers)\n\n#compare clusters with original class labels\ntable(iris$Species,iris2.kmeans$cluster)\n\n\n#plot clusters\nplot(iris2[,1:2], col = iris2.kmeans$cluster)\n#add cluster centers\npoints(iris2.kmeans$centers[,1:2], col = 1:3, pch = 8, cex=2)\n\n\n# Quality of the clustering \n\nkm<-kmeans(iris2,3)\n\n#alternative execution of kmeans\nkm_alt<-eclust(iris2, \"kmeans\", k=3, graph=FALSE)\nfviz_silhouette(km_alt, palette=\"jco\")\n\n# From the output, avg.silwidth represents the average silhouette width. A silhouette is a measurement\n# that considers how closely related objects are within the cluster and how clusters are separated\n# from each other. The silhouette value usually ranges from 0 to 1; a value closer to 1 suggests\n# the data is better clustered.\n\nsilinfo<-km_alt$silinfo\nnames(silinfo)\n\n#silhouette length for each observation\nhead(silinfo$widths[,1:3],10)\n#silhouette length for each cluster\nsilinfo$clus.avg.widths\n#average silhouette length\nsilinfo$avg.width\n\n# Rand index\n# The corrected Rand index provides a measure for assessing the similarity between\n# two partitions, adjusted for chance. Its range is -1 (no agreement) to 1 (perfect agreement).\nspecies <- as.numeric(iris$Species)\nclust_stats<-cluster.stats(d=dist(iris2), species, km_alt$cluster)\nclust_stats$corrected.rand\n\n\n\n#### data scaling\n?scale\nirisScale <- scale(iris2, center = FALSE)\nstr(irisScale)\niris2.kmeansS = kmeans(irisScale,3, iter.max = 20)\nstr(iris2.kmeansS)\ntable(iris$Species,iris2.kmeansS$cluster)\n\nplot(irisScale[,3:4], col = iris2.kmeansS$cluster)\n#add cluster centers\npoints(iris2.kmeansS$centers[,3:4], col = 1:3, pch = 8, cex=2)\n\n###############################################################\n# finding the optimal number of groups with the \"elbow\" method\n###############################################################\n\nwss <- vector(mode = \"integer\" ,length = 15)\n\n# 1 to 15 clusters\nfor (i in 1:15) {\n kmeans.group <- kmeans(irisScale, centers = i, nstart=20)\n # total within-cluster sum of squares\n wss[i] <- kmeans.group$tot.withinss\n}\n\n# total within-cluster sum of squares per number of groups\nplot(1:15, wss, type = \"b\", \n xlab = \"number of groups\", \n ylab = \"total within-cluster sum of squares\")\n\n\n####################################\n# PAM - partitioning around medoids#\n####################################\n\n# deciding on the optimal number of clusters\nfviz_nbclust(iris2, pam, method = \"silhouette\")+theme_classic()\n\n# division into 2 clusters\npam.res <- pam(iris2, 2)\n\n# clustering results together with information on objects being cluster centers\nprint(pam.res)\n\n#adding information on cluster assignment\niris_clus<-cbind(iris2, pam.res$cluster)\nhead(iris_clus)\n\n#cluster centers\nprint(pam.res$medoids)\n\n#cluster assignment\npam.res$clustering\n\n#clustering visualization\nfviz_cluster(pam.res,\n palette = c(\"#00AFBB\", \"#FC4E07\"), # color palette\n ellipse.type = \"t\", # ellipse of concentration\n repel = TRUE, # avoid overlapping (slows down)\n ggtheme = theme_light() #background color\n)\n\n\n\n#### hierarchical clustering\n#sample data\nidx <- sample(1:nrow(iris), 50)\nirisSample <- iris[idx,1:4]\n\n?hclust\n#calculation of a distance matrix\n?dist\ndistM = dist(irisSample)\ndistT = as.matrix(distM)\n\ndim(distT)\ndistT[1:5,1:5]\n\n#hierarchical clustering for different linkage methods\niris2.hc_complete <- hclust(distM, method=\"complete\")\niris2.hc_single <- hclust(distM, method=\"single\")\niris2.hc <- hclust(distM, method=\"average\")\niris2.hc_centroid <- hclust(distM, method=\"centroid\")\n\n#dendrograms for different clustering\n?plot\npar(mfrow=c(2,2))\nplot(iris2.hc, hang = -1, labels=iris$Species[idx])\nrect.hclust(iris2.hc, k=3, border=2:4)\n\nplot(iris2.hc_complete, hang = -1, labels=iris$Species[idx])\nrect.hclust(iris2.hc_complete, k=3, border=2:4)\n\nplot(iris2.hc_single, hang = -1, labels=iris$Species[idx])\nrect.hclust(iris2.hc_single, k=3, border=2:4)\n\nplot(iris2.hc_centroid, hang = -1, labels=iris$Species[idx])\nrect.hclust(iris2.hc_centroid, k=3, border=2:4)\npar(mfrow=c(1,1))\n\n#generates clusters\n?cutree\niris2.hc.groups <- cutree(iris2.hc, k=3)\niris2.hc.groups\n\n#compare clusters with original class labels\ntable(iris$Species[idx], iris2.hc.groups)\n\n##### dbscan algorithm ##########################\n\n?dbscan\n\n# MinPts parameter estimation\n# The idea is to calculate the average of the distances of every point to its k nearest\n# neighbors. The value of k will be specified by the user and corresponds to MinPts.\n# Next, these k-distances are plotted in an ascending order. The aim is to determine\n# the “knee”, which corresponds to the optimal eps parameter.\n# A knee corresponds to a threshold where a sharp change occurs along the k-distance\n# curve.\n\ndbscan::kNNdistplot(iris2, k=5)\nabline(h=0.5, lty=\"dashed\")\n\n# dbscan alg. execution\n\niris2.dbscan <- dbscan(iris2, eps=0.5, MinPts=5)\n\n#compare clusters with original class labels\n#cluster 0 means noise\ntable(iris$Species, iris2.dbscan$cluster)\n\niris2.dbscan <- dbscan(iris2, eps=0.4, MinPts=5)\ntable(iris$Species, iris2.dbscan$cluster)\n\n\n# plot clusters\nplot(iris2.dbscan, iris2)\nplot(iris2.dbscan, iris2[c(1,4)])\n\n############ Laboratory task ###################\n#calculation of accuracy\naccuracyCalc <- function(confTbl, startCol)\n{\n corr = 0;\n for(i in startCol:ncol(confTbl))\n {\n corr = corr + max(confTbl[,i]) \n }\n accuracy = corr/sum(confTbl)\n accuracy \n}\n\n#data set for the laboratory task\n#http://archive.ics.uci.edu/ml/datasets/Cardiotocography \n\ndownload.file('http://staff.ii.pw.edu.pl/~gprotazi/dydaktyka/dane/cardioto_noClass_corr.csv','cardioto_noClass_corr.csv')\nctg_noClass <- read.csv(\"cardioto_noClass_corr.csv\",row.names = 1)\n\ndownload.file('http://staff.ii.pw.edu.pl/~gprotazi/dydaktyka/dane/cardioto_all_corr.csv','cardioto_all_corr.csv')\nctg_all <- read.csv(\"cardioto_all_corr.csv\",row.names = 1)\n\n#example\ncard.kmeans = kmeans(ctg_noClass,10)\nres3 = table(ctg_all$CLASS,card.kmeans$cluster )\nres3\naccuracyCalc(res3,1)\n\n#wines\ndownload.file('http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv', 'wine_red.csv');\ndownload.file('http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv', 'wine_white.csv');\nwineRed_ds = read.table(\"wine_red.csv\", header = TRUE, sep=\";\", na.strings= \"*\")\nwineRed_dsC <- wineRed_ds[,-12]\n\n#example - wines\ncard.kmeans = kmeans(wineRed_dsC,6)\nres3 = table(wineRed_ds$quality,card.kmeans$cluster )\nres3\naccuracyCalc(res3,1)\n\n\n\n\n", "meta": {"hexsha": "85c62e3cc9816caae1f26dfc721d82a2905d0042", "size": 7018, "ext": "r", "lang": "R", "max_stars_repo_path": "labs/5/lab5_script.r", "max_stars_repo_name": "gardner-dev/data_mining", "max_stars_repo_head_hexsha": "1b2224cbb424057cde0a7be204d51270e3cf203e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-16T03:57:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T03:57:13.000Z", "max_issues_repo_path": "labs/5/lab5_script.r", "max_issues_repo_name": "gardner-dev/data_mining", "max_issues_repo_head_hexsha": "1b2224cbb424057cde0a7be204d51270e3cf203e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "labs/5/lab5_script.r", "max_forks_repo_name": "gardner-dev/data_mining", "max_forks_repo_head_hexsha": "1b2224cbb424057cde0a7be204d51270e3cf203e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3073929961, "max_line_length": 127, "alphanum_fraction": 0.7111712739, "num_tokens": 2046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7076947679380895}} {"text": "#' Iterator of numeric sequence with initial value and step size\n#'\n#' Constructs an iterator that generates a sequence of evenly spaced values\n#' starting with \\code{icount}. The step size is given by \\code{step}. By\n#' default, the sequence is neverending unless the optional \\code{stop} is\n#' provided.\n#'\n#' NOTE: Use a negative \\code{step} size to generate decreasing sequences.\n#'\n#' Often used as an argument to \\code{\\link[itertools2]{imap}} to\n#' generate consecutive data points.\n#'\n#' @export\n#' @param start sequence's initial value\n#' @param step sequence's step size\n#' @param stop optional stopping point to sequence\n#' @return sequence's iterator\n#'\n#' @examples\n#' it <- icount()\n#' iterators::nextElem(it)\n#' iterators::nextElem(it)\n#' iterators::nextElem(it)\n#'\n#' it2 <- icount(start=5.5, step=1.5)\n#' iterators::nextElem(it2)\n#' iterators::nextElem(it2)\n#' iterators::nextElem(it2)\n#'\n#' it3 <- icount(start=1, stop=3)\n#' iterators::nextElem(it3)\n#' iterators::nextElem(it3)\n#' iterators::nextElem(it3)\n#'\nicount <- function(start=0, step=1, stop=NULL) {\n start <- as.numeric(start)\n step <- as.numeric(step)\n\n if (length(start) != 1) {\n stop(\"'start' must be a numeric value of length 1\")\n }\n if (length(step) != 1) {\n stop(\"'step' must be a numeric value of length 1\")\n }\n\n if (!is.null(stop)) {\n stop <- as.numeric(stop)\n if (length(stop) != 1) {\n stop(\"'stop' must be a numeric value of length 1\")\n }\n }\n\n current_val <- start - step\n nextElem <- function() {\n current_val <<- current_val + step\n\n if (!is.null(stop) && current_val > stop) {\n stop(\"StopIteration\", call.=FALSE)\n }\n\n current_val\n }\n\n it <- list(nextElem=nextElem)\n class(it) <- c(\"abstractiter\", \"iter\")\n it\n}\n", "meta": {"hexsha": "7619c54c247759c2fa46265c8f87858608d7e6a9", "size": 1752, "ext": "r", "lang": "R", "max_stars_repo_path": "R/icount.r", "max_stars_repo_name": "ramhiser/itertools2", "max_stars_repo_head_hexsha": "471515f4e8cf0aa48cc6402741ad3feccca94a9b", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-02-02T02:54:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T12:07:34.000Z", "max_issues_repo_path": "R/icount.r", "max_issues_repo_name": "ramhiser/itertools2", "max_issues_repo_head_hexsha": "471515f4e8cf0aa48cc6402741ad3feccca94a9b", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2015-01-07T15:36:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-18T18:01:36.000Z", "max_forks_repo_path": "R/icount.r", "max_forks_repo_name": "ramhiser/itertools2", "max_forks_repo_head_hexsha": "471515f4e8cf0aa48cc6402741ad3feccca94a9b", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-02-02T05:04:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T02:13:12.000Z", "avg_line_length": 25.7647058824, "max_line_length": 75, "alphanum_fraction": 0.6546803653, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7076800696787381}} {"text": "# The algorithm is written in R. The lines starting with or followed by \"#\" are comments for functions, command lines, or delimiters of separate functions.\r\n###### Load packages \r\n###### Author: Qingyuan Yang and Marcus Bursik\r\n###### License: GPL. Use at your own risk.\r\n###### Requires: to run the examples, the appropriate CSV files are needed.\r\nlibrary(gstat)\r\nlibrary(sp)\r\nlibrary(rgdal)\r\nlibrary(RandomFields)\r\nlibrary(maptools)\r\nlibrary(raster)\r\nlibrary(deldir)\r\nlibrary(ggplot2)\r\nlibrary(segmented)\r\nlibrary(poweRlaw)\r\nlibrary(segmented)\r\nlibrary(geoR)\r\nlibrary(combinat)\r\n\r\n\r\n###### Workflow #########################################################################################################################################\r\n######(1) Calculate the distances, downwind distances of sample sites with respect to the input <------ function \"prep\"\t\t\t\t######\r\n###### source vent location and wind direction.\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t######\r\n######\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t######\r\n######(2) Apply segmented/simple linear regression to the datasets: the log-thickness is the linear <------ function \"sample.reg\"\t\t\t######\r\n###### combination of distance and downwind distance plus a constant.\t\t\t\t\t\t\t\t\t\t\t\t\t######\r\n######\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t######\r\n######(3) Record the fitted values and residuals from the fitting in step (2) <------ implemented by command lines\t\t######\r\n######\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t######\r\n######(4) Form a grid for mapping of the trend and the final result\t\t \t\t <------ function \"form.grid\"\t\t\t######\r\n######\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t######\r\n######(5) Form the trend model \t\t\t\t\t\t\t\t\t\t\t <------ function \"prep2\" and \"trendmodel\"\t######\r\n######\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t######\r\n######(6) Form and fit the variogram function of the residuals recorded in step (3)\t <------ function \"var.read\"\t\t\t######\r\n######\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t######\r\n######(7) Implemnt ordinary kriging using the residuals in step (3) and the variogram models <------ function \"prediction\"\t\t\t######\r\n###### from step (6) to form the local thickness variation. We take the sum of \t\t\t \t\t\t\t\t\t\t######\r\n###### the trend model in step (5) and the local variation to form the final thickness distribution\t\t\t\t\t\t\t\t######\r\n######\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t######\r\n###### End of workflow ##################################################################################################################################\r\n\r\n\r\n\r\n###### Functions ########################################################################################################################################\r\nprep <- function(sv, td, ang){\t\r\n\t\t\t\t\t\t\t\t\t\t\t\r\n### See step (1) in the workflow above\r\n### Input variables: \t\t\t\t\t\t\t\t\t ### Data type\t\t\t ### Column naes\r\n###\t\tsv: the source vent location\t\t\t\t\t\t\tdataframe\t\t\t\t\"x\" and \"y\"\r\n###\t\ttd: the tephra thickness dataset\t\t\t\t\t\tdataframe\t\t\t\t\"x\", \"y\", \"rz\" (real thickness), \"z\"(log-transformed thickness)\r\n###\t\tang: the inferred wind direction (from north clockwise)\t\ta single value\t\t\t \t -\r\n\r\n### Intermediate variables:\r\n###\t\tpts: the coordinates of sample sites\r\n###\t\tnr: the number of observations\r\n###\t\tsv.mtx: the matrix prepared for the computation of distance and downwind distance\r\n###\t\tdisp.mtx: the unit vector pointing along the wind direction for the computation of downwind distance\r\n###\t\tdist, dd, cd: computed distances, downwind distances, and crosswind distances from the sample sites to\r\n###\t\tthe source vent with the inferred wind direction\r\n\r\n### Output:\r\n###\t\tThe output is a dataframe that contains the original thickness dataset and the calculated distances, downwind\r\n###\t\tdistances, and the crosswind distances of the sample sites.\r\n\r\n\r\n### Method:\r\n###\t\tThis function uses a simple dot product to calculate the downwind distance\r\n\r\n\tpts <- as.matrix(td[,c(1,2)])\t\t\t\t\t\t\t\t\t### Extract the coordinates of sample sites\r\n\tsv <- as.matrix(sv)\r\n\tnr <- nrow(pts)\t\r\n\r\n\r\n\tsv.mtx <- matrix(ncol=2, nrow=nr)\t\t\t\t\t\t\t\t### Repeated rows of the coordinates of the source vent\r\n\tsv.mtx[,1] <- rep(sv[1], nr)\r\n\tsv.mtx[,2] <- rep(sv[2], nr)\r\n\r\n\r\n\tdisp.mtx <- c(sin(ang*pi/180),cos(ang*pi/180))\t\t\t\t\t\t### Form the unit vector pointing to the wind direction\r\n\r\n\t\r\n\tpts.mtx <- pts-sv.mtx\t\t\t\t\t\t\t\t\t\t### Calculate the distances, downwind distances, and crosswind distances\r\n\tpts.sq <- (pts.mtx)^2\t\t\t\t\t\t\t\t\t\t### of the sample sites\r\n\tdist<- (pts.sq[,1]+pts.sq[,2])^0.5\r\n\tdd <- pts.mtx %*% disp.mtx\r\n\tcd <-(dist^2-dd^2)^0.5\r\n \r\n\r\n\toutput <- as.data.frame(cbind(pts, dist, dd, cd, td[, c(3,4)]))\t\t\t### Reorganize the data for output\r\n\tcolnames(output) <- c(\"x\", \"y\", \"dist\", \"dd\", \"cd\", \"rz\", \"z\")\r\n\t\t\r\n\r\n\treturn(output)\r\n}\r\n\r\n###-----------------\r\n\r\nprep2 <- function(sv, td, ang){\r\n\r\n### This function is written for the computation of the trend model, which requires distances and \r\n### downwind distances of all the cells within the region of interest. Therefore this function works\r\n### exactly the same way as function \"prep\", except that the trend thicknesses of these cells are to\r\n### be computed. This function is called in the function \"trendmodel\" for further calculation of trend thickness.\r\n\r\n\r\n### Input variables: \t\t\t\t\t\t\t\t\t ### Data type\t\t\t ### Column names\r\n###\t\tsv: the source vent location\t\t\t \t\t\t\tdataframe\t\t\t\t\"x\" and \"y\"\r\n###\t\ttd: the coordinates of the cells of the grid\t\t\t\tdataframe or matrix\t\tdoes not matter, as they are transfered into matrix in this function\r\n###\t\tang: the inferred wind direction (from north clockwise)\t\ta single value\t\t\t -\r\n\r\n\r\n### Output variables:\r\n### \t\tThe output is a dataframe that records the coordinates, distances, downwind distances, and crosswind distances\r\n###\t\tof the cells of the grid.\r\n\r\n\tpts <- as.matrix(td[,c(1,2)])\r\n\tsv <- as.matrix(sv)\r\n\tnr <- nrow(pts)\t\r\n\r\n\r\n\tsv.mtx <- matrix(ncol=2, nrow=nr)\r\n\tsv.mtx[,1] <- rep(sv[1], nr)\r\n\tsv.mtx[,2] <- rep(sv[2], nr)\r\n\tdisp.mtx <- c(sin(ang*pi/180),cos(ang*pi/180))\r\n\r\n\t\r\n\tpts.mtx <- pts-sv.mtx\r\n\tpts.sq <- (pts.mtx)^2\r\n\tdist<- (pts.sq[,1]+pts.sq[,2])^0.5\r\n\tdd <- pts.mtx %*% disp.mtx\r\n\tcd <-(dist^2-dd^2)^0.5\r\n \r\n\r\n\toutput <- as.data.frame(cbind(pts, dist, dd, cd))\r\n\tcolnames(output) <- c(\"x\", \"y\", \"dist\", \"dd\", \"cd\")\r\n\t\t\r\n\r\n\treturn(output)\r\n}\r\n\r\n###-----------------\r\n\r\nsample.reg <- function(td, segdist, segdd){\r\n\r\n### See step (2) of the workflow above\r\n### This function provides two alternative fitting schemes for the fitting of thickness with distance and downwind distance:\r\n### \t(1) Use linear regression with the \"segmented\" fitting function to simulate\r\n###\t the different decay rates of tephra thickness within and outside the plume corner.\r\n\r\n###\t(2) Use simple linear regression for the fitting.\r\n\r\n###\tThis method will tend to use the segmented fitting option as it is better reconciled with the physics of tephra settling.\r\n### If error occurs, meaning that the data are inappropriate for option(1), a \"tryCatch\" function is set up to switch to \r\n###\toption(2).\r\n\r\n###\tInput variables:\r\n###\t\ttd: the output from function \"prep\"\r\n###\t\tsegdist: the inferred breakpoint for distance, this can be estimated by plotting the thickness against distance of the observations.\r\n###\t\tsegdd: the inferred breakpoint for downwind distance.\r\n\r\n### \tIntermediate functions:\r\n###\t\tsegfit: segmented fitting function\r\n###\t\tsimplefit: simple linear regression\r\n\r\n### \tOutput variables:\r\n###\t\tAn object that can be regarded as the fitted model. It contains the fitted values, residuals and the\r\n###\t\tcoefficients of the fitting. It can be used to predict the trend thickness for the grid and also store the residuals \r\n###\t\tfor ordinary kriging.\r\n\r\n###\t*** NOTES ***\r\n###\t\tThe segemented fitting runs iterative processes. Sometimes even with the same \"segdist\" and \"segdd\" inputs, it still\r\n###\t\tcomes up with different breakpoints and consequently slightly different coefficients. Most of the time, such variation\r\n###\t\tin the models is negligible, but we still suggest users to be careful when dealing with the segmented fitting.\r\n###\t\tThe goodness of fit can be examined by printing or plotting the residuals, which are stored in the output.\r\n### \t\tIf option (1) is being used, the output also contains the values of the breakpoints for the two variables.\r\n\t\t\r\n\tsegfit <-function(segdist, segdd){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### Segmented fitting function\r\n\t\treg.mod <- lm(z~ dist + dd,data=td)\r\n\t\t\tseg.lmmodel <- segmented(reg.mod, seg.Z = ~dist + dd, psi = list(dist = c(segdist), dd = c(segdd)))\r\n \treturn(seg.lmmodel)\r\n\t}\r\n\r\n\r\n\tsimplefit <-function(){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### Simple linear regression function\r\n\t\treg.mod <- lm(z ~ dist + dd ,data=td)\r\n \treturn(reg.mod)\r\n\t}\r\n\r\n\t\r\n\tresult = tryCatch(segfit(segdist, segdd),error=function(e){simplefit()})\t\t\t\t\t\t\t\t\t### TryCatch structure to automatically switch to simple linear regression\r\n\t\r\n\r\n return(result)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### when error occurs\r\n }\r\n\r\n###-----------------\r\n\r\nform.grid <- function(td, cellsize, displacement.coef, expanding.coef){\r\n### See step (4) in the workflow above\r\n### This function first finds the bounding box of the sample sites. It can be used as the extent of the grid.\r\n### However, sometimes one needs a larger extent. To do that, \"displacement.coef\" and \"expanding.coef\" are set.\r\n### \"displacement.coef\" determines if the lowerleft corner of the bounding box should be further shifted to \r\n### the lower left. \"expanding.coef\" determines if the length and width of the bouding box should be expanded.\r\n### These two values are all ratios. For example, for a 500*500 squared bounding box, if the 'displacement.coef\"\r\n### is set to be 1, then the lowerleft corner (if it was 0,0), will be moved to -500, -500. If the \"expanding.coef\"\r\n### is set to be 2, then the size of the new bounding box will be 1000*1000.\r\n\r\n### Input variables:\r\n### td: the output from function \"prep\"\r\n### cellsize: cellsize (a single value, as they are squared cells)\r\n### displacement.coef: explained above (a single value)\r\n### expanding.coef: explained above (a single value)\r\n\r\n\r\n### Output variables:\r\n### An empty grid\r\n\r\n\r\n td.sp <- SpatialPoints(cbind(td$x, td$y))\r\n bbox <- bbox(td.sp)\r\n cs <- c(cellsize, cellsize)\r\n cc <- as.numeric(ceiling(bbox[,1] + (cs / 2) - diff(t(bbox)) * displacement.coef))\r\n cd <- ceiling(diff(t(bbox)) / cs) * expanding.coef\r\n td.temp.grid <- GridTopology(cellcentre.offset = cc, cellsize = cs, cells.dim = cd)\r\n td.grid <- SpatialGrid(td.temp.grid)\r\n return(td.grid)\r\n} \r\n\r\n###-----------------\r\n\r\ntrendmodel <- function(td, sv, grid, ang, ftng.rslt){\r\n### See step (5) in the workflow above\r\n### This function calculates the distances, downwind distances of the cells of the grid, and makes the\r\n### prediction of trend thickness using the model from function \"sample.reg\".\r\n\r\n### Input variables:\r\n###\t\ttd: the output from function \"prep\"\r\n###\t\tsv: the source vent coordinate\r\n###\t\tgrid: the output from function \"form.grid\"\r\n###\t\tang: the inferred wind direction (from north clockwise)\r\n###\t\tftng.rslt: the output from function \"sample.reg\"\r\n\r\n\r\n### Output variables:\r\n### A dataframe that contains the coordinates, distances, downwind and crosswind distances, trend thicknesses and \r\n### trend thicknesses in logarithm form for all the cells within the grid.\r\n\r\n\ttd.grid <- SpatialPoints(as(grid, \"SpatialPixels\"))\r\n\ttd.grid.coord <- coordinates(td.grid)\r\n\r\n\r\n\t\tgrided<- prep2(sv, td.grid.coord, ang)\r\n\r\n\t\r\n\t\tgridz <- predict(ftng.rslt, data.frame(cbind(dist = grided$dist, dd = grided$dd)))\r\n\t\tgridrz <- 10^gridz\r\n\r\n\t\t\r\n\toutput <- as.data.frame(cbind(grided, gridrz, gridz))\r\n\tcolnames(output) <- c(\"x\", \"y\", \"dist\", \"dd\", \"cd\", \"zr\", \"z\")\r\n\r\n\t\r\n\treturn(output)\r\n}\r\n\r\n###-----------------\r\n\r\nvar.read <- function(td, width.val, cutoff.val, var.par, var.model){\r\n### This function reads the locations of the sample sites and the residuals from the fitting in function \"sample.reg\" to \r\n### form and fit a variogram model. This function serves as a preparation for ordinary kriging.\r\n\r\n### Input variables:\r\n###\t\ttd: the output from function \"prep\"\r\n###\t\twidth.val & cutoff.val: the parameters to calculate the experimental variogram. \"width.val\" denotes the\r\n###\t\taveraged lag for the computation, and \"cutoff.val\" is the maximum lag that is taken into consideration for the \r\n###\t\tcalculation.\r\n###\t\tvar.par: the parameters required for fitting variogram models. It includes three values, namely sill, range, and nugget.\r\n###\t\tDetailed explanations of these parameters can be found in any geostatistics reference.\r\n###\t\tvar.model: a text variable which describes the shape of different variogram models, type the command line \"show.vgms()\" to view a list\r\n###\t\tof variogram models.\r\n\r\n### Output variables:\r\n###\t\tThe output is a list, the first object of the list is the variogram model, which is the main output.\r\n###\t\tThe second object is the plot of the experimental variogram and the fitted variogram curve.\r\n###\t\tThe third object is the values of the experimental variogram\r\n\r\n td.sp <- SpatialPointsDataFrame(cbind(td$x, td$y), td)\r\n td.var <- variogram(res ~ 1, td.sp, width=width.val, cutoff = cutoff.val)\r\n\r\n\r\n\r\n td.vgm <- vgm(psill=var.par[1], model=var.model, range=var.par[2], nugget=var.par[3])\r\n td.fit <- fit.variogram(td.var, td.vgm, fit.sills = c(TRUE, TRUE)) \r\n return(list(td.fit,plot(td.var,td.fit),td.var))\r\n}\r\n\r\n###-----------------\r\n\r\nprediction <- function(td, max, min, maxdist, grid, trend, variog){\r\n### This function first implements ordinary kriging on the residuals to construct the local variation map, and then\r\n### takes the sum of trend and local variation to present the final result.\r\n\r\n### Input variables:\r\n###\t\ttd: the output from function \"prep\"\r\n###\t\tmax:\r\n###\t\tmin:\r\n###\t\tmaxdist:\r\n###\t\t\tThe \"max\" and \"min\" variables describe the maximum and minimum number of observations taken into account \r\n###\t\t\tfor the kriging estimation at a single cell. \"maxdist\" is used to define a maximum radius beyond which the \r\n###\t\t\tsample sites are assumed non-related to a particular cell.\r\n###\t\tgrid: the output from function \"form.grid\"\r\n###\t\ttrend: the output from function \"trendmodel\"\r\n###\t\tvariog: the first object of the output from function \"var.read\"\r\n\r\n### Output variables:\r\n###\t\tThe output is a dataframe that contains the columns of the output of function \"trendmodel\". In addition to that,\r\n###\t\tit also has the predicted thickness and its logarithm, and the variance of kriging estimation.\r\n###\t\tHere the variance only represents the variance from kriging the log-residuals of the observations and thus cannot\r\n###\t\tbe used to characterize the total variance of this method.\r\n\r\n\r\n\ttd.sp <- SpatialPointsDataFrame(cbind(td$x, td$y), td) \r\n\ttd.temp.k <- krige(res ~ 1, td.sp, nmax = max, nmin = min, maxdist = maxdist, grid, variog)\r\n\tk.result <- td.temp.k$var1.pred\r\n\tk.result[is.na(k.result)] <- 0\r\n\tk.variance <- td.temp.k$var1.var\r\n\tk.rz <- 10^(k.result + trend$z)\r\n\r\n\r\n\toutput <- cbind(trend, k.result, k.variance, k.rz)\r\n\r\n\r\nreturn(output)\r\n}\r\n\r\n\r\n###### End of functions ####################################################################################################\r\n\r\n\r\n\r\n###### Demo ################################################################################################################\r\n\r\nsetwd(\"C:\\\\Users\\\\working directory\")\t\t\t\t\t\t\t\t\t\t### Set working directory, \"\\\" has to be replaced by \"\\\\\". Change to \"/\" for *nix, mac.\r\ntd <- read.table(\"thickness dataset.csv\", header=TRUE, sep=\",\")\t\t\t\t\t\t### Read the thickness dataset\r\nsv <- read.table(\"source vent.csv\", header=TRUE, sep=\",\")\t\t\t\t\t\t\t### Read source vent location\r\n\r\ntd <- prep(sv, td, 20)\t\t\t\t\t\t\t\t\t\t\t\t\t### Calculate the distances, downwind distances, and crosswind distances of the sample sites,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### here the wind direction is 20 degree from north clockwise.\r\n\r\nmodel <- sample.reg(td, 3000,3000)\t\t\t\t\t\t\t\t\t\t\t### Form either the segmented or the simple linear regression model of thickness against\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### distance and downwind distance. The breakpoints for the two variables are set as\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### 3000 and 3000 meters.\r\n\r\ntd$fit <- model$fitted.values\t\t\t\t\t\t\t\t\t\t\t\t### Expand \"td\" by storing the fitted values and\r\ntd$res <- model$residuals\t\t\t\t\t\t\t\t\t\t\t\t### residuals from the fitting in the last command line\r\n\r\ngrid <- form.grid(td, 500, 0.1, 1.2)\t\t\t\t\t\t\t\t\t\t\t### Form the grid.\r\n\r\ntrend <- trendmodel(td, sv, grid, 20, model)\t\t\t\t\t\t\t\t\t### Form the trend. Note the wind direction has to be set again for\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### the calculation of grid cells, and the two wind directions have to be the same.\r\n\t\r\nvar <- var.read(td, 300,10000, c(0.04,5000,0.01), \"Cir\")\t\t\t\t\t\t\t### Form the variogram model. The parameters are explained in the \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### description of function \"var.read\"\r\n\r\nresult <- prediction(td, 50,20, 5000, grid,trend, var[[1]])\t\t\t\t\t\t\t### Calculate the local variation, and take its sum and trend thickness for final result.\r\n\r\n\r\nresult.sp <- SpatialPixelsDataFrame(cbind(trend$x, trend$y), result)\t\t\t\t\t### Turn the final result into \"SpatialPixelsDataFrame\" for visualization.\r\nspplot(result.sp[\"k.rz\"])\tor\tspplot(result.sp[\"zr\"])\t\t\t\t\t\t\t### Plot the final result or the trend model.\r\n\r\nlevels <- c(0,250,500,1000,2000,3000,5000,10000,20000)\t\t\t\t\t\t\t\t### Set up the levels for plotting the isopach map.\r\nisomap <- ContourLines2SLDF(contourLines(as.image.SpatialGridDataFrame(result.sp[\"k.rz\"]), levels = levels))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### Form the isopach map\r\n\r\nplot(isomap)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### Plot the isopach map\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### Note: \"isomap\" is a \"SpatialLinesDataFrame\" and can be used in GIS programs for further mapping purposes.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### Geo-referencing can be done in R or GIS programs.\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### ***Notes on infer the extent of tephra fall deposits:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### (1) Add one unit thickness to all the observations and log-transform them.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### (2) Apply these transformed log-thickness to the method\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### (3) Specify the \"levels <- c(1)\" and apply it to \"ContourLines2SLDF\" function to find the unit thickness isopach\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### (4) The resultant contour is the inferred extent.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### ***\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### The resultant contour is strongly influenced by the trend model,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t### as normally fewer observations are made on the distal and thin parts of a tephra fall deposit\r\n\r\n\r\n###### End of demo ##########################################################################################################\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "a105a9af092ce518c4b7bea04a7be236f56d80a5", "size": 18633, "ext": "r", "lang": "R", "max_stars_repo_path": "optimizedTTDv1.r", "max_stars_repo_name": "yiqioyang/ttd", "max_stars_repo_head_hexsha": "467931aca0eb5d237e238eca813857c495aac48f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimizedTTDv1.r", "max_issues_repo_name": "yiqioyang/ttd", "max_issues_repo_head_hexsha": "467931aca0eb5d237e238eca813857c495aac48f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimizedTTDv1.r", "max_forks_repo_name": "yiqioyang/ttd", "max_forks_repo_head_hexsha": "467931aca0eb5d237e238eca813857c495aac48f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8987951807, "max_line_length": 157, "alphanum_fraction": 0.6165405463, "num_tokens": 4407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7075144631445585}} {"text": "# Selection of matrix elements\n# my_matrix[1,2]: selects the element at the first row and second column.\n# my_matrix[1:3,2:4]: results in a matrix with the data on the rows 1, 2, 3 and columns 2, 3, 4.\n# my_matrix[,1]: selects all elements of the first column.\n# my_matrix[1,]: selects all elements of the first row.\n\n# all_wars_matrix is available in your workspace\nall_wars_matrix\n\n# Select the non-US revenue for all movies\nnon_us_all <- all_wars_matrix[,2]\n \n# Average non-US revenue\nmean(non_us_all)\n \n# Select the non-US revenue for first two movies\nnon_us_some <- all_wars_matrix[1:2, 2]\n \n# Average non-US revenue for first two movies\nmean(non_us_some)\n", "meta": {"hexsha": "4880c4e86f714fa78388b4228b59b9e85b80fb54", "size": 664, "ext": "r", "lang": "R", "max_stars_repo_path": "R/DataAnalyst/Basics/matrix-selection.r", "max_stars_repo_name": "James-McNeill/Learning", "max_stars_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/DataAnalyst/Basics/matrix-selection.r", "max_issues_repo_name": "James-McNeill/Learning", "max_issues_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/DataAnalyst/Basics/matrix-selection.r", "max_forks_repo_name": "James-McNeill/Learning", "max_forks_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.619047619, "max_line_length": 96, "alphanum_fraction": 0.7484939759, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7074331216886407}} {"text": "x_values <- c(9,11,15)\r\n\r\ny_values <- c(-15,-8,2,8)\r\n\r\nprxs <- c(0.38, 0.29, 0.33)\r\n\r\nprys <- c()\r\n\r\nprCongiunta <- c()\r\n\r\npry_x <- c(0.25, 0.30, 0.20, 0.25,\r\n 0.22, 0.27, 0.25, 0.26,\r\n 0.20, 0.30, 0.23, 0.27)\r\n\r\nmatrixy_x <- matrix(data = pry_x, ncol = length(y_values), nrow = length(x_values), byrow = TRUE);\r\n\r\n\r\nvaloreAttesoX <- 0\r\n\r\nfor( i in 1:length(x_values) ){\r\n\r\n valoreAttesoX <- valoreAttesoX + prxs[i] * x_values[i];\r\n\r\n}\r\n\r\n\r\nvarianzaX <- 0\r\n\r\nfor( i in 1:length(x_values) ){\r\n\r\n varianzaX <- varianzaX + prxs[i] * (x_values[i] - valoreAttesoX)^2;\r\n\r\n}\r\n\r\n\r\nfor( i in 1:length(x_values) ){\r\n\r\n for( j in 1:length(y_values) ){\r\n\r\n prCongiunta <- c(prCongiunta, matrixy_x[i,j] * prxs[i]);\r\n\r\n }\r\n\r\n}\r\n\r\n\r\nmatrixCongiunta <- matrix(data = prCongiunta, nrow = length(x_values), ncol = length(y_values), byrow = TRUE);\r\n\r\nfor( i in 1:length(y_values) ){\r\n\r\n prys <- c(prys, sum(matrixCongiunta[,i]));\r\n\r\n}\r\n\r\nprx_y <- c()\r\n\r\nfor( i in 1:length(x_values)){\r\n\r\n for( j in 1:length(y_values)){\r\n prx_y <- c(prx_y, matrixCongiunta[i,j] / prys[j] )\r\n }\r\n\r\n}\r\n\r\nmatrixx_y <- matrix(data=prx_y, nrow = length(x_values), ncol = length(y_values), byrow = TRUE);\r\n\r\nvaloreAttesoX_Y <- c();\r\n\r\nfor( j in 1:length(y_values) ){\r\n\r\n somma <- 0\r\n for( i in 1:length(x_values) ){\r\n\r\n somma <- somma + x_values[i] * matrixx_y[i,j];\r\n\r\n }\r\n\r\n valoreAttesoX_Y <- c(valoreAttesoX_Y, somma);\r\n\r\n}\r\n\r\n\r\nvarianzaValoreAttesoX_Y <- 0\r\n\r\nfor( j in 1:length(y_values) ){\r\n\r\n varianzaValoreAttesoX_Y <- varianzaValoreAttesoX_Y + (valoreAttesoX_Y[j] - valoreAttesoX)^2 * prys[j];\r\n\r\n}\r\n\r\nvaloreAttesoVarianzaX_Y <- varianzaX - varianzaValoreAttesoX_Y;\r\n\r\ncat(\"X\\n\")\r\nprint(matrix(data=c(x_values,prxs), ncol = length(x_values), byrow = TRUE))\r\n\r\ncat(\"\\nY\\n\")\r\nprint(matrix(data=c(y_values,prys), ncol = length(y_values), byrow = TRUE))\r\n\r\ncat(\"\\nProbabilita congiunta\\n\")\r\nprint(matrixCongiunta)\r\n\r\ncat(\"\\nX|Y\\n\")\r\nprint(matrixx_y)\r\n\r\ncat(\"\\nY|x\\n\")\r\nprint(matrixy_x)\r\n\r\ncat(\"\\nRisposte\\n\")\r\nprint(valoreAttesoX);\r\nprint(varianzaX)\r\nprint(varianzaValoreAttesoX_Y)\r\nprint(valoreAttesoVarianzaX_Y)\r\n", "meta": {"hexsha": "437affbf25676ec218a83db548afb7ddfd809e63", "size": 2120, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 46.r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio 46.r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio 46.r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7610619469, "max_line_length": 111, "alphanum_fraction": 0.6146226415, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7073582084341143}} {"text": "=begin\n # sample-m-factorize02.rb\n\n require \"algebra\"\n \n Z7 = ResidueClassRing(Integer, 7)\n P = MPolynomial(Z7)\n x, y, z = P.vars(\"xyz\")\n f = x**3 + y**3 + z**3 - 3*x*y*z\n p f.factorize #=> (x + 4y + 2z)(x + 2y + 4z)(x + y + z)\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "4b5206922238fab7a563b185820bb99fd89e51e4", "size": 258, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-m-factorize02.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-m-factorize02.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-m-factorize02.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8461538462, "max_line_length": 57, "alphanum_fraction": 0.5310077519, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.7072708248258406}} {"text": "# MULTIPLY transaction rates in a given cycle to obtain possible profit\nbf.mult <- function(edges, rates, cycle) {\n\n profit = 1\n\n # find and multiply by pairs\n for (i in 1:(NROW(cycle)-1)) {\n next_value = rates[which(edges[,1]==cycle[i] & edges[,2]==cycle[i+1])]\n profit = profit * as.numeric(next_value)\n }\n\n # as number\n return(profit)\n}\n\n# RETRIEVE a path given a predecessor array and a source/target pair of nodes\nbf.path <- function(nodes, prevs, terminal) {\n\n path = as.matrix(c(terminal))\n prev = nodes[prevs[which(nodes==terminal)]]\n\n # track util repeated element\n while (sum(path==prev) == 0) {\n path = rbind(path, prev)\n prev = nodes[prevs[which(nodes==prev)]]\n }\n\n # add repeated element\n path = rbind(path, prev)\n\n # trim the fat\n trim.bound = which(path==prev)[1]\n path = path[trim.bound:NROW(path)]\n path = as.matrix(rev(path))\n\n # as matrix\n return(path)\n}\n\n# APPLY classic Bellman-Ford Algorithm\nbf.find <- function(graph, summary, debug=T) {\n\n # receive an EDGE LIST with the following format:\n #\n # [,1] [,2] [,3]\n # [1,] node 1 node 2 weight\n # [1,] node 1 node 3 weight\n # [1,] node 2 node 1 weight\n # . . . .\n # . . . .\n # . . . .\n\n # ready data\n edges = as.matrix(graph)\n nodes = unique(matrix(edges[,1:2], ncol=1))\n weights = as.numeric(as.character(edges[,3]))\n\n # ready state\n dists = rep(Inf, NROW(nodes))\n prevs = rep(NULL, NROW(nodes))\n\n # distance from source is zero\n # source is always the artificial node\n dists[1] = 0\n\n if (debug) {\n cat(\"Applying Bellman-Ford algorithm\\n\")\n }\n\n for (i in 1:(NROW(nodes)-1)) { # this can STILL stop earlier\n\n if (debug) {\n cat(\" exploring paths with\", i, \"steps away from source\\n\")\n }\n\n for (j in 1:NROW(edges)) {\n if (dists[which(nodes==edges[j,1])] + weights[j] < dists[which(nodes==edges[j,2])]) {\n dists[which(nodes==edges[j,2])] = dists[which(nodes==edges[j,1])] + weights[j]\n prevs[which(nodes==edges[j,2])] = which(nodes==edges[j,1])\n }\n }\n }\n\n # test for negative cycles\n cycle = NULL\n for (i in 1:NROW(edges)) {\n\n # a path with NROW(nodes) steps can only occur via a negative cycle\n if (dists[which(nodes==edges[i,1])] + weights[i] < dists[which(nodes==edges[i,2])]) {\n cycle = bf.path(nodes, prevs, edges[i,1])\n\n if (debug) {\n cat(\"Arbitrage cycle found!\\n\")\n print(cycle)\n }\n\n break\n }\n }\n\n # then find possible profit\n profit = NULL\n if (NROW(cycle) > 0) {\n rates = as.numeric(as.character(summary[,3]))\n profit = bf.mult(edges, rates, cycle)\n\n if (debug) {\n cat(\"Possible profit:\", profit, \"\\n\")\n }\n } else {\n\n if (debug) {\n cat(\"No negative cycles found :(\\n\")\n }\n }\n\n ret = list()\n ret$nodes = nodes\n ret$cycle = cycle\n ret$profit = profit\n\n return(ret)\n}\n\n# APPLY Bellman-Ford SPFA variation algorithm\nbf.spfa <- function(graph, summary, SLF=F, debug=T) {\n\n # This implementation improves upon the traditional Bellman-Ford algorithm:\n # - Nodes are only explored if edges connecting to it could be relaxed in\n # the previous step, severely improving average case runs\n # - Small Label First induces exploration of closer nodes first, improving\n # further even the average case performance\n\n # ready data\n edges = as.matrix(graph)\n nodes = unique(matrix(edges[,1:2], ncol=1))\n weights = as.numeric(as.character(edges[,3]))\n\n # ready state\n dists = rep(Inf, NROW(nodes))\n prevs = rep(NULL, NROW(nodes))\n\n # worst case iter count\n max_iters = NROW(nodes) - 1\n\n # distance from source is zero\n # source is always the artificial node\n dists[1] = 0\n\n # Q behaves as a FIFO queue\n # ...also, add source to it\n Q = c(1)\n\n if (debug) {\n cat(\"Applying Bellman-Ford SPFA variation\\n\")\n }\n\n while (NROW(Q) > 0) {\n # get front\n node = Q[1]\n Q = Q[-which(Q==node)]\n\n if (debug) {\n cat(\" currently exploring node\", node, \"\\n\")\n }\n\n # neighbor node edge ids\n edge.ids = which(edges[,1]==nodes[node])\n\n for (i in 1:NROW(edge.ids)) {\n\n # distance inbetween\n distance = weights[edge.ids[i]]\n\n # neighbor node number\n neighbor = which(nodes==edges[edge.ids[i], 2])\n\n if (dists[node] + distance < dists[neighbor]) {\n dists[neighbor] = dists[node] + distance\n prevs[neighbor] = node\n\n # add to queue (only once)\n if (sum(Q==neighbor) == 0) {\n Q = c(Q, neighbor)\n\n # >>> Optimization: SLF <<<\n if ((SLF) & (dists[neighbor] < dists[Q[1]])) {\n Q = c(neighbor, Q[1:(NROW(Q)-1)])\n }\n }\n }\n }\n\n # necessary for worst case\n max_iters = max_iters - 1\n if (max_iters == 0) {\n break\n }\n }\n\n # find negative cycle\n cycle = NULL\n profit = NULL\n for (i in 1:NROW(edges)) {\n\n u = which(nodes==edges[i, 1]) # node\n v = which(nodes==edges[i, 2]) # neighbor\n\n # only possible in the presence of negatie cycles\n if (dists[u] + weights[i] < dists[v]) {\n\n # cycle path\n cycle = bf.path(nodes, prevs, edges[i,1])\n\n # cycle mult\n rates = as.numeric(as.character(summary[,3]))\n profit = bf.mult(edges, rates, cycle)\n\n if (debug) {\n cat(\"Arbitrage cycle found!\\n\")\n print(cycle)\n cat(\"Possible profit:\", profit, \"\\n\")\n }\n\n break\n }\n }\n\n # case of \"failure\"\n if (NROW(cycle) == 0) {\n if (debug) {\n cat(\"No negative cycles found :(\\n\")\n }\n }\n\n ret = list()\n ret$nodes = nodes\n ret$cycle = cycle\n ret$profit = profit\n\n return(ret)\n}\n", "meta": {"hexsha": "5efcea720a5f14f61d5353888b52cd7f9b7b33ae", "size": 6273, "ext": "r", "lang": "R", "max_stars_repo_path": "assignment1/bf-arbitrate.r", "max_stars_repo_name": "felipecustodio/ai", "max_stars_repo_head_hexsha": "55f332d7070b79833d005ee2c2243c9e67d6e7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-03T03:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-03T03:12:39.000Z", "max_issues_repo_path": "assignment1/bf-arbitrate.r", "max_issues_repo_name": "felipecustodio/ai", "max_issues_repo_head_hexsha": "55f332d7070b79833d005ee2c2243c9e67d6e7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-08T11:52:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-19T03:12:42.000Z", "max_forks_repo_path": "assignment1/bf-arbitrate.r", "max_forks_repo_name": "felipecustodio/ai", "max_forks_repo_head_hexsha": "55f332d7070b79833d005ee2c2243c9e67d6e7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8148148148, "max_line_length": 97, "alphanum_fraction": 0.5214410968, "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7071971506658136}} {"text": "# vector c attached to each node in the modwpt transform (Percival and Walden, page 215)\n# vector c will be used to align LA wavelet coefficients\ngetC=function(j,n)\n{\n vectorC=c();\n if (j==1)\n {\n if (n==0) vectorC=0\n else vectorC=1\n return(vectorC)\n \n }\n else\n {\n if (((n%%4)==0)||((n%%4)==3))\n return(c(getC(j-1,floor(n/2)),0))\n else \n return(c(getC(j-1,floor(n/2)),1))\n }\n \n}\n\n# Auxiliary function used to calculate time shifts for wavelets(Percival and walden,229-230)\n# This function will return c(Sjn0,Sjn1) \ngetSc=function(j,n)\n{\n vectorC=getC(j,n)\n Sjn1=(sum(vectorC*2^(0:(j-1))))\n Sjn0=2^j-1-Sjn1\n return (c(Sjn0,Sjn1))\n \n \n}\n# Auxiliary function used to calculate time shifts for LA wavelets(Percival and walden,229-230)\ngetLj=function(j,wf)\n{\n #length of the wave filter\n L=length(wave.filter(wf)$lpf)\n Lj=(2^j-1)*(L-1)+1\n return(Lj)\n}\n\n#getVjnLA returns time shifts for la8,la16 and la20 wavelets in modwpt\ngetVjnLA=function(j,n,wf)\n{\n aux=getSc(j,n);\n Sjn1=aux[2];\n return(abs(-getLj(j,wf)/2+(2^(j-1)-Sjn1)))\n}\n\n#performs left circular shift\ncircularShift=function(x,n)\n{\n l=length(x)\n if ((n==0)||(n==l)) return(x)\n if ((n<0)||(n>l)) {n=n%%l}\n return(c(x[(n+1):l],x[1:n]))\n}\n# aligns <> wavelet coefficients from modwpt using <> wavelet. <> are the\n# (j.n) node wavelet coefficients. <> should be \"l8\",\"l16\" or \"l20\". If not, not \n# alignment is perform\nalign=function(x,j,n,wf)\n{ \n #return(x)\n if ((wf!=\"la8\")&&(wf!=\"la16\")&&(wf!=\"la20\")) \n { \n #general method\n return(circularShift(x,CenterOfEnergyAdvances(j,n,wf)))\n }\n else\n { #specific method for LA wavelets\n return(circularShift(x,getVjnLA(j,n,wf)))\n }\n}\n\n\n#shift applicable to (almost) every filter using the notion of the 'center of\n#energy' by Hess-Nielsen and Wickerhauser.\n# Walden page 231\n\n# gets the appropiate advance for the (j.n) node of the <> wavelet. \nCenterOfEnergyAdvances=function(j,n,wf)\n{\n #variables for the computation\n S=getSc(j,n)\n E=CenterEnergies(wf)\n advance=round( S[1]*E[1]+S[2]*E[2] ) \n \n \n return (advance)\n}\n\n# gets the center of energy for both wf filters\nCenterEnergies=function(wf)\n{\n waveletFilter=wave.filter(wf)\n #Center ofEnergy of the scaling filter\n cesf=computeCenterEnergy(waveletFilter$length,waveletFilter$lpf);\n #Center ofEnergy of the wavelet filter\n cewf=computeCenterEnergy(waveletFilter$length,waveletFilter$hpf);\n return (c(cesf,cewf))\n \n}\n\n#auxiliar function: gets the center of energy of coefs. length(coefs)=l\ncomputeCenterEnergy=function(l,coefs){\n auxVector=0:(l-1)\n coefs2=(coefs)^2\n a=coefs2%*%auxVector\n b=sum(coefs2)\n return (a/b)\n}", "meta": {"hexsha": "2cc1eda35d65b01d579fd4a7d25ca97af00eed91", "size": 2673, "ext": "r", "lang": "R", "max_stars_repo_path": "RHRV/getC.r", "max_stars_repo_name": "med-material/ArduinoLoggerShinyApp", "max_stars_repo_head_hexsha": "6c80e9a8015946dbdba29087e35e487dcd4493eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RHRV/getC.r", "max_issues_repo_name": "med-material/ArduinoLoggerShinyApp", "max_issues_repo_head_hexsha": "6c80e9a8015946dbdba29087e35e487dcd4493eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-01-23T08:30:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T11:58:03.000Z", "max_forks_repo_path": "RHRV/getC.r", "max_forks_repo_name": "med-material/ArduinoLoggerShinyApp", "max_forks_repo_head_hexsha": "6c80e9a8015946dbdba29087e35e487dcd4493eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-30T09:42:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-30T09:42:11.000Z", "avg_line_length": 23.8660714286, "max_line_length": 95, "alphanum_fraction": 0.6651702207, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7071937837223861}} {"text": "svdopt <- function(R, k, lr = 0.05, reg = 0.002, miter = 10) {\n\tglobal_mean <- mean(as.matrix(R[,3]), na.rm = TRUE)\n\tbu <- rep(0, max(R[,1]))\n\tbi <- rep(0, max(R[,2]))\n\tnusers <- max(R[,1])\n\tnitems <- max(R[,2])\n\tP <- matrix(rnorm(nusers*k, mean=0, sd=0.1), nusers, k)\n\tQ <- matrix(rnorm(nitems*k, mean=0, sd=0.1), nitems, k)\n\terror <- list()\n\n\tfor(l in 1:miter) {\n\t\tsq_error <- 0\n\t\tfor(j in 1:nrow(R)) {\n\t\t\tu <- R[j,1]\n\t\t\ti <- R[j,2]\n\t\t\tr_ui <- R[j,3]\n\t\t\tpred <- global_mean + bu[u] + bi[i] + P[u, ] %*% Q[i,]\n\t\t\te_ui <- r_ui - pred\n\t\t\tsq_error <- sq_error + e_ui^2\n\t\t\tbu[u] <- bu[u] + lr * e_ui\n\t\t\tbi[i] <- bi[i] + lr * e_ui\n\t\t\tfor(f in 1:k) {\n\t\t\t\ttemp_uf <- P[u,f]\n \t\tP[u,f] <- P[u,f] + lr * (e_ui * Q[i,f] - reg * P[u,f])\n\t\t\t Q[i,f] <- Q[i,f] + lr * (e_ui * temp_uf - reg * Q[i,f])\n\t\t\t}\n\t\t}\n\t\terror <- c(error, sqrt(sq_error/nrow(R)))\n\t}\n\n\treturn(list(bu = bu, bi = bi, P = P, Q = Q, error = error))\n}\n", "meta": {"hexsha": "8d7962d27fe92ef32e1e1015d8313cc542d55322", "size": 917, "ext": "r", "lang": "R", "max_stars_repo_path": "class/class-3/svdopt.r", "max_stars_repo_name": "felipecustodio/recommender-systems", "max_stars_repo_head_hexsha": "902655d0c6b9a8058223b6e3d2db11589ad12ab8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "class/class-3/svdopt.r", "max_issues_repo_name": "felipecustodio/recommender-systems", "max_issues_repo_head_hexsha": "902655d0c6b9a8058223b6e3d2db11589ad12ab8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "class/class-3/svdopt.r", "max_forks_repo_name": "felipecustodio/recommender-systems", "max_forks_repo_head_hexsha": "902655d0c6b9a8058223b6e3d2db11589ad12ab8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7878787879, "max_line_length": 65, "alphanum_fraction": 0.4852780807, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7067578992977125}} {"text": "pravd.f = function(x,p){\r\n plot(x, p, # plna kolecka - v skutecnych hodnotach\r\n ylab='p(x)',xaxt='n',pch=19,ylim=c(0,max(p)),main=\"Pravdepodobnostni funkce\") \r\n lines(c(min(x)-100,max(x)+100),c(0, 0))\r\n for(i in 1:length(x)){\r\n lines(c(min(x)-100,max(x)+100), c(p[i],p[i]),\r\n type = 'l', lty = 3, lwd=0.5) # horizontalni grid\r\n lines(c(x[i],x[i]), c(-0.1,1.1), \r\n type = 'l', lty = 3, lwd=0.5) # vertikalni grid\r\n }\r\n par(new=TRUE) # ze chceme kreslit do jednoho grafu\r\n plot(x, p*0, # prazdna kolecka - tam kde je definovana nenulova hodnota\r\n ylab='p(x)', xaxt='n', ylim=c(0,max(p)))\r\n axis(1, at=x,labels=x) # nastaveni hodnot na X\r\n axis(4, at=p,labels=p, las=2, cex.axis=0.7, tck=-.01) # a Y\r\n}\r\n\r\n\r\ndist.f = function(x,p){\r\n F = cumsum(p)\r\n F_ext = c(0, F) # natahneme F o 0 na zacatku\r\n x_ext = c(x[1]-1, x, x[length(x)]+1) # a x z obou stran\r\n \r\n plot(x, F, ylab=\"F(x)\", xaxt='n', ylim=c(0,1), # prazdna kolecka\r\n type='p', main=\"Distribucni funkce\") \r\n par(new=TRUE) # ze chceme kreslit do jednoho grafu\r\n plot(x, F_ext[1:(length(F_ext)-1)], # plna kolecka\r\n ylab=\"F(x)\", xaxt='n', ylim=c(0,1), type='p', pch=19) \r\n \r\n for(i in 1:(length(x_ext)-1)){\r\n lines(c(min(x)-100,max(x)+100), c(F_ext[i],F_ext[i]),\r\n type = 'l', lty = 3, lwd=0.5) # horizontalni grid\r\n lines(c(x_ext[i],x_ext[i]), c(-0.1,1.1), \r\n type = 'l', lty = 3, lwd=0.5) # vertikalni grid\r\n lines(x_ext[i:(i+1)], c(F_ext[i],F_ext[i])) # graf - cary\r\n }\r\n axis(1, at=x,labels=x) # nastaveni hodnot na X\r\n axis(4, at=F,labels=F, las=2, cex.axis=0.7, tck=-.01) # a Y\r\n #return(F)\r\n}\r\n\r\nsouhrn=function(x,p){\r\n EX = sum(x*p)\r\n EX2 = sum(x*x*p) \r\n DX = EX2-EX^2\r\n sigma.X = sqrt(DX)\r\n modus = x[match(max(p),p)]\r\n # zapis vysledku do tabulky\r\n tab = rbind(EX, DX, sigma.X, modus)\r\n tab.popis = c(\"str. hodnota\",\"rozptyl\",\"smer. odchylka\", \"modus\")\r\n rownames(tab) = tab.popis\r\n colnames(tab) = \"\"\r\n return(tab)\r\n}\r\n\r\n\r\n# 1A\r\n# Pouzijeme Hypergeometrickou vetu, kde vybirame pocet uspechu v n zavislych pokusech\r\n# X ... pocet projektu bez chyb mezi 4 vybranymi\r\n# X ~ H(N = 9, M = 6, n = 4)\r\n\r\nx = 0:4 #pocet projektu, ktere nas zajimaji\r\nN = 9 #celkem 9 projektu\r\nM = 6 #celkovy pocet projektu, ktere nas zajimaji\r\nn = 4 #pocet projektu ve vyberu\r\n\r\n# graf pravdepodobnostni funkce pro P(X = 0 az 4)\r\np = dhyper(x, M, N - M, n) # hodnoty pravdepodobnostni funkce pro x\r\n#kontrola - melo by dat 1\r\n#sum(p) == 1\r\n#plot(x, p)\r\n\r\n#jednotlive pravdepodobnosti p priradime k odpovidajicim hodnotam vytyhnutemu poctu spravnych projektu\r\npravdep = rbind(c(\"P(xi)\",p))\r\ncolnames(pravdep) = c(\"xi\",0:4)\r\nrownames(pravdep) = \"\"\r\npravdep #tabulka pravdepodobnostni funkce\r\npravd.f(x, p) #vykresleni\r\n\r\n#pravdepodobnosti prubezne scitame a priradime k nim omezeni\r\ndistrib = cbind(cumsum(p),c(\"x<=0\",\"03\"))\r\ncolnames(distrib) = c(\"\",\"\")\r\nrownames(distrib) = c(\"\",\"\",\"F(x) = \",\"\",\"\")\r\ndistrib #predpis distribucni funkce\r\ndist.f(x,p) #vykresleni\r\n\r\n# 1B\r\n# stredni hodnota je soucet vsech hodnot vynasobenych jejich pravdepodobnosti\r\n# rozptyl pomoci E(x^2) - E(x)^2\r\n# smerodatna odchylka je odmocnina rozptylu\r\n# modus je hodnota nejvetsi pravdepodobnosti\r\n# vypocet modus by bylo treba nahradit y[matchAll(max(p),p)] misto y[match(max(p),p)], \r\n# ale chtel jsem to mit spustitelne bez knihoven (matchAll je asi v knihovne tuple?)\r\nsouhrn(x,p)\r\n\r\n# 1C\r\n# vybirame alespon jeden spatny projekt, takze 1 nebo 2 nebo 3 spravne (4 spatne neexistuji)\r\n# P(x<=3)\r\nsum(p[1:4])\r\n\r\n# 1D\r\n(4 - sum(x*p)) * 200000 # celkem 4 projekty a odecteme sanci na vytazeni spravnych projektu\r\n\r\n# 1E\r\n# vetsi nez 250 tisic bude v pripade, ze vybereme alespon dva spatne projekty\r\n# P(x<3)\r\nsum(p[1:3])\r\n\r\n\r\n# 2A\r\n# definujeme distribucni funkci\r\nF = c(0, 0.3, 0.5, 0.9, 1)\r\ny = c(1,10,100,1000)\r\n\r\n# z distribucni funkce zjistime pravdepodobnosti pro omezeni\r\np = diff(F)\r\npravd.f(y, p) #vykreslime pravdepodobnosti funkci\r\ndist.f(y, p) #vykreslime distribucni funkci\r\n\r\n# 2B\r\n# P(Y=100) \r\np[match(100,y)] #dohledame hodnotu pro 100\r\n# P(Y >= 10)\r\n1-F[match(10,y)] #hledame vetsi nez, takze musime odecist pravdepodobnost 10 od jednicky\r\np[match(10,y)] + p[match(100,y)] + p[match(1000,y)] # nebo by jsme mohli secist zmeny vetsich nez\r\n\r\n# 2C\r\nsouhrn(y, p) # podobne jako 1B\r\n\r\n# 2D\r\nR = log10(y) # prepocteme si omezeni podle logaritmu\r\n\r\n# mohlo by dojit k nesetrizenym omezenim, takze je treba setridit\r\nidx_sorted = order(R)\r\nR = R[idx_sorted]\r\np_R = p[idx_sorted]\r\n\r\nsouhrn(R, p_R)\r\n\r\n# 3A\r\n# integral od -2/3 do 0 pro f(x)dx = 1 kde f(x) = c(6x+8)\r\n# c(3*x^2+8*x) => c(0*0)-c(3*(-2/3)^2+8*(-2/3)) => c(0) - c(-4) => c*4 dame rovno jedne => c = 0.25\r\nf = function(x){return(6*x+8)} # f(x) = 6x+8\r\ndolniMez = -2/3\r\nhorniMez = 0\r\n1/integrate(f, dolniMez, horniMez)$value\r\n\r\n# kdybych pocital rucne, tak si vyberu dva krajni body -2/3 a 0 a vypocitam jejich hodnoty\r\n# jelikoz jde o primku tak tyto dva body bych spojil a dal do uzavreneho intervalu\r\n# zbytek grafu hustoty bude na nule do nekonecen s otevrenymi intervaly\r\n\r\nf.dens = function(x){\r\n res = 6/4*x+2 # 1/4(6*x+8)\r\n res[x < -2/3] = 0 \r\n res[x > 0] = 0 \r\n return(res)\r\n}\r\n\r\nx = seq(from = -1, to = 0.5, by = 0.01) \r\nFX = f.dens(x) \r\nplot(x, FX, cex = 0.2, main=\"Graf hustoty\") \r\n\r\n# 3B\r\n# integral od -2/3 do 0 pro F(t) = f(x)dx\r\n# 0 t < -2/3\r\n# F(t) 6/8*t^2 + 2*t + 1 t <-2/3;0>\r\n# 1 t > 0\r\n# pocitam integral od -2/3 do t, kde t je mensi nez 0, pro f(x)dx\r\n# 6/4*x+2\r\n# 6/8*x^2+2*x\r\n# 6/8*t^2+2*t - (6/8*(-2/3)^2+2*(-2/3)) => 6/8*t^2 + 2*t + 1 => dosadim do F(t)\r\n\r\nF.dist = function(x){\r\n res = 6/8*x^2 + 2*x + 1\r\n res[x < -2/3] = 0 \r\n res[x > 0] = 1 \r\n return(res)\r\n}\r\n\r\nx = seq(from = -1, to = 0.5, by = 0.01) \r\nFX = F.dist(x)\r\nplot(x, FX, type = 'l', main=\"Distribucni funkce\")\r\n\r\n# 3C\r\n# vypocet se provadi integraci hustoty pravdepodobnosti v limitach danych zadanim pripadne oseknutou limitami hustoty\r\n# integrace provedena v 3B, pouze dosazujeme (6/8*(-1/3)^2 + 2*(-1/3) + 1) - (6/8*(-2/3)^2 + 2*(-2/3) + 1)\r\n# P(-1 <= X <= -1/3)\r\nintegrate(f.dens, -2/3, -1/3)$value\r\n\r\n# P(X > -1/3)\r\n# integrace provedena v 3B, pouze dosazujeme (6/8*(0)^2 + 2*(0) + 1) - (6/8*(-1/3)^2 + 2*(-1/3) + 1)\r\nintegrate(f.dens, -1/3, 0)$value \r\n\r\n\r\n# 3D\r\nx_fx = function(x){\r\n fx = f.dens(x)\r\n return(x*fx)\r\n} \r\nxx_fx = function(x){\r\n fx = f.dens(x) \r\n return(x*x*fx)\r\n} \r\n\r\n# pouzijeme vzorce E(x) = integral x*f(x)dx na celem nenulovem intervalu\r\n# E(x^2) = integral x^2*f(x)dx, pro D(x) = E(x^2) - E(x)^2\r\nE_X = integrate(x_fx, -2/3, 0)$value\r\nE_XX = integrate(xx_fx, -2/3, 0)$value\r\n\r\nD_X = E_XX - E_X^2\r\nstd_X = sqrt(D_X)\r\n\r\ncbind(c(\"E(X)\",\"D(X)\",\"sigma x\"),c(E_X,D_X,std_X))\r\n\r\n# 3E \r\n# pro Y = 4-2x vyuzijeme vzorecku\r\n# E(aX + b) = a*E(x)+b\r\n# D(aX + b) = a^2*D(x)\r\n# a hodnot, ktere jsme vypocitali v 3D\r\nE_Y = 4 - 2*E_X # E(4-2x)\r\nD_Y = (-2)^2*D_X # D(4-2x)\r\nstd_Y = sqrt(D_Y)\r\n\r\ncbind(c(\"E(Y)\",\"D(Y)\",\"sigma y\"),c(E_Y,D_Y,std_Y))\r\n\r\n\r\n# 4A\r\n# hustota se pocita derivaci distribucni funkce\r\n# zderivujeme sin x => cos x\r\n# f(x) cos x <0,pi/2>\r\n# 0 (-inf,0) nebo (pi/2,inf)\r\nf = function(x){\r\n res = cos(x) # x^2+2x+1\r\n res[x < 0] = 0 # 0 pro x<=0\r\n res[x > pi/2] = 0 # 1 pro x>1\r\n return(res)\r\n}\r\n\r\nx = seq(from = -0.5, to = 2, by = 0.01) \r\nFX = f(x) \r\nplot(x, FX, cex = 0.2, main=\"Graf hustoty\") \r\n\r\n\r\n# 4B \r\n# median nalezi do <0,pi/2> a pocita se z distribucni funkce\r\nF.dist = function(x){\r\n res = sin(x) # x^2+2x+1\r\n res[x <= 0] = 0 # 0 pro x<=0\r\n res[x > pi/2] = 1 # 1 pro x>1\r\n return(res)\r\n}\r\n\r\nx = seq(from = -0.5, to = 2, by = 0.001) \r\nFX = F.dist(x) \r\nplot(x, FX, type='l', main=\"Pravdepodobnostni funkce a median\") \r\nlines(c(-0.5, 2),c(0.5, 0.5))\r\n\r\nasin(0.5)\r\nx[FX >= 0.5][1]\r\n\r\n# 4C \r\n# podobne jako median spocitame i pravdepodobnost 60%, akorat musime pocitat s 1-0.6\r\nx = seq(from = -0.5, to = 2, by = 0.001) \r\nFX = F.dist(x) \r\nplot(x, FX, type='l', main=\"Pravdepodobnostni funkce a pravdepodobnost 60%\") \r\nlines(c(-0.5, 2),c(0.4, 0.4))\r\n\r\n\r\nasin(0.4)\r\nx[FX >= 0.4][1]\r\n\r\n\r\n\r\n\r\n#BONUS\r\nF = c(0, 0.1, 0.3, 0.6, 1)\r\ny = c(0,1,2,3)\r\n\r\n# z distribucni funkce zjistime pravdepodobnosti pro omezeni\r\np = diff(F)\r\npravd.f(y, p) #vykreslime pravdepodobnosti funkci\r\ndist.f(y, p) #vykreslime distribucni funkci\r\n\r\n# 2B\r\n# P(Y=100) \r\np[match(2,y)] #dohledame hodnotu pro 100\r\n# P(Y >= 10)\r\n1-F[match(1,y)] #hledame vetsi nez, takze musime odecist pravdepodobnost 10 od jednicky\r\n\r\n# 2A\r\nF = c(0, 0.2, 0.4, 0.7, 1)\r\ny = c(0,1,2,3)\r\n\r\np = diff(F)\r\npravd.f(y, p)\r\ndist.f(y, p) \r\n\r\n# 2B\r\np[match(2,y)]\r\n1-p[match(1,y)] \r\n\r\n# 2C\r\nsouhrn(y, p)\r\n\r\n# 2D\r\nR = y-y^2 \r\nidx_sorted = order(R)\r\nR = R[idx_sorted]\r\np_R = p[idx_sorted]\r\n\r\n#souhrn(R, p_R)\r\nEX = sum(R*p_R)\r\nEX\r\nDX = sum(R*R*p_R)-EX^2\r\nDX\r\nsigma = sqrt(DX)\r\nsigma\r\n\r\n\r\n\r\n\r\n\r\n#A\r\n#c(4x-3/2x^2)\r\nf = function(x){return(4-3*x)} \r\na = 0\r\nb = 2/3\r\n1/integrate(f, a, b)$value # obsah pod primkou je 1 a pocitame kolik je c\r\n\r\n#vyberu si dva body v intervalu abych vedel kde jde primka hustoty\r\n#2-3/2*0\r\n#2-(3/2)*(2/3)\r\n\r\nf.dens = function(x){\r\n res = 2 - 3/2*x\r\n res[x < 0] = 0 \r\n res[x > 2/3] = 0 \r\n return(res)\r\n}\r\n\r\nx = seq(from = -0.5, to = 1, by = 0.01) \r\nFX = f.dens(x) \r\nplot(x, FX, cex=0.2, main=\"Hustota\") \r\n\r\n\r\n#B\r\n#2-3/2*x #udelam integral od 0 do 2/3 s tckama - 3 hodnoty 0, x, 1\r\n# 0 t < 0\r\n# F(t) 2*t - 3/4*t^2 t <0;2/3>\r\n# 1 t > 2/3\r\n#2 - 3/2*x\r\n#2x - 3/4*x^2\r\n#2t - 3/4*t^2 - (0) => dosadim do F(t)\r\n\r\nF.dist = function(x){\r\n res = 2*x - 3/4*x^2 # x^2\r\n res[x<=0] = 0 # 0 pro x<=0\r\n res[x>2/3] = 1 # 1 pro x>1\r\n return(res)\r\n}\r\n\r\nx = seq(from = -0.5, to = 1, by = 0.01) \r\nFX = F.dist(x) \r\nplot(x, FX, type = 'l', main=\"Distribucni funkce\") # vykreslit jako caru\r\n\r\n\r\n\r\n#C\r\nf.dens = function(x){\r\n res = 2-(3/2)*x\r\n res[x < 0] = 0\r\n res[x > 2/3] = 0\r\n return(res)\r\n}\r\n\r\n# P(-1/3 ≤ X ≤ 1/3)\r\nintegrate(f.dens, -1/3, 1/3)$value\r\n\r\n# P(X >0.3)\r\nintegrate(f.dens, 1/3, 2/3)$value # tohle nebude vzdy fungovat\r\n\r\n#D\r\nx_fx = function(x){\r\n fx = f.dens(x)\r\n return(x*fx)\r\n} \r\nxx_fx = function(x){\r\n fx = f.dens(x) \r\n return(x*x*fx)\r\n} \r\n\r\n# integrujeme jen tam kde vime, ze je f(x) nenulova\r\nE_X = integrate(x_fx, 0, 2/3)$value\r\nE_XX = integrate(xx_fx, 0, 2/3)$value\r\n\r\nD_X = E_XX - E_X^2\r\nstd_X = sqrt(D_X)\r\n\r\ncbind(c(\"E(X)\",\"D(X)\",\"sigma x\"),c(E_X,D_X,std_X))\r\n\r\n#E Y = 2-4x\r\nE_Y = 2 - 4*E_X # E(2-4x)\r\nD_Y = (-4)^2*D_X # D(2-4x)\r\nstd_Y = sqrt(D_Y)\r\n\r\ncbind(c(\"E(Y)\",\"D(Y)\",\"sigma y\"),c(E_Y,D_Y,std_Y))\r\n\r\n\r\n\r\n\r\n\r\n\r\nx = 0:4 #pocet projektu, ktere nas zajimaji\r\nN = 100000 #celkem 9 projektu\r\nM = 20000 #celkovy pocet projektu, ktere nas zajimaji\r\nn = 4 #pocet projektu ve vyberu\r\n\r\n# graf pravdepodobnostni funkce pro P(X = 0 az 4)\r\np = dhyper(x, M, N - M, n) # hodnoty pravdepodobnostni funkce pro x\r\n#kontrola - melo by dat 1\r\n#sum(p) == 1\r\n#plot(x, p)\r\n\r\n#jednotlive pravdepodobnosti p priradime k odpovidajicim hodnotam vytyhnutemu poctu spravnych projektu\r\npravdep = rbind(c(\"P(xi)\",p))\r\ncolnames(pravdep) = c(\"xi\",0:4)\r\nrownames(pravdep) = \"\"\r\npravdep #tabulka pravdepodobnostni funkce\r\npravd.f(x, p) #vykresleni\r\n\r\n#pravdepodobnosti prubezne scitame a priradime k nim omezeni\r\ndistrib = cbind(cumsum(p),c(\"x<=0\",\"03\"))\r\ncolnames(distrib) = c(\"\",\"\")\r\nrownames(distrib) = c(\"\",\"\",\"F(x) = \",\"\",\"\")\r\ndistrib #predpis distribucni funkce\r\ndist.f(x,p) #vykresleni\r\n", "meta": {"hexsha": "2c39dd5f6b332aa4c00d60ea73602bc99d02c1c4", "size": 11596, "ext": "r", "lang": "R", "max_stars_repo_path": "2P/2P.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2P/2P.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2P/2P.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5354691076, "max_line_length": 118, "alphanum_fraction": 0.5745084512, "num_tokens": 5133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7066324022029815}} {"text": "f <- function(net) {\n return ( 1/(1+exp(-net)) )\n}\n\ndf_dnet <- function(f_net) {\n return (f_net * (1 - f_net))\n}\n\nmlp.architecture <- function(input.length=2,\n hidden.length=2,\n output.length=1,\n activation.function=f,\n d_activation.function=df_dnet) {\n\n model = list()\n model$input.length = input.length\n model$hidden.length = hidden.length\n model$output.length = output.length\n\n model$hidden = matrix(runif(min=-0.5, max=0.5, \n hidden.length*(input.length+1)), \n nrow=hidden.length, ncol=input.length+1)\n\n model$output = matrix(runif(min=-0.5, max=0.5, \n output.length*(hidden.length+1)), \n nrow=output.length, ncol=hidden.length+1)\n\n model$f = activation.function\n model$df_dnet = d_activation.function\n\n return (model)\n}\n\nmlp.forward <- function(model, Xp) {\n # Hidden layer\n net_h_p = model$hidden %*% c(Xp, 1)\n f_net_h_p = model$f(net_h_p)\n \n # Output layer\n net_o_p = model$output %*% c(as.numeric(f_net_h_p), 1)\n f_net_o_p = model$f(net_o_p)\n\n # Results\n ret = list()\n ret$net_h_p = net_h_p\n ret$net_o_p = net_o_p\n ret$f_net_h_p = f_net_h_p\n ret$f_net_o_p = f_net_o_p\n\n return (ret)\n}\n\nmlp.backpropagation <- function(model,\n dataset,\n eta=0.1,\n threshold=1e-4) {\n\n squaredError = 2 * threshold\n counter = 0\n\n while(squaredError > threshold) {\n squaredError = 0\n \n for (p in 1:nrow(dataset)) {\n Xp = as.numeric(dataset[p, 1:model$input.length])\n Yp = as.numeric(dataset[p,\n (model$input.length+1):ncol(dataset)])\n\n results = mlp.forward(model, Xp)\n Op = results$f_net_o_p\n\n # Calculando o erro\n error = Yp - Op\n\n squaredError = squaredError + sum(error^2)\n\n delta_o_p = error * model$df_dnet(results$f_net_o_p)\n \n w_o_kj = model$output[,1:model$hidden.length]\n delta_h_p = \n as.numeric(model$df_dnet(results$f_net_h_p)) *\n (as.numeric(delta_o_p) %*% w_o_kj)\n\n model$output = model$output +\n eta*(delta_o_p%*%as.vector(c(results$f_net_h_p,1)))\n model$hidden = model$hidden +\n eta*(t(delta_h_p) %*% as.vector(c(Xp,1)))\n }\n squaredError = squaredError / nrow(dataset)\n\n cat(\"Erro médio quadrado = \", squaredError, \"\\n\")\n\n counter = counter + 1\n }\n cat(\"Base treinada Daniel, SEU GOSTOSO!\\n\")\n ret = list()\n ret$model = model\n ret$counter = counter\n\n return (ret)\n}\n\n\ndataset = read.csv('__dataset.csv', header=F, skip=1)\ndataset <- dataset[c(1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 8)]\nids = sample(1:nrow(dataset), size=33)\ntraining = dataset[ids,]\ntest = dataset[-ids,]\nmodel = mlp.architecture(input.length=14, output.length=1, hidden.length=15)\ntrained = mlp.backpropagation(dataset=training, model=model, eta=0.5)\nwrite.csv(trained$model$hidden, file=\"hidden.csv\", row.names=FALSE)\nwrite.csv(trained$model$output, file=\"output.csv\", row.names=FALSE)\n", "meta": {"hexsha": "c359a28d14c2ad0136a05c8498968f7f85d0a961", "size": 3286, "ext": "r", "lang": "R", "max_stars_repo_path": "mlp.r", "max_stars_repo_name": "shodi/PI-V", "max_stars_repo_head_hexsha": "c2f95a70e2ece5adc1124d4f5f8d716a3a54e48e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-26T01:39:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-26T01:39:26.000Z", "max_issues_repo_path": "mlp.r", "max_issues_repo_name": "shodi/PI-V", "max_issues_repo_head_hexsha": "c2f95a70e2ece5adc1124d4f5f8d716a3a54e48e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2018-03-21T02:21:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-21T16:55:21.000Z", "max_forks_repo_path": "mlp.r", "max_forks_repo_name": "shodi/PI-V", "max_forks_repo_head_hexsha": "c2f95a70e2ece5adc1124d4f5f8d716a3a54e48e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0796460177, "max_line_length": 76, "alphanum_fraction": 0.5629945222, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7063980450715613}} {"text": "library(tidyr)\nlibrary(ggplot2)\nlibrary(dplyr)\nlibrary(cowplot)\nlibrary(readr)\n\n\npredict_mean_fitness <- function(Ne, L, s, eps)\n{\n k <- c(0:L)\n f <- exp(-s*k^(1-eps))\t\n p_k <- (f^(2*Ne-2)*choose(L, k))/sum(f^(2*Ne-2)*choose(L, k))\n sum(f*p_k)\n}\n\nw_vs_eps <- function(Ne, L, s, epsstart, epsstop, epssteps = 0.01)\n{\n eps <- seq(epsstart, epsstop, epssteps) \n w_ave <- vapply(eps, function(eps){predict_mean_fitness(Ne, L, s, eps)}, 1)\n data.frame(s, w_ave, Ne, L, eps)\n}\n\nqmin <- function(s, N, L){log(L*log(2)/(2*s*N-2*s))/log(L/2)}\n\nt <- read_csv(\"../processed_results/varying_eps_N100_max1.csv\")\n\nt %>% mutate(q=1-epistasis_coef) %>% \n group_by(q,sel_coef,mu_prob,k_start,rep) %>%\n summarise(mean_f_over_time=mean(mean_fitness)) -> t_sum\n\nfor (s in c(0.01, 0.001, 0.0001)){\n t_sum %>% filter(sel_coef==s) -> f\n Ne <- t$Ne[1]\n L <- t$L[1]\n an_f <- w_vs_eps(Ne, L, s, -1, 1) %>% mutate(q=1-eps)\n q_est <- qmin(s,Ne,100)\n \n p <- ggplot()+ \n stat_summary(data=f,\n inherit.aes=FALSE,\n aes(x=q,y=mean_f_over_time,color=factor(mu_prob)),\n fun.y = mean,\n fun.ymin = function(x) mean(x) - sd(x)/sqrt(length(x)),\n fun.ymax = function(x) mean(x) + sd(x)/sqrt(length(x)),\n geom = \"pointrange\",\n size=0.4)+\n geom_line(data=an_f, aes(x=q,y = w_ave))+\n #geom_vline(xintercept = q_est, linetype = 2)+\n #draw_text(x = q_est+0.02, y =1, hjust = 0, vjust = 1, text = \"predicted q*\", size = 12)+\n #scale_y_continuous(breaks=seq(0.2,1,0.2))+\n coord_cartesian(ylim=c(0.7,1),xlim=c(0,2))+\n guides(col = guide_legend(title=\"\\u03BC\"))+\n theme(axis.title = element_text(size = 14),\n axis.text = element_text(size = 12),\n legend.text = element_text(size = 11),\n legend.title = element_text(size = 12),\n legend.position = \"none\")+\n xlab('Q') +\n ylab('Mean fitness')\n save_plot(paste0(\"../plots/mean_fit_v_Q_s\",s,\"_N\",Ne,\"_max1.png\"), p)\n}\n\np3 <- make_fig(L = 100, s = 0.001, N = 100)", "meta": {"hexsha": "a24c82219134ef4de811a7c13e00083799db9cdf", "size": 2054, "ext": "r", "lang": "R", "max_stars_repo_path": "fixed_q_sim/src/plot_fitness_v_epistasis.r", "max_stars_repo_name": "clauswilke/epistasis_evolution", "max_stars_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fixed_q_sim/src/plot_fitness_v_epistasis.r", "max_issues_repo_name": "clauswilke/epistasis_evolution", "max_issues_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fixed_q_sim/src/plot_fitness_v_epistasis.r", "max_forks_repo_name": "clauswilke/epistasis_evolution", "max_forks_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6031746032, "max_line_length": 93, "alphanum_fraction": 0.5788704966, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.7061947641417451}} {"text": "\n\ninverse.logit = function( x ) {\n # x should be the log odds ratio\n oddsratio = exp(x)\n prob = oddsratio / (1 + oddsratio )\n return (prob) \n}\n\n\n", "meta": {"hexsha": "2a2b1ff93c1de6388570bd274db70fb3e52cf389", "size": 149, "ext": "r", "lang": "R", "max_stars_repo_path": "R/inverse.logit.r", "max_stars_repo_name": "jae0/snowcrab", "max_stars_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/inverse.logit.r", "max_issues_repo_name": "jae0/snowcrab", "max_issues_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/inverse.logit.r", "max_forks_repo_name": "jae0/snowcrab", "max_forks_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:57:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:57:48.000Z", "avg_line_length": 13.5454545455, "max_line_length": 37, "alphanum_fraction": 0.610738255, "num_tokens": 49, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.706194748512304}} {"text": "#' The zero-truncated compund poisson-lognormal distributions\n#'\n#' Density function and random generation for Zero-Trauncated Poisson Lognormal\n#' distribution with parameters `mu` and sd `sig`.\n#'\n#' A compound Poisson-lognormal distribution is a Poisson probability \n#' distribution where its parameter \\eqn{\\lambda} is a random variable with \n#' lognormal distribution, that is to say \\eqn{log\\lambda} are normally \n#' distributed with mean \\eqn{\\mu} and variance \\eqn{\\sigma^2} (Bulmer 1974). \n#' The zero-truncated Poisson-lognormal distribution can be derived from a \n#' zero-truncated Poisson distribution.\n#' \n#' Type 1 ZTPLN truncates zero based on Poisson-lognormal distribution and \n#' type 2 ZTPLN truncates zero based on zero-truncated Poisson distribution.\n#' For mathematical details, please see `vignette(\"ztpln\")`\n#'\n#' @param n number of random values to return.\n#' @param x\tvector of (non-negative integer) quantiles.\n#' @param mu mean of lognormal distribution.\n#' @param sig standard deviation of lognormal distribution.\n#' @param log logical; if TRUE, probabilities p are given as log(p).\n#' @param type1 logical; if TRUE, Use type 1 ztpln else use type 2. \n#' @return dztpln gives the (log) density and rztpln generates\n#' random variates.\n#' @references Bulmer, M. G. 1974. On Fitting the Poisson Lognormal Distribution to Species-Abundance Data. Biometrics 30:101-110.\n#'\n#' @seealso \\code{\\link{dztplnm}}\n#'\n#' @examples\n#' rztpln(n = 10, mu = 0, sig = 1, type1 = TRUE)\n#' rztpln(n = 10, mu = 6, sig = 4, type1 = TRUE)\n#' dztpln(x = 1:5, mu = 1, sig = 2)\n#' @export\ndztpln <- function(x, mu, sig, log = FALSE, type1 = TRUE) {\n if (length(mu) > 1 | length(sig) > 1)\n stop(\"Vectorization of parameters not implemented\")\n if (sig < 0) stop(\"sig needs to be > 0\")\n if (any(!DistributionUtils::is.wholenumber(x))) warning(\"non integer values in x\")\n if (min(x) <= 0) warning(\"zero in x\")\n x <- x[x > 0]\n if (type1) {\n lik <- do_dztpln(x, mu, sig)\n } else lik <- do_dztpln2(x, mu, sig)\n if (log) return(log(lik)) else return(lik)\n}\n\n#' @rdname dztpln\n#' @export\nrztpln <- function(n, mu, sig, type1 = TRUE) {\n if (length(mu) > 1 | length(sig) > 1) \n stop(\"Vectorization of parameters not implemented\")\n if (sig < 0) stop(\"sig needs to be > 0\")\n if (sig > 15) stop(\"standard deviation > 15 in log-scale is too large\")\n if (type1) do_vec_rztpln1(n, mu, sig) else do_vec_rztpln2(n, mu, sig)\n}\n", "meta": {"hexsha": "5444ef969c23cf653f5ae3012ea3ec213251ee42", "size": 2434, "ext": "r", "lang": "R", "max_stars_repo_path": "R/dztpln.r", "max_stars_repo_name": "mattocci27/poilog2", "max_stars_repo_head_hexsha": "5d2a6e6dc4238a9bb61a02126a99fe8b8205ef35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/dztpln.r", "max_issues_repo_name": "mattocci27/poilog2", "max_issues_repo_head_hexsha": "5d2a6e6dc4238a9bb61a02126a99fe8b8205ef35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/dztpln.r", "max_forks_repo_name": "mattocci27/poilog2", "max_forks_repo_head_hexsha": "5d2a6e6dc4238a9bb61a02126a99fe8b8205ef35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4642857143, "max_line_length": 130, "alphanum_fraction": 0.6922760887, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7061881693564404}} {"text": "#Developing multivariate normal with covariance. This recovers species abundances and covariance matrix.\n#Eventually extend to dirlichet case.\n#clear ennvironment, load packages.\nrm(list=ls())\nlibrary(runjags)\n\n#try with simulated data\ny1 <- round(rnorm(100, 100, 5)) \ny2 <- round(y1*-2 + rnorm(100,0,5)) + 400\ny3 <- round(rnorm(100,50,5))\ny4 <- round(rnorm(100,50,5))\nspp.y <- data.frame(y1,y2,y3,y4)\nspp.y <- as.matrix(spp.y)\nseqs <- rowSums(spp.y)\n\n#introduce a sequence depth effect.\n#Get a integer value to multiply species abundances by.\n#effort <- round(runif(100,5,50))\n#spp.y2 <- spp.y * effort\n#eqs <- rowSums(spp.y2)\n#seqs <- rep(1,nrow(spp.y))\n\n\njags.model = \"\nmodel {\n#setup priors for each species\nfor(j in 1:N.spp){\n m0[j] ~ dnorm(0, .001) #intercept prior\n}\n\n#Sigma (covariance matrix) prior\nsigma ~ dwish(r,S)\n\n#implement multivariate normal.\nfor(i in 1:N){\n y.hat[i,1:N.spp] <- (m0[1:N.spp]) * seqs[i]\n y[i,1:N.spp] ~ dmnorm(y.hat[i,1:N.spp], sigma[1:N.spp,1:N.spp])\n}\n\n} #close model loop.\n\"\n\n#Wish prior on covariance - weak covariance.\nW = diag(ncol(spp.y))/10000\n\njags.data <- list(y = spp.y,\n N = nrow(spp.y),\n N.spp = ncol(spp.y),\n r = W,\n S = ncol(spp.y),\n seqs = seqs)\n\njags.out <- run.jags(jags.model,\n data=jags.data,\n adapt = 100,\n burnin = 3000,\n sample = 2000,\n n.chains=3,\n monitor=c('m0','sigma'))\n\n#true relative abundances across samples.\ncolMeans(spp.y) / sum(colMeans(spp.y)) \n#estimated relative abundances\nsummary(jags.out)[grep('m0',rownames(summary(jags.out))),'Median']\n\n\n#Get estimated covariance matrix\nz <- summary(jags.out)[grep('sigma',rownames(summary(jags.out))),'Median']\nz.lo.95 <- summary(jags.out)[grep('sigma',rownames(summary(jags.out))),'Lower95']\nz.hi.95 <- summary(jags.out)[grep('sigma',rownames(summary(jags.out))),'Upper95']\ni.covm <- matrix(z, ncol = sqrt(length(z)))\ni.covm.lo <- matrix(z.lo.95, ncol = sqrt(length(z.lo.95)))\ni.covm.hi <- matrix(z.hi.95, ncol = sqrt(length(z.hi.95)))\nsolve(i.covm) #jags returns the inverse of the covariance matrix. This inverts it.\n\n#What is the covariance of real data?\n#spp.y.cov <- spp.y2 / seqs\n#cov(spp.y.cov)\ncov(spp.y)\ncov(spp.y2)\n\ncov2cor(cov(spp.y2))\n(cov2cor(cov(spp.y)))^2\n\ncov2cor(solve(i.covm))\ncov2cor(solve(i.covm.lo))\ncov2cor(solve(i.covm.hi))\n", "meta": {"hexsha": "78297195339e8bd4cfd5b5f4e05076ccc9297716", "size": 2471, "ext": "r", "lang": "R", "max_stars_repo_path": "testing_development/dmnorm_development/dmnorm_development.r", "max_stars_repo_name": "bhackos/NEFI_microbe", "max_stars_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing_development/dmnorm_development/dmnorm_development.r", "max_issues_repo_name": "bhackos/NEFI_microbe", "max_issues_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-10-23T16:09:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T16:01:10.000Z", "max_forks_repo_path": "testing_development/dmnorm_development/dmnorm_development.r", "max_forks_repo_name": "bhackos/NEFI_microbe", "max_forks_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-09T18:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-06T19:17:07.000Z", "avg_line_length": 28.0795454545, "max_line_length": 104, "alphanum_fraction": 0.6212059895, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.7061584684956007}} {"text": "#' ---\n#' subtitle: Exploring incomplete gamma function\n#' output: html_document\n#' ---\n#'\nsource(\"notebooks/eda_startup.r\")\ndevtools::load_all(path = \".\")\n#'\n#'\n#' Incomplete gamma-function\n#'\n#' @param n day `n`\ndaily_lactation_f <- function(n, a, b, c) {\n a * n ** b * exp(-c * n)\n}\n#' @inheritParams daily_lactation_f\ndaily_lactation_df <- function(n, a, b, c) {\n #' alternative: `a exp(-c n) (b n^(-1 + b) - c n^b)`\n a * exp(-c * n) * n^(-1 + b) * (b - c * n)\n}\n#'\n#'\n#' Source: [Application of the Incomplete Gamma Function to\n#' Predict Cumulative Milk Production](https://www.sciencedirect.com/science/article/pii/S0022030280828955)\n#'\ntibble(lactation = \"first\",\n a = 13.546, b = 19.575 / 1e2, c = 3.388 / 1e3) %>%\n add_row(lactation = \"second\",\n a = 18.820, b = 23.576 / 1e2, c = 5.441 / 1e3) %>%\n add_row(lactation = \"third and more\",\n a = 15.956, b = 30.004 / 1e2, c = 6.067 / 1e3) %>%\n mutate(lactation = fct_inorder(lactation)) %>%\n\n #' Change `a` to opposite sign just to get the curve that we are exploring\n mutate(a = -a) %>%\n\n #' Add suggested peaks\n mutate(peak_location = b/c) %>%\n # mutate(peak_level = ???) %>%\n\n #' Evaluate lactation-curve\n expand_grid(n = seq_len(305)) %>%\n mutate(daily_lactation_f =\n pmap_dbl(select(., n, a, b, c), daily_lactation_f)) %>%\n mutate(daily_lactation_df =\n pmap_dbl(select(., n, a, b, c), daily_lactation_df)) %>%\n pivot_longer(starts_with(\"daily_lactation\")) %>%\n identity() %>% {\n ggplot(.) +\n # aes(n, daily_lactation_f,\n aes(n, value,\n groups = interaction(name, lactation),\n color = lactation) +\n geom_line() +\n\n geom_vline(aes(xintercept = peak_location,\n color = lactation),\n data = . %>% distinct(peak_location, lactation)) +\n facet_wrap(~name, ncol = 1, scales = \"free_y\") +\n NULL\n }\n#'\n#'\n#'\n", "meta": {"hexsha": "0430740da30e54a7d6a4111169fbc872cf27ab4a", "size": 1909, "ext": "r", "lang": "R", "max_stars_repo_path": "notebooks/002_explore_incomplete_gamma_function.r", "max_stars_repo_name": "ku-awdc/woodcurvebox", "max_stars_repo_head_hexsha": "b1d26f97ad0e81efb1f7400d70aaf6c04eea360b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/002_explore_incomplete_gamma_function.r", "max_issues_repo_name": "ku-awdc/woodcurvebox", "max_issues_repo_head_hexsha": "b1d26f97ad0e81efb1f7400d70aaf6c04eea360b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/002_explore_incomplete_gamma_function.r", "max_forks_repo_name": "ku-awdc/woodcurvebox", "max_forks_repo_head_hexsha": "b1d26f97ad0e81efb1f7400d70aaf6c04eea360b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-01T11:13:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T11:13:43.000Z", "avg_line_length": 29.3692307692, "max_line_length": 107, "alphanum_fraction": 0.5845992666, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7061076371149776}} {"text": "# Master Thesis Project - Extreme Value Theory\n# We use here QQ-plots to assess graphically the\n# goodness of fit of our extreme distributions for\n# the high ( above high quantile) and low (below low\n# quantile) log-returns\n\n# Clear the environment\nrm(list=ls())\n\n# Close all already open graphic windows\ngraphics.off()\n\n# Sourcing the auxiliary files\nsource(\"loadStockData_plain.r\")\n\n# Remark : the csv uses the metastock data format \n# 7 columns : - Ticker (identifier of the stock\n# and stockmarket on which it is listed)\n#\t\t\t\t\t - Date (yyyymmdd)\n#\t\t\t\t\t - Open\n#\t\t\t\t\t - High\n#\t\t\t\t\t - Low\n#\t\t\t\t\t - Close\n#\t\t\t\t\t - Volume\n# By default, the highest price is used i.e. column 3.\nCHOICE <- 3\n\n# Loading the original data for the five stocks then\n# getting the LVMH and the Total data\ndf_plain <- loadStockData_plain(CHOICE)\n\n# Fitting\n\n\tdata_bnp <- diff(log(df_plain[[1]]))\n\tdata_carrefour <- diff(log(df_plain[[2]]))\n\tdata_lvmh <- diff(log(df_plain[[3]]))\n\tdata_sanofi <- diff(log(df_plain[[4]]))\n\tdata_total <- diff(log(df_plain[[5]]))\n\t\n\t# Computing the 95 % - quantiles [97.5 % - quantile in the case of the LVMH stock]\n\t# and the 5 % quantiles for each of the stocks\n\thighQuantiles <- c(quantile(data_bnp,0.99), quantile(data_carrefour,0.995), quantile(data_lvmh,0.995),\n\t\t\t\t\tquantile(data_sanofi,0.995), quantile(data_total,0.995))\n\tlowQuantiles <- c(quantile(-data_bnp,0.01), quantile(-data_carrefour,0.005), quantile(-data_lvmh,0.005),\n\t\t\t\t\tquantile(-data_sanofi,0.005), quantile(-data_total,0.005))\n\t\t\t\t\t\t\t\t\t\n\t# Getting the data above the high threshold and below the low threshold\n\tdata_bnp_H <- diff(log(df_plain[[1]]))\n\tdata_bnp_H <- data_bnp_H[data_bnp_H > highQuantiles[1]]\n\t\n\tdata_bnp_L <- -diff(log(df_plain[[1]]))\n\tdata_bnp_L <- data_bnp_L[data_bnp_L < lowQuantiles[1]]\n\n\tdata_carrefour_H <- diff(log(df_plain[[2]]))\n\tdata_carrefour_H <- data_carrefour_H[data_carrefour_H > highQuantiles[2]]\n\n\tdata_carrefour_L <- -diff(log(df_plain[[2]]))\n\tdata_carrefour_L <- data_carrefour_L[data_carrefour_L < lowQuantiles[2]]\n\t\n\tdata_lvmh_H <- diff(log(df_plain[[3]]))\n\tdata_lvmh_H <- data_lvmh_H[data_lvmh_H > highQuantiles[3]]\n\t\n\tdata_lvmh_L <- -diff(log(df_plain[[3]]))\n\tdata_lvmh_L <- data_lvmh_L[data_lvmh_L < lowQuantiles[3]]\n\n\tdata_sanofi_H <- diff(log(df_plain[[4]]))\n\tdata_sanofi_H <- data_sanofi_H[data_sanofi_H > highQuantiles[4]]\n\n\tdata_sanofi_L <- -diff(log(df_plain[[4]]))\n\tdata_sanofi_L <- data_sanofi_L[data_sanofi_L < lowQuantiles[4]]\n\n\tdata_total_H <- diff(log(df_plain[[5]]))\n\tdata_total_H <- data_total_H[data_total_H > highQuantiles[5]]\n\n\tdata_total_L <- -diff(log(df_plain[[5]]))\n\tdata_total_L <- data_total_L[data_total_L < lowQuantiles[5]]\n\n\t# Fitting the data, and getting the corresponding location, scale and \n\t# shape parameters respectively, for each stock\n\t# Fitting the log-returns for the above-high-threshold data\n\tbnp_fit_H <- (gev.fit(data_bnp_H))\n\tcarrefour_fit_H <- gev.fit(data_carrefour_H)\n\tlvmh_fit_H <- gev.fit(data_lvmh_H)\n\tsanofi_fit_H <- gev.fit(data_sanofi_H)\n\ttotal_fit_H <- gev.fit(data_total_H)\n\t# Fitting the minus log-returns for the below-low-threshold data\n\tbnp_fit_L <- (gev.fit(data_bnp_L))\n\tcarrefour_fit_L <- gev.fit(data_carrefour_L)\n\tlvmh_fit_L <- gev.fit(data_lvmh_L)\n\tsanofi_fit_L <- gev.fit(data_sanofi_L)\n\ttotal_fit_L <- gev.fit(data_total_L)\t\n\t\n\t# Saving the GEV parameters for later use\n\tparams_bnp_H <- bnp_fit_H$mle\n\tparams_carrefour_H <- carrefour_fit_H$mle\n\tparams_lvmh_H <- lvmh_fit_H$mle\n\tparams_sanofi_H <- sanofi_fit_H$mle\n\tparams_total_H <- total_fit_H$mle\n\t\n\tparams_bnp_L <- bnp_fit_L$mle\n\tparams_carrefour_L <- carrefour_fit_L$mle\n\tparams_lvmh_L <- lvmh_fit_L$mle\n\tparams_sanofi_L <- sanofi_fit_L$mle\n\tparams_total_L <- total_fit_L$mle\n\n# Drawing the QQ-plots\n\t# BNP stock\n\t\n\t\tN_bnp_H <- length(data_bnp_H)\n\t\tqVect_bnp_H <- (N_bnp_H + 1 - 1:N_bnp_H)/(N_bnp_H + 1)\n\t\tN_bnp_L <- length(data_bnp_L)\n\t\tqVect_bnp_L <- (N_bnp_L + 1 - 1:N_bnp_L)/(N_bnp_L + 1)\n\t\t\n\t\t# Ordering the samples\n\t\tdata_bnp_H <- sort(data_bnp_H)\n\t\tdata_bnp_L <- sort(data_bnp_L, decreasing = TRUE)\n\t\t\n\t\t# Getting the quantiles of the fitting distributions\n\t\tgev_bnp_H <- qgev(qVect_bnp_H ,params_bnp_H[3],params_bnp_H[1],params_bnp_H[2])\n\t\tgev_bnp_L <- qgev(qVect_bnp_L ,params_bnp_L[3],params_bnp_L[1],params_bnp_L[2])\n\t\t\n\t\t# Plotting\n\t\tquartz()\n \tpng(file = \"QQ_BNP_High.png\")\n\t\tplot(qVect_bnp_H,gev_bnp_H, main = \"QQ-plot BNP Paribas, above \\n99 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_bnp_H~qVect_bnp_H), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_BNP_Low.png\")\n\t\tplot(qVect_bnp_L,gev_bnp_L, main = \"QQ-plot BNP Paribas, below \\n1 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_bnp_L~qVect_bnp_L), col = \"blue\")\n\t\tdev.off()\n\t\tgraphics.off()\n\t\t\n\t# Carrefour stock\n\t\n\t\tN_carrefour_H <- length(data_carrefour_H)\n\t\tqVect_carrefour_H <- (N_carrefour_H + 1 - 1:N_carrefour_H)/(N_carrefour_H + 1)\n\t\tN_carrefour_L <- length(data_carrefour_L)\n\t\tqVect_carrefour_L <- (N_carrefour_L + 1 - 1:N_carrefour_L)/(N_carrefour_L + 1)\n\t\t\n\t\t# Ordering the samples\n\t\tdata_carrefour_H <- sort(data_carrefour_H)\n\t\tdata_carrefour_L <- sort(data_carrefour_L, decreasing = TRUE)\n\t\t\n\t\t# Getting the quantiles of the fitting distributions\n\t\tgev_carrefour_H <- qgev(qVect_carrefour_H ,params_carrefour_H[3],params_carrefour_H[1],params_carrefour_H[2])\n\t\tgev_carrefour_L <- qgev(qVect_carrefour_L ,params_carrefour_L[3],params_carrefour_L[1],params_carrefour_L[2])\n\t\t\n\t\t# Plotting\n\t\tquartz()\n \tpng(file = \"QQ_Carrefour_High.png\")\n\t\tplot(qVect_carrefour_H,gev_carrefour_H, main = \"QQ-plot Carrefour, above \\n99.5 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_carrefour_H~qVect_carrefour_H), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_Carrefour_Low.png\")\n\t\tplot(qVect_carrefour_L,gev_carrefour_L, main = \"QQ-plot Carrefour, below \\n0.5 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_carrefour_L~qVect_carrefour_L), col = \"blue\")\n\t\tdev.off()\n\t\tgraphics.off()\n\n\t# LVMH stock\n\t\n\t\tN_lvmh_H <- length(data_lvmh_H)\n\t\tqVect_lvmh_H <- (N_lvmh_H + 1 - 1:N_lvmh_H)/(N_lvmh_H + 1)\n\t\tN_lvmh_L <- length(data_lvmh_L)\n\t\tqVect_lvmh_L <- (N_lvmh_L + 1 - 1:N_lvmh_L)/(N_lvmh_L + 1)\n\t\t\n\t\t# Ordering the samples\n\t\tdata_lvmh_H <- sort(data_lvmh_H)\n\t\tdata_lvmh_L <- sort(data_lvmh_L, decreasing = TRUE)\n\t\t\n\t\t# Getting the quantiles of the fitting distributions\n\t\tgev_lvmh_H <- qgev(qVect_lvmh_H ,params_lvmh_H[3],params_lvmh_H[1],params_lvmh_H[2])\n\t\tgev_lvmh_L <- qgev(qVect_lvmh_L ,params_lvmh_L[3],params_lvmh_L[1],params_lvmh_L[2])\n\t\t\n\t\t# Plotting\n\t\tquartz()\n \tpng(file = \"QQ_LVMH_High.png\")\n\t\tplot(qVect_lvmh_H,gev_lvmh_H, main = \"QQ-plot LVMH, above \\n99.5 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_lvmh_H~qVect_lvmh_H), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_LVMH_Low.png\")\n\t\tplot(qVect_lvmh_L,gev_lvmh_L, main = \"QQ-plot LVMH, below \\n0.5 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_lvmh_L~qVect_lvmh_L), col = \"blue\")\n\t\tdev.off()\n\t\tgraphics.off()\n\n\t# Sanofi stock\n\t\n\t\tN_sanofi_H <- length(data_sanofi_H)\n\t\tqVect_sanofi_H <- (N_sanofi_H + 1 - 1:N_sanofi_H)/(N_sanofi_H + 1)\n\t\tN_sanofi_L <- length(data_sanofi_L)\n\t\tqVect_sanofi_L <- (N_sanofi_L + 1 - 1:N_sanofi_L)/(N_sanofi_L + 1)\n\t\t\n\t\t# Ordering the samples\n\t\tdata_sanofi_H <- sort(data_sanofi_H)\n\t\tdata_sanofi_L <- sort(data_sanofi_L, decreasing = TRUE)\n\t\t\n\t\t# Getting the quantiles of the fitting distributions\n\t\tgev_sanofi_H <- qgev(qVect_sanofi_H ,params_sanofi_H[3],params_sanofi_H[1],params_sanofi_H[2])\n\t\tgev_sanofi_L <- qgev(qVect_sanofi_L ,params_sanofi_L[3],params_sanofi_L[1],params_sanofi_L[2])\n\t\t\n\t\t# Plotting\n\t\tquartz()\n \tpng(file = \"QQ_Sanofi_High.png\")\n\t\tplot(qVect_sanofi_H,gev_sanofi_H, main = \"QQ-plot Sanofi, above \\n99.5 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_sanofi_H~qVect_sanofi_H), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_Sanofi_Low.png\")\n\t\tplot(qVect_sanofi_L,gev_sanofi_L, main = \"QQ-plot Sanofi, below \\n0.5 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_sanofi_L~qVect_sanofi_L), col = \"blue\")\n\t\tdev.off()\n\t\tgraphics.off()\n\n\t# Total stock\n\t\n\t\tN_total_H <- length(data_total_H)\n\t\tqVect_total_H <- (N_total_H + 1 - 1:N_total_H)/(N_total_H + 1)\n\t\tN_total_L <- length(data_total_L)\n\t\tqVect_total_L <- (N_total_L + 1 - 1:N_total_L)/(N_total_L + 1)\n\t\t\n\t\t# Ordering the samples\n\t\tdata_total_H <- sort(data_total_H)\n\t\tdata_total_L <- sort(data_total_L, decreasing = TRUE)\n\t\t\n\t\t# Getting the quantiles of the fitting distributions\n\t\tgev_total_H <- qgev(qVect_total_H ,params_total_H[3],params_total_H[1],params_total_H[2])\n\t\tgev_total_L <- qgev(qVect_total_L ,params_total_L[3],params_total_L[1],params_total_L[2])\n\t\t\n\t\t# Plotting\n\t\tquartz()\n \tpng(file = \"QQ_Total_High.png\")\n\t\tplot(qVect_total_H,gev_total_H, main = \"QQ-plot Total, above \\n99.5 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_total_H~qVect_total_H), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_Total_Low.png\")\n\t\tplot(qVect_total_L,gev_total_L, main = \"QQ-plot Total, below \\n0.5 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_total_L~qVect_total_L), col = \"blue\")\n\t\tdev.off()\n\t\tgraphics.off()\t\n\t\t\n", "meta": {"hexsha": "0bc3e44fa6f2cceaab6e1585802143788ca187c3", "size": 9271, "ext": "r", "lang": "R", "max_stars_repo_path": "r_final_task/QQPlots.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r_final_task/QQPlots.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r_final_task/QQPlots.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0739299611, "max_line_length": 120, "alphanum_fraction": 0.7081221012, "num_tokens": 3261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7061076334452585}} {"text": "h = max(10, plantHeight) / 100.0\nconductance = (wind * vonKarman** 2) / (log((heightWeatherMeasurements - d * h) / (zm * h)) * log((heightWeatherMeasurements - d * h) / (zh * h)))\n\n", "meta": {"hexsha": "77c40c154d871312435948e5609c0c479deaf163", "size": 181, "ext": "r", "lang": "R", "max_stars_repo_path": "test/data/energyBalance/crop2ml/Algo/R/conductance.r", "max_stars_repo_name": "brichet/PyCrop2ML", "max_stars_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "test/data/energyBalance/crop2ml/Algo/R/conductance.r", "max_issues_repo_name": "brichet/PyCrop2ML", "max_issues_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "test/data/energyBalance/crop2ml/Algo/R/conductance.r", "max_forks_repo_name": "brichet/PyCrop2ML", "max_forks_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 45.25, "max_line_length": 146, "alphanum_fraction": 0.6187845304, "num_tokens": 65, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.7061012566963264}} {"text": "## 3. Populations and Samples ##\n\n# question_1 <- ''\n# question_2 <- ''\n# question_3 <- ''\n# question_4 <- ''\n# question_5 <- ''\nquestion_1 <- 'population'\nquestion_2 <- 'population'\nquestion_3 <- 'sample'\nquestion_4 <- 'population'\nquestion_5 <- 'sample'\n\n## 4. Explore the Dataset ##\n\nlibrary(readr)\nwnba <- read_csv(\"wnba.csv\")\n\n## 5. Sampling Error ##\n\nset.seed(1)\nparameter <- max(wnba$Games_Played)\nsample <- sample(wnba$Games_Played, size = 30)\nstatistic <- max(sample)\nsampling_error <- parameter - statistic\n\n## 6. Simple Random Sampling ##\n\nset.seed(1)\nsample_1 <- mean(sample(wnba$PTS, size = 10))\nsample_2 <- mean(sample(wnba$PTS, size = 10))\nsample_3 <- mean(sample(wnba$PTS, size = 10))\n\n## 7. Generating Numerous Random Samples ##\n\nset.seed(1)\nmean_points <- replicate(n = 100, \n expr = mean(sample(wnba$PTS, size = 10)))\nminimum <- min(mean_points)\nmaximum <- max(mean_points)\n\n## 8. Visualizing Random Samples ##\n\nlibrary(tibble)\nlibrary(ggplot2)\nset.seed(1)\nmean_points <- replicate(n = 100, \n expr = mean(sample(wnba$PTS, size = 10)))\nsample_number <- 1:100\ndf <- tibble(x = sample_number, y = mean_points)\nggplot(data = df, \n aes(x = sample_number, y = mean_points)) +\n geom_point() +\n geom_hline(yintercept = mean(wnba$PTS), \n color = \"blue\") +\n ylim(90, 310)", "meta": {"hexsha": "2b6c3ea5c5912f33877c418c7eda7c3cf3f20baf", "size": 1327, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/1. Statistics Fundamentals in R/1. Simple Random Sampling.r", "max_stars_repo_name": "MyArist/Dataquest", "max_stars_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-27T12:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T04:39:33.000Z", "max_issues_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/1. Statistics Fundamentals in R/1. Simple Random Sampling.r", "max_issues_repo_name": "myarist/Dataquest", "max_issues_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/1. Statistics Fundamentals in R/1. Simple Random Sampling.r", "max_forks_repo_name": "myarist/Dataquest", "max_forks_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-03-30T06:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T03:55:02.000Z", "avg_line_length": 23.6964285714, "max_line_length": 51, "alphanum_fraction": 0.6510926903, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7060976539227983}} {"text": "#' Calculates Future Value\n#'\n#' @param p numeric\n#' @param r numeric\n#' @param t numeric\n#'\n#' @return numeric\n#' @export\n#'\n#' @examples\n#' future_value(2500, 0.043, 8/12) #2571.67\nfuture_value <- function(p, r, t) {\n p*(1+r*t)\n # Predicts the future value of the money invested\n}\n", "meta": {"hexsha": "87568ad0e3c73baaa0c363a8e0ba3d9aea55735d", "size": 285, "ext": "r", "lang": "R", "max_stars_repo_path": "R/FutureValue.r", "max_stars_repo_name": "NamanDhamejaBITS/FinancialMaths", "max_stars_repo_head_hexsha": "6fdf18b6de044c2b07fa94cf8141a48e917e1587", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/FutureValue.r", "max_issues_repo_name": "NamanDhamejaBITS/FinancialMaths", "max_issues_repo_head_hexsha": "6fdf18b6de044c2b07fa94cf8141a48e917e1587", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/FutureValue.r", "max_forks_repo_name": "NamanDhamejaBITS/FinancialMaths", "max_forks_repo_head_hexsha": "6fdf18b6de044c2b07fa94cf8141a48e917e1587", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8125, "max_line_length": 51, "alphanum_fraction": 0.6421052632, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7060877328297058}} {"text": "#Define function to allocate integer quantities among categories\n#---------------------------------------------------------------\n#' Allocate integer quantities among categories\n#'\n#' \\code{splitIntegers} splits a total value into a vector of whole numbers to\n#' reflect input vector of proportions\n#'\n#' This function splits an input total into a vector of whole numbers to reflect\n#' an input vector of proportions. If the input total is not an integer, the\n#' value is rounded and converted to an integer.\n#'\n#' @param Tot a number that is the total value to be split into a vector of\n#' whole numbers corresponding to the input proportions. If Tot is not an\n#' integer, its value is rounded and converted to an integer.\n#' @param Props_ a numeric vector of proportions used to split the total value.\n#' The values should add up to approximately 1. The function will adjust so that\n#' the proportions do add to 1.\n#' @return a numeric vector of whole numbers corresponding to the Props_\n#' argument which sums to the Tot.\n#' @export\nsplitIntegers <- function(Tot, Props_) {\n #Convert Tot into an integer\n if (!is.integer(Tot)) {\n Tot <- as.integer(round(Tot))\n }\n #If Tot is 0, return vector of zeros\n if (Tot == 0) {\n integer(length(Props_))\n } else {\n #Make sure that Props_ sums exactly to 1\n Props_ <- Props_ / sum(Props_)\n #Make initial whole number split\n Ints_ <- round(Tot * Props_)\n #Determine the difference between the initial split and the total\n Diff <- Tot - sum(Ints_)\n #Allocate the difference\n if (Diff != 0) {\n for (i in 1:abs(Diff)) {\n IdxToChg <- sample(1:length(Props_), 1, prob = Props_)\n Ints_[IdxToChg] <- Ints_[IdxToChg] + sign(Diff)\n }\n }\n unname(Ints_)\n }\n}\n", "meta": {"hexsha": "6d99ac571d1905998f8914cc0f908b406e95fcf3", "size": 1755, "ext": "r", "lang": "R", "max_stars_repo_path": "sources/modules/VESimLandUse/tests/scripts/split_integers.r", "max_stars_repo_name": "jrawbits/VisionEval", "max_stars_repo_head_hexsha": "27d8cbee9c2e9c9d54a74f4ee2005eb7b214e4dd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2015-11-02T15:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T15:55:24.000Z", "max_issues_repo_path": "sources/modules/VESimLandUse/tests/scripts/split_integers.r", "max_issues_repo_name": "jrawbits/VisionEval", "max_issues_repo_head_hexsha": "27d8cbee9c2e9c9d54a74f4ee2005eb7b214e4dd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 198, "max_issues_repo_issues_event_min_datetime": "2015-10-27T19:05:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-31T17:40:37.000Z", "max_forks_repo_path": "sources/modules/VESimLandUse/tests/scripts/split_integers.r", "max_forks_repo_name": "jrawbits/VisionEval", "max_forks_repo_head_hexsha": "27d8cbee9c2e9c9d54a74f4ee2005eb7b214e4dd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2015-11-02T14:54:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-18T21:37:27.000Z", "avg_line_length": 38.152173913, "max_line_length": 80, "alphanum_fraction": 0.6729344729, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7055621888892367}} {"text": "pascalTriangle <- function(h) {\n for(i in 0:(h-1)) {\n s <- \"\"\n for(k in 0:(h-i)) s <- paste(s, \" \", sep=\"\")\n for(j in 0:i) {\n s <- paste(s, sprintf(\"%3d \", choose(i, j)), sep=\"\")\n }\n print(s)\n }\n}\n", "meta": {"hexsha": "f33b7221b0fa95ec8f5254e189b537331349a548", "size": 220, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Pascals-triangle/R/pascals-triangle-1.r", "max_stars_repo_name": "mullikine/RosettaCodeData", "max_stars_repo_head_hexsha": "4f0027c6ce83daa36118ee8b67915a13cd23ab67", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Pascals-triangle/R/pascals-triangle-1.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Pascals-triangle/R/pascals-triangle-1.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 20.0, "max_line_length": 58, "alphanum_fraction": 0.4227272727, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.705399500058066}} {"text": "sd<-.225\r\nz_foralpha=qnorm(1-0.05)\r\nz_forbeta=qnorm(1-0.01)\r\nzstar<-z_foralpha+z_forbeta\r\nE<-16.37 - 16.27\r\nsample_size<- zstar^2 * sd * sd/ E^2\r\nprint(ceiling(sample_size))\r\n# the manufacturer must obtain a random sample of n = 80 boxes to conduct this test\r\n ", "meta": {"hexsha": "48629aa7c674cf8cfb1a342350f9ba758f10effa", "size": 262, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.11/Ex5_11.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.11/Ex5_11.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.11/Ex5_11.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 29.1111111111, "max_line_length": 85, "alphanum_fraction": 0.7099236641, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7052152885202757}} {"text": "# Master Thesis Project - Extreme Value Theory\n# We assume that the stock prices follow a geometric\n# Brownian motion (Black-Scholes model). We plot the\n# empirical stock price data as well as the simulated\n# geometric Brownian motions associated to them.\n# Killian Martin--Horgassan\n# 08-06-2015\n\n# Clear the environment\nrm(list=ls())\n\n# Close all already open graphic windows\ngraphics.off()\n\n# Sourcing the auxiliary files\nsource(\"loadStockData_plain.r\")\nsource(\"firstElement.r\")\nsource(\"computeApproximateGradient.r\")\nsource(\"meanAndVariance.r\")\nsource(\"Visualisation_StockPriceVariations.r\")\n\n\n# Remark : the csv uses the metastock data format \n# 7 columns : - Ticker (identifier of the stock\n# and stockmarket on which it is listed)\n#\t\t\t\t\t - Date (yyyymmdd)\n#\t\t\t\t\t - Open\n#\t\t\t\t\t - High\n#\t\t\t\t\t - Low\n#\t\t\t\t\t - Close\n#\t\t\t\t\t - Volume\n# By default, the highest price is used i.e. column 3.\nCHOICE <- 3\n\n# Loading the original data for the five stocks then\n# getting the LVMH and the Total data\ndf_plain <- loadStockData_plain(CHOICE)\nlvmhData <- df_plain[[3]]\ntotalData <- df_plain[[5]]\nindexes <- Visualisation_StockPriceVariations()\n#indexes[1] <- indexes[1] - 100\n\n# Building the Geometric Brownian motion \n\tN = max(indexes)-1\n\tM = dim(df)[2]\n\tsimulationLVMH <- rep(0,indexes[1]-1)\n\tsimulationTotal <- rep(0,indexes[2]-1)\n\t\n\t# Computing the mean and Variances of the stocks\n\tmeanAndVarLVMH <- meanAndVariance(lvmhData[1:indexes[1]-1])\n\tmeanAndVarTotal <- meanAndVariance(totalData[1:indexes[2]-1])\n\t\n\t#######################################################################\n\t# From experience we see that we need to rescale the time steps if we \n\t# want to be able not to go over the max and min values allowed by the\n\t# computer\n\t#######################################################################\n\t\n\t# Time component\n\ttimeSteps = 0:(N-1)\n\ttimeSteps = timeSteps/N ## RESCALING\n\t \n\t# Brownian motion component\n dis = (1/sqrt(N))*rnorm(N,0,1) ## DO NOT FORGET TO RESCALE HERE\n dis = cumsum(dis)\n \n\n\t# LVMH stock\n\tcoeff1 = meanAndVarLVMH[1] - 0.5*meanAndVarLVMH[2]\n\tcoeff1 = coeff1*(1/N) ## Rescale the mean\n\tcoeff2 = sqrt(meanAndVarLVMH[2]) ## The variance has already been rescaled\n\tcat(\"****************************************************\")\n\tcat(\"\\nDeterministic coefficient GBM - LVMH simulation:\\n\")\n\tprint(coeff1)\n\tcat(\"\\nStochastic coefficient GBM - LVMH simulation:\\n\")\n\tprint(coeff2)\n\texponentLVMH <- rep(0,(indexes[1]-1))\n\tfor (k in 2:(indexes[1] - 1)){\n\t\texponentLVMH[k] <- coeff1*timeSteps[k] + coeff2*dis[k]\n\t}\n\t#exponentLVMH[2:(indexes[1]-1)] <- coeff1*timeSteps[2:(indexes[1]-1)] + \n\t\t#coeff2*dis[2:(indexes[1]-1)]\n\tlvmhT0 <- (df_plain[[3]])[1]\n\tsimulationLVMH <- lvmhT0*exp(exponentLVMH)\n\t\n\t# Total Stock\n\tcoeff1 = meanAndVarTotal[1] - 0.5*meanAndVarTotal[2]\n\tcoeff1 = coeff1*(1/N) ## Rescale the mean\n\tcoeff2 = sqrt(meanAndVarTotal[2]) ## The variance has already been rescaled\n\tcat(\"\\nDeterministic coefficient GBM - Total simulation:\\n\")\n\tprint(coeff1)\n\tcat(\"\\nStochastic coefficient GBM - Total simulation:\\n\")\n\tprint(coeff2)\n\tcat(\"****************************************************\\n\")\n\tcat(\"****************************************************\\n\")\n\texponentTotal <- rep(0,(indexes[2]-1))\n\tfor (k in 2:(indexes[2] - 1)){\n\t\texponentTotal[k] <- coeff1*timeSteps[k] + coeff2*dis[k]\n\t}\n\t#exponentTotal[2:(indexes[2]-1)] <- coeff1*timeSteps[2:(indexes[2]-1)] +\n\t\t#coeff2*dis[2:(indexes[2]-1)]\n\ttotalT0 <- (df_plain[[5]])[1]\n\tsimulationTotal <- totalT0*exp(exponentTotal)\n\t \n\t#######################################################################\n\t# From experience again we see that we need to clean up a bit the data\n\t# we have just simulated as there a few points for which the value is\n\t# extremely high. We will replace them with the closest more 'reasonable'\n\t# value\n\t#######################################################################\n\t# Using the median is a RUBBISH-grade idea\n\t#simulationLVMH <- replaceExtremes(simulationLVMH,median(simulationLVMH))\n\t#simulationTotal <- replaceExtremes(simulationTotal,median(simulationTotal))\n\t\t \n\t quartz()\n par(mfrow = c(2,4))\n \n\t plot(log(lvmhData[1:(indexes[1]-1)]), type = 'l', main = \"LVMH - Actual\",\n\t \tylab = \"Log of the Stock price\")\n\t plot(exponentLVMH + rep(log(lvmhT0),length(exponentLVMH)), type = 'l',\n\t main = \"LVMH - simulation\", ylab = \"Log of the Stock price - simulated\")\n\t plot(exp(exponentLVMH + rep(log(lvmhT0),length(exponentLVMH))), type = 'l',\n\t main = \"LVMH - simulation\", ylab = \"Exp of the Log of the Stock price - simulated\")\n\t plot(simulationLVMH, type = 'l', main = \"LVMH - simulation\")\n\t cat(\"\\n \\n \\nMax simulation LVMH\\n\")\n\t print(max(simulationLVMH))\n\t \n\t plot(log(totalData[1:(indexes[2]-1)]), type = 'l', main = \"Total - Actual\",\n\t \tylab = \"Log of the Stock price\")\n\t plot(exponentTotal + rep(log(totalT0),length(exponentTotal)), type = 'l',\n\t main = \"Total - simulation\", ylab = \"Log of the Stock price - simulated\")\n\t plot(exp(exponentTotal + rep(log(totalT0),length(exponentTotal))), type = 'l',\n\t main = \"Total - simulation\", ylab = \"Exp of the Log of the Stock price - simulated\")\n\t plot(simulationTotal, type = 'l', main = \"Total - simulation \")\n\t cat(\"\\n \\n \\nMax simulation Total\\n\")\n\t print(max(simulationTotal))\n\n\n# Plotting the actual stock prices and the corresponding simulations\nx_label <- \"Weekly measurements\"\ny_label1 <- \"Log Prices : actual and simulation\"\ny_label2 <- \"Prices : actual and simulation\"\ntitle1 <- \"LVMH Stock\"\ntitle2 <- \"Total Stock\"\n\n# Rescaling the y-axis by computing the maxima and minima\n# and adapting the y-min and y-max\nYmaxima <- c(max((df_plain[[3]])[1:indexes[1]-1],simulationLVMH),\n\t\t\t\tmax((df_plain[[5]])[1:indexes[2]-1],simulationTotal))\nYminima <- c(min((df_plain[[3]])[1:indexes[1]-1],simulationLVMH),\n\t\t\t\tmin((df_plain[[5]])[1:indexes[2]-1],simulationTotal))\n\t\t\t\t\nquartz()\npng(file = \"cleanedLVMH_Total_Log.png\")\npar(mfrow = c(1,2))\nplot(log(lvmhData[1:(indexes[1]-1)]), pch = 1, col = \"green\", type = 'l', xlab = x_label, ylab = y_label1, main = title1, ylim = c(0,10))\nlines(exponentLVMH + rep(log(lvmhT0),length(exponentLVMH)), col = \"yellow\")\nprint(length(exponentLVMH))\nprint(length(log(lvmhData[1:(indexes[1]-1)])))\nplot(log(totalData[1:(indexes[2]-1)]), pch = 1, col = \"red\", type = 'l', xlab = x_label, ylab = y_label1, main = title2, ylim = c(0,10))\nlines(exponentTotal + rep(log(totalT0),length(exponentTotal)), col = \"yellow\")\n#dev.off()\n#graphics.off()\n\n\nquartz()\npng(file = \"cleanedLVMH_Total.png\")\npar(mfrow = c(1,2))\nplot(exp(log((df_plain[[3]])[1:(indexes[1]-1)])), pch = 1, col = \"green\", type = 'l', xlab = x_label, ylab = y_label2, main = title1, ylim = c(Yminima[1],1000))\nlines(exp(exponentLVMH + rep(log(lvmhT0),length(exponentLVMH))), col = \"yellow\")\nplot(exp(log((df_plain[[5]])[1:(indexes[2]-1)])), pch = 1, col = \"red\", type = 'l', xlab = x_label, ylab = y_label2, main = title2, ylim = c(Yminima[2],1000))\nlines(exp(exponentTotal + rep(log(totalT0),length(exponentTotal))), col = \"yellow\")\n\n\t\n\n\n\n\n\n", "meta": {"hexsha": "96241c47c5a15f65af4bde0f28dc55d284f837c3", "size": 7051, "ext": "r", "lang": "R", "max_stars_repo_path": "r_files_gbm_task7/GBM_LVMH_Total copy.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r_files_gbm_task7/GBM_LVMH_Total copy.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r_files_gbm_task7/GBM_LVMH_Total copy.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1722222222, "max_line_length": 160, "alphanum_fraction": 0.6392001135, "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.7718434873426303, "lm_q1q2_score": 0.7052152759490086}} {"text": "#############\n## PSI routines\n#############\n\n## The following are low level routines to calculate the phase from various PSI algorithms.\n\n## least squares fit of phase shifted interferograms with optional weights.\n\nlspsi <- function(images, phases, wt=rep(1, length(phases))) {\n img.mat <- matrix(images, ncol=dim(images)[3])\n lspsiC(img.mat, phases, wt)\n}\n\n## Vargas et al.'s (2011) Principal Components method\n\npcapsi <- function(im.mat, bgsub=TRUE, group_diag=\"v\") {\n if (bgsub) im.mat <- im.mat-rowMeans(im.mat)\n\n\t# svd of the crossproduct is faster!\n\t\n svd.cp <- svd(crossprod(im.mat))\n if (tolower(group_diag) == \"v\") {\n ph <- atan2(svd.cp$v[,2]*sqrt(svd.cp$d[2]),svd.cp$v[,1]*sqrt(svd.cp$d[1]))\n u <- im.mat %*% (svd.cp$u[,1:2] %*% diag(1/sqrt(svd.cp$d[1:2])))\n } else {\n ph <- atan2(svd.cp$v[,2],svd.cp$v[,1])\n u <- im.mat %*% svd.cp$u[,1:2]\n }\n ph <- wrap(ph-ph[1])\n phi <- atan2(-u[,2],u[,1])\n mod <- sqrt(u[,1]^2+u[,2]^2)\n r2 <- (svd.cp$d[1]+svd.cp$d[2])/sum(svd.cp$d)\n list(phi=phi, mod=mod/max(mod), phases=ph, snr=sqrt(r2/(1-r2)), eigen=svd.cp$d)\n}\n\n## Moore-Penrose generalized inverse (needed for genpca below)\n\nmpinv <- function(X) {\n S <- svd(X)\n eps <- .Machine$double.eps * max(dim(X)) * S$d[1]\n dinv <- numeric(length(S$d))\n dinv[S$d >= eps] <- 1/S$d[S$d >= eps]\n tcrossprod(S$v %*% diag(dinv), S$u)\n}\n\n## my variation on a PCA based algorithm\n\ngpcapsi <- function(im.mat, ptol=0.001, maxiter=20, trace=1) {\n gpcapsiC(im.mat, ptol, maxiter, trace)\n}\n\n\n## The \"advanced iterative algorithm\" of Wang & Han (2004)\n\naiapsi <- function(im.mat, phases,\n\t\t ptol=0.001, maxiter=20, trace=1) {\n aiapsiC(im.mat, phases, ptol, maxiter, trace)\n}\n\n\n## A variation of Han & Kim's (1994) iterative algorithm\n\nhkpsi <- function(im.mat, phases,\n\t\tmaxiter=20, ptol=0.001, trace=1, plotprogress=TRUE) {\n\t.meps <- sqrt(.Machine$double.eps)\n\tM <- nrow(im.mat)\n\tnf <- ncol(im.mat)\n\tphases <- wrap(phases-phases[1])\n\tS <- rbind(rep(1,nf), cos(phases), sin(phases))\n\tsse <- numeric(maxiter+1)\n\tfor (i in 1:maxiter) {\n\t\tphases.last <- phases\n\t\t\n\t\t# get the phase estimate from phase shifts\n\t\t\n\t\tSD <- svd(S)\n\t\tdp <- SD$d\n\t\tdp[dp>.meps] <- 1/dp[dp>.meps]\n\t\tdp[dp <= .meps] <- 0\n\t\tPhi <- tcrossprod(im.mat %*% (SD$v %*% diag(dp)), SD$u)\n\t\tsse[i] <- crossprod(as.vector(im.mat)-as.vector(Phi %*% S))\n\t\tif (i == 1) sse.1 <- sse[i]\n\t\t\n\t\t# get phase shifts from the phase. Note use crossproduct for speed.\n\t\t# Here is only difference from AIA - use full least squares estimate\n\t\t# at this step.\n\t\t\n\t\tPD <- svd(crossprod(Phi))\n\t\tdp <- PD$d\n\t\tdp[dp>.meps] <- 1/dp[dp>.meps]\n\t\tdp[dp <= .meps] <- 0\n\t\tS <- (PD$u %*% diag(dp) %*% t(PD$v)) %*% crossprod(Phi, im.mat)\n\t\tphases <- atan2(S[3,], S[2,])\n\t\tdphases <- sd(wrap(phases-phases.last))\n\t\tif (plotprogress) {\n\t\t\tif (i ==1)\n\t\t\t\tplot(1:maxiter, 1:maxiter, ylim=c(ptol, 1), type=\"n\",\n\t\t\t\t xlab=\"Iteration\", ylab=\"\", log=\"y\")\n\t\t\tpoints(i, sse[i]/sse.1, pch=1)\n\t\t\tpoints(i, dphases, pch=2, col=\"green\")\n\t\t}\n\t\tif ((trace > 0) && ((i-1)%%trace == 0)) {\n\t\t cat(paste(i, \":\", format(sse[i], digits=2), \":\"), \n format(phases,digits=3), \"\\n\")\n\t\t flush.console()\n\t\t}\n\t\tif (dphases < ptol) break\n\t\tS <- rbind(rep(1,nf), cos(phases), sin(phases))\n\t}\n\n\t#final estimate of phase\n\n\tphases <- wrap(phases-phases[1])\n\tS <- rbind(rep(1,nf), cos(phases), sin(phases))\n\tSD <- svd(S)\n\tdp <- SD$d\n\tdp[dp>.meps] <- 1/dp[dp>.meps]\n\tdp[dp <= .meps] <- 0\n\tPhi <- tcrossprod(im.mat %*% (SD$v %*% diag(dp)), SD$u)\n\tsse[i+1] <- crossprod(as.vector(im.mat)-as.vector(Phi %*% S))\n\tphi <- atan2(-Phi[,3], Phi[,2])\n\tmod <- sqrt(Phi[,2]^2+Phi[,3]^2)\n\tlist(phi=phi, mod=mod/max(mod), phases=phases, iter=i, sse=sse)\n}\n\n## tiltpsi (new version)\n\ntiltpsi <- function(im.mat, phases, coords,\n \t\t ptol=0.01, maxiter=20, trace=1) {\n tiltpsiC(im.mat, phases, coords, ptol, maxiter, trace)\n}\n\n", "meta": {"hexsha": "15390b719b46766d34533793e5b4ac0f9191dbea", "size": 3900, "ext": "r", "lang": "R", "max_stars_repo_path": "R/psialgs.r", "max_stars_repo_name": "gmke/zernike", "max_stars_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-15T09:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T17:28:29.000Z", "max_issues_repo_path": "R/psialgs.r", "max_issues_repo_name": "gmke/zernike", "max_issues_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/psialgs.r", "max_forks_repo_name": "gmke/zernike", "max_forks_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-17T13:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T13:30:49.000Z", "avg_line_length": 29.3233082707, "max_line_length": 91, "alphanum_fraction": 0.5851282051, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7048798911141271}} {"text": "\n#' @title expected_k_pop\n#' @description\n#' Calculates the expected number of alleles at a locus in a population, evolving under\n#' a Wright-Fisher infinite-alleles drift model. Employs the approximation from \n#' Ewens 1972, Equation 4, and performs a simple numerical integration. The approximation\n#' is good enough to match the value from Mathematica 9/10. \n#' \n#' @param n population size\n#' @param theta scaled innovation rate \n#' @return expected_k\n#' @export\n\nexpected_k_pop <- function(n, theta) {\n \n expected_k_pop_integrand <- function(x) {(1/x) * ((1 - x)^(theta - 1))}\n \n \n \n tmp <- integrate(expected_k_pop_integrand, lower=1/n, upper=1)$value\n e_k <- tmp * theta\n e_k\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "50750ae3b978711b4cb9d72faf8d3ea2dd1c4aa7", "size": 702, "ext": "r", "lang": "R", "max_stars_repo_path": "R/neutral_model.r", "max_stars_repo_name": "mmadsen/mmadsenr", "max_stars_repo_head_hexsha": "1a7ac5431d87628a32fee0453a7d2a289dd5975b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/neutral_model.r", "max_issues_repo_name": "mmadsen/mmadsenr", "max_issues_repo_head_hexsha": "1a7ac5431d87628a32fee0453a7d2a289dd5975b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/neutral_model.r", "max_forks_repo_name": "mmadsen/mmadsenr", "max_forks_repo_head_hexsha": "1a7ac5431d87628a32fee0453a7d2a289dd5975b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4, "max_line_length": 90, "alphanum_fraction": 0.7022792023, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7048108839043382}} {"text": "#' f_sigmatau\n#'\n#' Construct the $\\Sigma_tau$ diagonal matrix\n#' given the dimension $K$\n#'\n#' @param k dimension of the diagonal matrix\n#'\n#' @return $K\\times K \\Sigma_tau$ diagonal matix,\n#' with $\\M \\Sigma_\\tau_{ij} = 1$ if $i\\geq j$ and $0$ otherwise.\n#'\nf_sigmatau <- function(k) {\n sigmatau <- matrix(0L, k, k)\n sigmatau[lower.tri(sigmatau, diag = T)] <- 1\n return(sigmatau)\n}\n\n\n#' f_sigma\n#'\n#' Construct the $\\Sigma$ matrix\n#' given the dimension $k_\\tau, K_1$\n#'\n#' @param ktau dimension of the taus\n#' @param k1 dimension of the first covariate\n#'\n#' @return $k_\\tauK_1 \\times k_\\tauK_1 \\Sigma$ diagonal block matix.\n#'\nf_sigma <- function(ktau, k1) {\n sigmatau <- f_sigmatau(ktau)\n return(kronecker(sigmatau, diag(k1)))\n}\n\n#' f_mate\n#'\n#' Construct the $E_{K_\\tau}$ diagonal matrix\n#' given the dimension $K_\\tau$\n#'\n#' @param ktau dimension of the diagonal matrix\n#'\n#' @return $K_\\tau \\times K_\\tau E_{K_\\tau}$ diagonal matix,\n#' with $\\M E_{11} = 1$ and $0$ anywhere else.\n#'\nf_mate <- function(ktau) {\n m_e <- matrix(0L, ktau, ktau)\n m_e[1, 1] <- 1\n return(m_e)\n}\n\n#' f_matf\n#'\n#' Construct the $(K_\\tau-2) \\times K_\\tau$ $F_{K_\\tau}$ matrix\n#' given the dimension $K$\n#'\n#' @param ktau dimension of the diagonal matrix\n#'\n#' @return $(K_\\tau-2)\\times K_\\tau F_{K_\\tau}$,\n#' aka the first order differencing matrix,\n#' without the first row.\n#'\nf_matf <- function(ktau) {\n m_dif <- diff_matrix(ktau, 1)[-1, ]\n if (is.vector(m_dif)) {\n m_dif <- t(m_dif)\n }\n return(m_dif)\n}\n\n#' f_d11\n#'\n#' Construct the $K_{\\tau}(K_1-2) \\times K_{\\tau}K_1$ $D_{11}$ matrix\n#' given the dimension $K$\n#'\n#' @param ktau dimension of the taus\n#' @param k1 dimension of the first covariate\n#'\n#' @return $K_{\\tau}(K_1-2) \\times K_{\\tau}K_1$ $D_{11}$ matrix\n#'\nf_d11 <- function(ktau, k1) {\n kronecker(f_mate(ktau), diff_matrix(k1, 2))\n}\n\n#' f_d12\n#'\n#' Construct the $K_{\\tau}(K_1-1) \\times K_{\\tau}K_1$ $D_{12}$ matrix\n#' given the dimension $K$\n#'\n#' @param ktau dimension of the taus\n#' @param k1 dimension of the first covariate\n#'\n#' @return $K_{\\tau}(K_1-1) \\times K_{\\tau}K_1$ $D_{12}$ matrix\n#'\nf_d12 <- function(ktau, k1) {\n kronecker((diag(ktau) - f_mate(ktau)), diff_matrix(k1, 1))\n}\n\n#' f_dtau\n#'\n#' Construct the $K_{\\tau - 2}K_1 \\times K_{\\tau}K_1$ $D_{\\tau}$ matrix\n#' given the dimension $K$\n#'\n#' @param ktau dimension of the taus\n#' @param k1 dimension of the first covariate\n#'\n#' @return $K_{\\tau - 2}K_1 \\times K_{\\tau}K_1$ $D_{\\tau}$ matrix\n#'\nf_dtau <- function(ktau, k1) {\n kronecker(f_matf(ktau), diag(k1))\n}\n\n#' f_mats\n#'\n#' Construct the $K_1K_2 \\times K_1K_2$ $S$ matrix\n#' given the dimension $K_1, K_2$\n#'\n#' @param ktau dimension of the taus\n#' @param k1 dimension of the first covariate\n#' @param lambdas vector of lambdas(penalty parameters)\n#'\n#' @return $K_{K_\\tau}K_1 \\timesK_{K_\\tau}K_1$ $S$ matrix\n#'\nf_mats <- function(ktau, k1, lambdas) {\n s <- lambdas[1] * crossprod(f_dtau(ktau, k1))\n s <- s + lambdas[2] * crossprod(f_d11(ktau, k1))\n s <- s + lambdas[3] * crossprod(f_d12(ktau, k1))\n return(s)\n}\n\n#' f_matc\n#'\n#' Construct the $K_{K_\\tau}K_1 \\times $K_{K_\\tau}K_1$ diagonla matrix $C$\n#' given the dimension \\code{v_dim}\n#'\n#' @param v_dim vector contain the dimension of covariates\n#' $(K_\\tau, K_1, K_2, \\cdots)$\n#'\n#' @param til_beta $K_\\tauK_1\\cdots$ vector of the coefficient $\\tilde{\\beta}$\n#'\n#' @return K_{K_\\tau}K_1\\cdots \\times K_{K_\\tau}K_1\\cdots$ diagonal matrix $C$,\n#' with diagonal equals derivative of $\\tilde{\\beta}$.\n#' $\\M C_{jj} = \\begin{cases}\n#' 1, &\\text{if } \\tilde{\\beta}_j=\\beta_j\\\\\n#' \\exp(\\beta_j), &\\text{otherwise}.\n#' \\end{cases}$\n#'\nf_matc <- function(v_dim, til_beta) {\n if (prod(v_dim) != length(til_beta)) {\n print(\"v_dim:\"); print(v_dim); print(\"til_beta:\"); print(til_beta)\n stop(\"f_matc: input dimension invalid \\n\")\n }\n v_idx <- seq_len(v_dim[2])\n til_beta[v_idx] <- 1L\n m_c <- diag(til_beta)\n return(m_c)\n}\n\n\n#' f_g1\n#'\n#' Construct the $(K_0+m) \\times (K_0+m)$ or $K \\times K$ $G_1$ diagonal matrix\n#' given the dimension $K = K_0 + m$\n#'\n#' @param k0 number of internal knots\n#' @param m order of the basis splines\n#'\n#' @return $K\\times K G_1$ diagonal matix,\n#' with $G_1_{ii} = (t_{i+m} - t_i)/m$.\n#'\nf_g1 <- function(k0, m) {\n h <- 1 / (1 + k0)\n v_knots <- seq_len(k0) * h\n v_knots <- c(rep(0, m), v_knots, rep(1, m))\n out <- diag(diff(x = v_knots, lag = m) / m)\n return(out)\n}\n\n\n#' f_g2\n#'\n#' Construct the $(K_0+m) \\times (K_0+m)$ or $K \\times K$ $G_2$ diagonal matrix\n#' given the dimension $K = K_0 + m$\n#'\n#' @param k0 number of internal knots\n#' @param m order of the basis splines\n#'\n#' @return $K\\times K G_2$ diagonal matix,\n#' with $G_2_{ii} = (t_{i+m+1} - t_i)/m$.\n#'\nf_g2 <- function(k0, m) {\n out <- f_g1(k0, m + 1)\n out <- out[-1, -1]\n return(out)\n}\n\n\n\n#' f_n1\n#'\n#' Construct the $n \\times (K_1)$ spline matrix for the first covariate\n#' given the dimension $K_1 = k1 + m1$\n#'\n#' @param x observations for the first covariate\n#' @param k1 number of internal knots\n#' @param m1 order of the basis splines\n#'\n#'\n#' @return $n \\times K_1$ spline matrix for the first covariate,\n#'\nf_n1 <- function(x, k1, m1) {\n out <- spline_basis(x, k1, m1)\n return(out)\n}\n\n\n#' f_ntau\n#'\n#' Construct the $n \\times (K_1)$ spline designfor the taus\n#' given the dimension $K_\\tau = k\\tau + m\\tau$\n#'\n#' @param v_tau observations for the tau\n#' @param ktau number of internal knots\n#' @param mtau order of the basis splines\n#'\n#'\n#' @return $n \\times K_\\tau$ spline design for the taus,\n#'\nf_ntau <- function(v_tau, ktau, mtau) {\n spline_basis(v_tau, ktau, mtau, x_range = c(1, 0))\n}\n\n\n#' f_ntau\n#'\n#' Construct the $n \\times (K_\\tau)$ spline matrix $N_{\\tau^*}$\n#' given the dimension $K_\\tau = k\\tau + m\\tau$\n#'\n#' @param taustar estimated tau for each observations\n#' @param k\\tau number of internal knots\n#' @param m\\tau order of the basis splines\n#'\n#' @import splines\n#'\n#' @return $n \\times K_\\tau$ intergrated spline matrix $N_{\\tau^*}$\n#'\nf_ntaustar <- function(taustar, ktau, mtau) {\n out <- spline_basis(taustar, ktau, mtau + 1, x_range = c(1, 0))\n out <- out[, -1]\n return(out)\n}\n", "meta": {"hexsha": "b4c7f741a97e627d613cb096a28f1f2cd578041c", "size": 6356, "ext": "r", "lang": "R", "max_stars_repo_path": "R/matrices.r", "max_stars_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_stars_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/matrices.r", "max_issues_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_issues_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/matrices.r", "max_forks_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_forks_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5261044177, "max_line_length": 79, "alphanum_fraction": 0.6110761485, "num_tokens": 2317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878721, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.7047942889141084}} {"text": "<<<<<<< HEAD\n#### Healthy Neighborhoods Project: Using Ecological Data to Improve Community Health\n### Cedric subproject: Developing better ways to measure equity in health using the Gini coefficient\n## Florida Charts Census Tract Mortality Data: R Project for Statistical Computing Code Script by DrewC!\n\n### Step 1: Import Libraries and Import Dataset\n\n## Open R Terminal\nR # open R in VS Code (any terminal)\n\n## Import Standard Libraries\nlibrary(tidyverse)\n\n## Import Machine Learning Libraries\nlibrary(randomForest) # Popular random forest package for R\n\n## Import Statistics Libraries\nlibrary(MASS) # Stepwise inclusion model with linear and logistic options\nlibrary(psych) # Survey analysis library with factor analysis\nlibrary(GPArotation) # Rotation options for factor analysis\nlibrary(pROC) # ROC tests with AUC output\nlibrary(ineq) # Gini coefficient and Lorenz curve\n\n## Import Data\nsetwd(\"C:/Users/drewc/GitHub/Healthy_Neighborhoods\") # Set wd to project repository\ndf_cedric = read.csv(\"_data/cedric_can_gini.csv\") # Import dataset from _data folder\ndf_mungos = read.csv(\"_data/mungos_np_value.csv\") # Import dataset from _data folder\n\n## Join\ndf_bella = inner_join(df_cedric, df_mungos, by = \"County\")\n\n## Verify\nglimpse(df_bella)\nglimpse(df_mungos)\nglimpse(df_cedric)\n\n## Export\nwrite.csv(df_bella, \"_data/bella_can_gini_np_value.csv\") #clean in excel and select variable\n\n### Step 2: Statistical Test\n\n## Spearman's Rank for ERR\ncorr_err = cor.test(x = df_bella$Gini, y = df_bella$ERR, method = \"spearman\") # Pearson's Rank for Q->Q\nprint(corr_err)\n\n## Spearman's Rank for MSPB\ncorr_mspb = cor.test(x = df_bella$Gini, y = df_bella$MSPB, method = \"spearman\") # Pearson's Rank for Q->Q\n=======\n#### Healthy Neighborhoods Project: Using Ecological Data to Improve Community Health\n### Cedric subproject: Developing better ways to measure equity in health using the Gini coefficient\n## Florida Charts Census Tract Mortality Data: R Project for Statistical Computing Code Script by DrewC!\n\n### Step 1: Import Libraries and Import Dataset\n\n## Open R Terminal\nR # open R in VS Code (any terminal)\n\n## Import Standard Libraries\nlibrary(tidyverse)\n\n## Import Machine Learning Libraries\nlibrary(randomForest) # Popular random forest package for R\n\n## Import Statistics Libraries\nlibrary(MASS) # Stepwise inclusion model with linear and logistic options\nlibrary(psych) # Survey analysis library with factor analysis\nlibrary(GPArotation) # Rotation options for factor analysis\nlibrary(pROC) # ROC tests with AUC output\nlibrary(ineq) # Gini coefficient and Lorenz curve\n\n## Import Data\nsetwd(\"C:/Users/drewc/GitHub/Healthy_Neighborhoods\") # Set wd to project repository\ndf_cedric = read.csv(\"_data/cedric_can_gini.csv\") # Import dataset from _data folder\ndf_mungos = read.csv(\"_data/mungos_np_value.csv\") # Import dataset from _data folder\n\n## Join\ndf_bella = inner_join(df_cedric, df_mungos, by = \"County\")\n\n## Verify\nglimpse(df_bella)\nglimpse(df_mungos)\nglimpse(df_cedric)\n\n## Export\nwrite.csv(df_bella, \"_data/bella_can_gini_np_value.csv\") #clean in excel and select variable\n\n### Step 2: Statistical Test\n\n## Spearman's Rank for ERR\ncorr_err = cor.test(x = df_bella$Gini, y = df_bella$ERR, method = \"spearman\") # Pearson's Rank for Q->Q\nprint(corr_err)\n\n## Spearman's Rank for MSPB\ncorr_mspb = cor.test(x = df_bella$Gini, y = df_bella$MSPB, method = \"spearman\") # Pearson's Rank for Q->Q\n>>>>>>> 321eaea894d29a3f212ee3e111b86695f46cf6db\nprint(corr_mspb)", "meta": {"hexsha": "eacc4b3d1a724a9dd7ff0a97a9e9692cac104325", "size": 3462, "ext": "r", "lang": "R", "max_stars_repo_path": "_archive/_archive/bellatrix/bellatrix_vasc_value_code.r", "max_stars_repo_name": "andrewcistola/healthy-neighborhoods", "max_stars_repo_head_hexsha": "08bd0cd9dcb81b083a003943cd6679ca12237a1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-13T17:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T17:50:08.000Z", "max_issues_repo_path": "_archive/_archive/bellatrix/bellatrix_vasc_value_code.r", "max_issues_repo_name": "andrewcistola/healthy-neighborhoods", "max_issues_repo_head_hexsha": "08bd0cd9dcb81b083a003943cd6679ca12237a1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_archive/_archive/bellatrix/bellatrix_vasc_value_code.r", "max_forks_repo_name": "andrewcistola/healthy-neighborhoods", "max_forks_repo_head_hexsha": "08bd0cd9dcb81b083a003943cd6679ca12237a1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0625, "max_line_length": 105, "alphanum_fraction": 0.7666088966, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.940789754239075, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.7047335645901474}} {"text": "# MIT License\n# Copyright (c) 2020 Abhinav Prakash, Vijay Panchang, Yu Ding, and Lewis Ntaimo\n \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nsource(\"function.r\")\ninput_file = \"assunpink.csv\"\noutput_file = \"assunpink\"\ndata_col = 3\nyear_col = 1\ncol_names = T\nCSVFile = read.csv(file = input_file, header = col_names)\nData = CSVFile[,data_col]\nYear = CSVFile[,year_col]\nreferenceyear = 2018\ntime_index = time.index(Year,referenceyear)\nlmfit = lm(Data~time_index)\nmu0.int = lmfit$coefficients[1]\nmu1.int = abs(lmfit$coefficients[2])\nscale.int = sd(Data)\nset.seed(2)\nshape.int = runif(1,-1,1)\nk = 0\nllf = function(x) {\n k =(1 + (x[4]*(Data-(x[1]+(x[2]*time_index)))/x[3]))^(-1/x[4])\n pdf = (1/x[3])*((k)^(x[4]+1))*exp(-k)\n -sum(log(pdf))\n}\nresult = try(\n expr = optim(par = c(mu0.int,mu1.int,scale.int,shape.int), method = \"L-BFGS-B\", fn = llf, lower = c(0,0,0,-Inf)), silent = TRUE\n)\nwhile (class(result) == \"try-error\"){\n k = k+1\n shape.int = runif(1,-1,1)\n result = try(\n expr = optim(par = c(mu0.int,mu1.int,scale.int,shape.int), method = \"L-BFGS-B\", fn = llf, lower = c(0,0,0,-Inf)), silent = TRUE\n )\n }\n mu0 = result$par[1]\n mu1 = result$par[2]\n scale = result$par[3]\n shape = result$par[4]\n NLLH = result$value\n \n \n retevent = calc.nstat.ret.event(mu0,mu1,scale,shape,100,baseyear = referenceyear,analysisyear = referenceyear,1)\n\n\ncat('Maximum Likelihood Estimation (Constrained)','\\n')\ncat('mu0 = ',mu0,'mu1 = ',mu1,'scale = ',scale,'shape = ',shape,'100yr return event = ',retevent,\"NLLH =\",NLLH,'\\n')\n\n", "meta": {"hexsha": "0855ca33218ebff4cfa94e5a24d10ec98b4f2bda", "size": 2560, "ext": "r", "lang": "R", "max_stars_repo_path": "C-MLE_Assunpink.r", "max_stars_repo_name": "abhinavprakash2006/SCBM-R", "max_stars_repo_head_hexsha": "959d1a420c1a29b38c8dd630c9d3300c745f8fa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:24:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-07T13:24:28.000Z", "max_issues_repo_path": "C-MLE_Assunpink.r", "max_issues_repo_name": "abhinavprakash2006/SCBM-R", "max_issues_repo_head_hexsha": "959d1a420c1a29b38c8dd630c9d3300c745f8fa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C-MLE_Assunpink.r", "max_forks_repo_name": "abhinavprakash2006/SCBM-R", "max_forks_repo_head_hexsha": "959d1a420c1a29b38c8dd630c9d3300c745f8fa2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6470588235, "max_line_length": 134, "alphanum_fraction": 0.696484375, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7043422538944778}} {"text": "graphics.off() # This closes all of R's graphics windows.\r\nrm(list=ls()) # Careful! This clears all of R's memory!\r\nlibrary(ggplot2)\r\nlibrary(ggpubr)\r\nlibrary(ks)\r\nlibrary(rjags)\r\nlibrary(runjags)\r\nsetwd(\"~/Documents/MATH2269_Bayesian/2020/presentations/Module 6/Application2\")\r\nsource(\"DBDA2E-utilities.R\") \r\n\r\n#===============PRELIMINARY FUNCTIONS FOR POSTERIOR INFERENCES====================\r\n\r\nsmryMCMC_HD = function( codaSamples , compVal = NULL, saveName=NULL) {\r\n summaryInfo = NULL\r\n mcmcMat = as.matrix(codaSamples,chains=TRUE)\r\n paramName = colnames(mcmcMat)\r\n for ( pName in paramName ) {\r\n if (pName %in% colnames(compVal)){\r\n if (!is.na(compVal[pName])) {\r\n summaryInfo = rbind( summaryInfo , summarizePost( paramSampleVec = mcmcMat[,pName] , \r\n compVal = as.numeric(compVal[pName]) ))\r\n }\r\n else {\r\n summaryInfo = rbind( summaryInfo , summarizePost( paramSampleVec = mcmcMat[,pName] ) )\r\n }\r\n } else {\r\n summaryInfo = rbind( summaryInfo , summarizePost( paramSampleVec = mcmcMat[,pName] ) )\r\n }\r\n }\r\n rownames(summaryInfo) = paramName\r\n \r\n # summaryInfo = rbind( summaryInfo , \r\n # \"tau\" = summarizePost( mcmcMat[,\"tau\"] ) )\r\n if ( !is.null(saveName) ) {\r\n write.csv( summaryInfo , file=paste(saveName,\"SummaryInfo.csv\",sep=\"\") )\r\n }\r\n return( summaryInfo )\r\n}\r\n\r\n#===============================================================================\r\n\r\nplotMCMC_HD = function( codaSamples , data , xName=\"x\" , yName=\"y\" ,\r\n showCurve=FALSE , pairsPlot=FALSE , compVal = NULL,\r\n saveName=NULL , saveType=\"jpg\" ) {\r\n # showCurve is TRUE or FALSE and indicates whether the posterior should\r\n # be displayed as a histogram (by default) or by an approximate curve.\r\n # pairsPlot is TRUE or FALSE and indicates whether scatterplots of pairs\r\n # of parameters should be displayed.\r\n #-----------------------------------------------------------------------------\r\n y = data[,yName]\r\n x = as.matrix(data[,xName])\r\n mcmcMat = as.matrix(codaSamples,chains=TRUE)\r\n chainLength = NROW( mcmcMat )\r\n zbeta0 = mcmcMat[,\"zbeta0\"]\r\n zbeta = mcmcMat[,grep(\"^zbeta$|^zbeta\\\\[\",colnames(mcmcMat))]\r\n if ( ncol(x)==1 ) { zbeta = matrix( zbeta , ncol=1 ) }\r\n zVar = mcmcMat[,\"zVar\"]\r\n beta0 = mcmcMat[,\"beta0\"]\r\n beta = mcmcMat[,grep(\"^beta$|^beta\\\\[\",colnames(mcmcMat))]\r\n if ( ncol(x)==1 ) { beta = matrix( beta , ncol=1 ) }\r\n tau = mcmcMat[,\"tau\"]\r\n pred1 = mcmcMat[,\"pred[1]\"] # Added by Demirhan\r\n pred2 = mcmcMat[,\"pred[2]\"] # Added by Demirhan\r\n pred3 = mcmcMat[,\"pred[3]\"] # Added by Demirhan\r\n pred4 = mcmcMat[,\"pred[4]\"] # Added by Demirhan\r\n pred5 = mcmcMat[,\"pred[5]\"] # Added by Demirhan\r\n \r\n #-----------------------------------------------------------------------------\r\n # Compute R^2 for credible parameters:\r\n YcorX = cor( y , x ) # correlation of y with each x predictor\r\n Rsq = zbeta %*% matrix( YcorX , ncol=1 )\r\n #-----------------------------------------------------------------------------\r\n if ( pairsPlot ) {\r\n # Plot the parameters pairwise, to see correlations:\r\n openGraph()\r\n nPtToPlot = 1000\r\n plotIdx = floor(seq(1,chainLength,by=chainLength/nPtToPlot))\r\n panel.cor = function(x, y, digits=2, prefix=\"\", cex.cor, ...) {\r\n usr = par(\"usr\"); on.exit(par(usr))\r\n par(usr = c(0, 1, 0, 1))\r\n r = (cor(x, y))\r\n txt = format(c(r, 0.123456789), digits=digits)[1]\r\n txt = paste(prefix, txt, sep=\"\")\r\n if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)\r\n text(0.5, 0.5, txt, cex=1.25 ) # was cex=cex.cor*r\r\n }\r\n pairs( cbind( beta0 , beta , tau )[plotIdx,] ,\r\n labels=c( \"beta[0]\" , \r\n paste0(\"beta[\",1:ncol(beta),\"]\\n\",xName) , \r\n expression(tau) ) , \r\n lower.panel=panel.cor , col=\"skyblue\" )\r\n if ( !is.null(saveName) ) {\r\n saveGraph( file=paste(saveName,\"PostPairs\",sep=\"\"), type=saveType)\r\n }\r\n }\r\n #-----------------------------------------------------------------------------\r\n # Marginal histograms:\r\n \r\n decideOpenGraph = function( panelCount , saveName , finished=FALSE , \r\n nRow=2 , nCol=3 ) {\r\n # If finishing a set:\r\n if ( finished==TRUE ) {\r\n if ( !is.null(saveName) ) {\r\n saveGraph( file=paste0(saveName,ceiling((panelCount-1)/(nRow*nCol))), \r\n type=saveType)\r\n }\r\n panelCount = 1 # re-set panelCount\r\n return(panelCount)\r\n } else {\r\n # If this is first panel of a graph:\r\n if ( ( panelCount %% (nRow*nCol) ) == 1 ) {\r\n # If previous graph was open, save previous one:\r\n if ( panelCount>1 & !is.null(saveName) ) {\r\n saveGraph( file=paste0(saveName,(panelCount%/%(nRow*nCol))), \r\n type=saveType)\r\n }\r\n # Open new graph\r\n openGraph(width=nCol*7.0/3,height=nRow*2.0)\r\n layout( matrix( 1:(nRow*nCol) , nrow=nRow, byrow=TRUE ) )\r\n par( mar=c(4,4,2.5,0.5) , mgp=c(2.5,0.7,0) )\r\n }\r\n # Increment and return panel count:\r\n panelCount = panelCount+1\r\n return(panelCount)\r\n }\r\n }\r\n \r\n # Original scale:\r\n panelCount = 1\r\n if (!is.na(compVal[\"beta0\"])){\r\n panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,\"PostMarg\") )\r\n histInfo = plotPost( beta0 , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(beta[0]) , main=\"Intercept\", compVal = as.numeric(compVal[\"beta0\"] ))\r\n } else { \r\n histInfo = plotPost( beta0 , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(beta[0]) , main=\"Intercept\")\r\n }\r\n for ( bIdx in 1:ncol(beta) ) {\r\n panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,\"PostMarg\") )\r\n if (!is.na(compVal[paste0(\"beta[\",bIdx,\"]\")])) {\r\n histInfo = plotPost( beta[,bIdx] , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(beta[.(bIdx)]) , main=xName[bIdx],\r\n compVal = as.numeric(compVal[paste0(\"beta[\",bIdx,\"]\")]))\r\n } else{\r\n histInfo = plotPost( beta[,bIdx] , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(beta[.(bIdx)]) , main=xName[bIdx])\r\n }\r\n }\r\n panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,\"PostMarg\") )\r\n histInfo = plotPost( tau , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(tau) , main=paste(\"Scale\") )\r\n panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,\"PostMarg\") )\r\n histInfo = plotPost( Rsq , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(R^2) , main=paste(\"Prop Var Accntd\") )\r\n panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,\"PostMarg\") )\r\n histInfo = plotPost( pred1 , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=\"pred1\" , main=\"Prediction 1\" ) # Added by Demirhan\r\n panelCount = decideOpenGraph( panelCount , finished=TRUE , saveName=paste0(saveName,\"PostMarg\") )\r\n histInfo = plotPost( pred2 , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=\"pred2\" , main=\"Prediction 2\" ) # Added by Demirhan\r\n\r\n panelCount = decideOpenGraph( panelCount , finished=TRUE , saveName=paste0(saveName,\"PostMarg\") )\r\n histInfo = plotPost( pred3 , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=\"pred2\" , main=\"Prediction 2\" ) # Added by Demirhan\r\n\r\n panelCount = decideOpenGraph( panelCount , finished=TRUE , saveName=paste0(saveName,\"PostMarg\") )\r\n histInfo = plotPost( pred4 , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=\"pred2\" , main=\"Prediction 2\" ) # Added by Demirhan\r\n\r\n panelCount = decideOpenGraph( panelCount , finished=TRUE , saveName=paste0(saveName,\"PostMarg\") )\r\n histInfo = plotPost( pred5 , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=\"pred2\" , main=\"Prediction 2\" ) # Added by Demirhan\r\n \r\n # Standardized scale:\r\n panelCount = 1\r\n panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,\"PostMargZ\") )\r\n histInfo = plotPost( zbeta0 , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(z*beta[0]) , main=\"Intercept\" )\r\n for ( bIdx in 1:ncol(beta) ) {\r\n panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,\"PostMargZ\") )\r\n histInfo = plotPost( zbeta[,bIdx] , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(z*beta[.(bIdx)]) , main=xName[bIdx] )\r\n }\r\n panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,\"PostMargZ\") )\r\n histInfo = plotPost( zVar , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(z*tau) , main=paste(\"Scale\") )\r\n panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,\"PostMargZ\") )\r\n histInfo = plotPost( Rsq , cex.lab = 1.75 , showCurve=showCurve ,\r\n xlab=bquote(R^2) , main=paste(\"Prop Var Accntd\") )\r\n panelCount = decideOpenGraph( panelCount , finished=TRUE , saveName=paste0(saveName,\"PostMargZ\") )\r\n \r\n #-----------------------------------------------------------------------------\r\n}\r\n\r\n#===============PRELIMINARY FUNCTIONS FOR POSTERIOR INFERENCES====================\r\n\r\n\r\nmyData <- read.csv(\"Assignment2PropertyPrices.csv\")\r\nhead(myData)\r\n\r\n# Scatter plots\r\np1 <- ggplot(myData, aes(x=Area, y=SalePrice.100K.)) +\r\n geom_point() +\r\n xlab(\"Area\") +\r\n ylab(\"SalePrice.100K.\")\r\n\r\np2 <- ggplot(myData, aes(x=Bedrooms, y=SalePrice.100K.)) +\r\n geom_point() +\r\n xlab(\"Bedrooms\") +\r\n ylab(\"SalePrice.100K.\")\r\n\r\n\r\np3 <- ggplot(myData, aes(x=Bathrooms, y=SalePrice.100K.)) +\r\n geom_point() +\r\n xlab(\"Bathrooms\") +\r\n ylab(\"SalePrice.100K.\")\r\n\r\n\r\np4 <- ggplot(myData, aes(x=CarParks, y=SalePrice.100K.)) +\r\n geom_point() +\r\n xlab(\"CarParks\") +\r\n ylab(\"SalePrice.100K.\")\r\n\r\np5 <- ggplot(myData, aes(x=PropertyType, y=SalePrice.100K.)) +\r\n geom_point() +\r\n xlab(\"PropertyType\") +\r\n ylab(\"SalePrice.100K.\")\r\n\r\nfigure <- ggarrange(p1, p2, p3, p4, p5, nrow = 2, ncol = 3)\r\nfigure\r\n\r\n# Histogram\r\nhist(myData$SalePrice.100K., main= \" Histogram of the dependent variable\", xlab = \"Cost\")\r\n# Kernel density estimation\r\nplot(kde(myData$SalePrice.100K.), xlab = \"Cost\") # with default settings\r\n\r\n\r\n# THE DATA.\r\ny = myData[,\"Y\"]\r\nx = as.matrix(myData[,c(\"X1\",\"X2\",\"X3\",\"X4\",\"X5\")])\r\n\r\n# Some more descriptives\r\ncat(\"\\nCORRELATION MATRIX OF PREDICTORS:\\n \")\r\nshow( round(cor(x),3) )\r\ncat(\"\\n\")\r\n\r\nxPred = array(NA, dim = c(5,5))\r\nxPred[1,] = c(600, 2, 2, 1, 1)\r\nxPred[2,] = c(800, 3, 1, 2, 0)\r\nxPred[3,] = c(1500, 2, 1, 1, 0)\r\nxPred[4,] = c(2500, 5, 4, 4, 0)\r\nxPred[5,] = c(250, 3, 2, 1, 1)\r\n\r\n# Specify the data in a list, for later shipment to JAGS:\r\ndataList <- list(\r\n x = x ,\r\n y = y ,\r\n xPred = xPred ,\r\n Nx = dim(x)[2] ,\r\n Ntotal = dim(x)[1]\r\n)\r\n\r\n# First run without initials!\r\ninitsList <- list(\r\n zbeta0 = 2000,\r\n zbeta = c(0.009, 1, 1, 1.2, -1.5),\r\n Var = 12000000\r\n)\r\n\r\n# WE WILL RUN THE MODEL WITH SCALING!\r\n\r\n# THE MODEL.\r\nmodelString = \"\r\n# Standardize the data:\r\ndata {\r\n ysd <- sd(y)\r\n for ( i in 1:Ntotal ) {\r\n zy[i] <- y[i] / ysd\r\n }\r\n for ( j in 1:Nx ) {\r\n xsd[j] <- sd(x[,j])\r\n for ( i in 1:Ntotal ) {\r\n zx[i,j] <- x[i,j] / xsd[j]\r\n }\r\n }\r\n}\r\n# Specify the model for scaled data:\r\nmodel {\r\n for ( i in 1:Ntotal ) {\r\n zy[i] ~ dgamma( (mu[i]^2)/zVar , mu[i]/zVar ) \r\n mu[i] <- zbeta0 + sum( zbeta[1:Nx] * zx[i,1:Nx] ) \r\n }\r\n # Priors on standardized scale:\r\n zbeta0 ~ dnorm( 0 , 1/2^2 ) # 1/ variance for normal distribution\r\n zbeta[1] ~ dnorm( 0.0009/xsd[1] , 1/(0.01/xsd[1]^2) ) # 1/ variance for normal distribution\r\n zbeta[2] ~ dnorm( 1 , 1/(2/xsd[2]^2) ) ) # 1/ variance for normal distribution\r\n zbeta[3] ~ dnorm( 0 , 1/4 ) # 1/ variance for normal distribution\r\n zbeta[4] ~ dnorm( (1.2)/xsd[4] , 1/(0.1/xsd[4]^2) ) # 1/ variance for normal distribution\r\n zbeta[5] ~ dnorm( (-1.5)/xsd[5] , 1/(0.01/xsd[5]^2) ) # 1/ variance for normal distribution\r\n zVar ~ dgamma( 0.01 , 0.01 )\r\n # Transform to original scale:\r\n beta[1:Nx] <- ( zbeta[1:Nx] / xsd[1:Nx] ) * ysd\r\n beta0 <- zbeta0*ysd\r\n tau <- zVar * (ysd)^2\r\n\r\n # Compute predictions at every step of the MCMC\r\n for ( i in 1:5){\r\n pred[i] <- beta0 + beta[1] * xPred[i,1] + beta[2] * xPred[i,2] + beta[3] * xPred[i,3] + beta[4] * xPred[i,4] + beta[5] * xPred[i,5]\r\n }\r\n # pred[1] <- beta0 + beta[1] * xPred[1,1] + beta[2] * xPred[1,2] + beta[3] * xPred[1,3] + beta[4] * xPred[1,4]\r\n # pred[2] <- beta0 + beta[1] * xPred[2,1] + beta[2] * xPred[2,2] + beta[3] * xPred[2,3] + beta[4] * xPred[2,4]\r\n\r\n}\r\n\" # close quote for modelString\r\n# Write out modelString to a text file\r\nwriteLines( modelString , con=\"TEMPmodel_Assignment2.txt\" )\r\n\r\n\r\nparameters = c( \"zbeta0\" , \"zbeta\" , \"beta0\" , \"beta\" , \"tau\", \"zVar\") # Here beta is a vector!\r\n\r\nadaptSteps = 1500 # Number of steps to \"tune\" the samplers\r\nburnInSteps = 5000\r\nnChains = 3 \r\nthinSteps = 40 # First run for 3\r\nnumSavedSteps = 10000\r\nnIter = ceiling( ( numSavedSteps * thinSteps ) / nChains )\r\n\r\n# Parallel run\r\nrunJagsOut <- run.jags( method=\"parallel\" ,\r\n model=\"TEMPmodel_Assignment2.txt\" ,\r\n monitor=c( \"zbeta0\" , \"zbeta\" , \"beta0\" , \"beta\" , \"tau\", \"zVar\", \"pred\") ,\r\n data=dataList ,\r\n inits=initsList ,\r\n n.chains=nChains ,\r\n adapt=adaptSteps ,\r\n burnin=burnInSteps ,\r\n sample=numSavedSteps ,\r\n thin=thinSteps , summarise=FALSE , plots=FALSE )\r\ncodaSamples = as.mcmc.list( runJagsOut )\r\n\r\n# save.image(file=\"rEnvironment.RData\")\r\n#load(file=\"rEnvironment.RData\") # Load the results with 124,000 iterations\r\n\r\ndiagMCMC( codaSamples , parName=\"beta0\" )\r\ndiagMCMC( codaSamples , parName=\"beta[1]\" )\r\ndiagMCMC( codaSamples , parName=\"beta[2]\" )\r\ndiagMCMC( codaSamples , parName=\"beta[3]\" )\r\ndiagMCMC( codaSamples , parName=\"beta[4]\" )\r\ndiagMCMC( codaSamples , parName=\"beta[5]\" )\r\ndiagMCMC( codaSamples , parName=\"tau\" )\r\ndiagMCMC( codaSamples , parName=\"pred[1]\" )\r\ndiagMCMC( codaSamples , parName=\"pred[2]\" )\r\ndiagMCMC( codaSamples , parName=\"pred[3]\" )\r\ndiagMCMC( codaSamples , parName=\"pred[4]\" )\r\ndiagMCMC( codaSamples , parName=\"pred[5]\" )\r\ndiagMCMC( codaSamples , parName=\"zbeta0\" )\r\ndiagMCMC( codaSamples , parName=\"zbeta[1]\" )\r\n\r\ncompVal <- data.frame(\"beta0\" = NA, \"beta[1]\" = NA, \"beta[2]\" = NA, \"beta[3]\" = NA, \"beta[4]\" = NA, \"tau\" = NA , check.names=FALSE)\r\n\r\nsummaryInfo <- smryMCMC_HD( codaSamples = codaSamples , compVal = compVal )\r\nprint(summaryInfo)\r\n\r\n\r\nplotMCMC_HD( codaSamples = codaSamples , data = myData, xName=c(\"X1\",\"X2\",\"X3\",\"X4\") , \r\n yName=\"Y\", compVal = compVal)\r\n\r\n# ============ Predictive check ============\r\ncoefficients <- summaryInfo[7:11,3] # Get the model coefficients out\r\nVariance <- summaryInfo[12,3] # Get the variance out\r\n# Since we imposed the regression model on the mean of the gamma likelihood,\r\n# we use the model (X*beta) to generate the mean of gamma population for each \r\n# observed x vector. \r\nmeanGamma <- as.matrix(cbind(rep(1,nrow(x)), x)) %*% as.vector(coefficients)\r\n# Generate random data from the posterior distribution. Here I take the \r\n# reparameterisation back to alpha and beta.\r\nrandomData <- rgamma(n= 10000,shape=meanGamma^2/Variance, rate = meanGamma/Variance)\r\n\r\n# Display the density plot of observed data and posterior distribution:\r\npredicted <- data.frame(elapsed = randomData)\r\nobserved <- data.frame(elapsed = y)\r\npredicted$type <- \"Predicted\"\r\nobserved$type <- \"Observed\"\r\ndataPred <- rbind(predicted, observed)\r\n\r\nggplot(dataPred, aes(elapsed, fill = type)) + geom_density(alpha = 0.2)\r\n", "meta": {"hexsha": "d37b5e6c1d933b49d2d0e19028b82340cffb7a14", "size": 15853, "ext": "r", "lang": "R", "max_stars_repo_path": "assignment2.r", "max_stars_repo_name": "modihill/bayesian_assignment_with_JAGS_and_MCMC_chains", "max_stars_repo_head_hexsha": "359e7671fe589ebd43c1f00907b34d731e2b62de", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment2.r", "max_issues_repo_name": "modihill/bayesian_assignment_with_JAGS_and_MCMC_chains", "max_issues_repo_head_hexsha": "359e7671fe589ebd43c1f00907b34d731e2b62de", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment2.r", "max_forks_repo_name": "modihill/bayesian_assignment_with_JAGS_and_MCMC_chains", "max_forks_repo_head_hexsha": "359e7671fe589ebd43c1f00907b34d731e2b62de", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9638242894, "max_line_length": 136, "alphanum_fraction": 0.5767362644, "num_tokens": 4993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7043194257413782}} {"text": " ## prediction equation is\r\n #y=25.0+1.5*x1+0.8*x2\r\nY <- matrix(c(25,19,33,23),4,1)\r\nX <- matrix(c(1,1,1,1,-2,-2,2,2,5,-5,5,-5),4,3)\r\ntranspose_X=t(X)\r\ntranspose_X_X=transpose_X%*%X\r\ninverse_transpose_X_X=solve(transpose_X_X)\r\ninverse_transpose_X_X\r\n# for estimated standard error use inverse_trasnpose_X_X matrix\r\ns_beta0=2*sqrt(0.25)\r\ns_beta0\r\ns_beta1=2*sqrt(0.0625)\r\ns_beta2=2*sqrt(0.01)\r\ns_beta1\r\ns_beta2\r\n", "meta": {"hexsha": "4db247b8d01ebb450efdf746aa67bf2565aacf52", "size": 411, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH12/EX12.31/Ex12_31.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH12/EX12.31/Ex12_31.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH12/EX12.31/Ex12_31.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 25.6875, "max_line_length": 65, "alphanum_fraction": 0.7128953771, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.704077062743126}} {"text": "subroutine circen(i,j,k,x0,y0,x,y,ntot,eps,collin,nerror)\n# Find the circumcentre (x0,y0) of the triangle with\n# vertices (x(i),y(i)), (x(j),y(j)), (x(k),y(k)).\n# Called by qtest1, dirseg, dirout.\n\nimplicit double precision(a-h,o-z)\ndimension x(-3:ntot), y(-3:ntot), xt(3), yt(3)\nlogical collin\n\nnerror = -1\n\n# Get the coordinates.\nxt(1) = x(i)\nyt(1) = y(i)\nxt(2) = x(j)\nyt(2) = y(j)\nxt(3) = x(k)\nyt(3) = y(k)\n\n# Check for collinearity\nijk = 0\ncall cross(xt,yt,ijk,cprd)\nif(abs(cprd) < eps) collin = .true.\nelse collin = .false.\n\n# Form the vector u from i to j, and the vector v from i to k,\n# and normalize them.\na = x(j) - x(i)\nb = y(j) - y(i)\nc = x(k) - x(i)\nd = y(k) - y(i)\nc1 = sqrt(a*a+b*b)\nc2 = sqrt(c*c+d*d)\na = a/c1\nb = b/c1\nc = c/c2\nd = d/c2\n\n# If the points are collinear, make sure that they're in the right\n# order --- i between j and k.\nif(collin) {\n alpha = a*c+b*d\n # If they're not in the right order, bring things to\n # a shuddering halt.\n if(alpha>0) {\n\t\tnerror = 3\n\t\treturn\n }\n # Collinear, but in the right order; think of this as meaning\n # that the circumcircle in question has infinite radius.\n return\n}\n\n# Not collinear; go ahead, make my circumcentre. (First, form\n# the cross product of the ***unit*** vectors, instead of the\n# ``normalized'' cross product produced by ``cross''.)\ncrss = a*d - b*c\nx0 = x(i) + 0.5*(c1*d - c2*b)/crss\ny0 = y(i) + 0.5*(c2*a - c1*c)/crss\n\nreturn\nend\n", "meta": {"hexsha": "e2f5d05c028be948de4e18c64f69c56d55934906", "size": 1473, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/circen.r", "max_stars_repo_name": "hyeongmokoo/SAAR_beta1", "max_stars_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-08-23T15:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T12:20:59.000Z", "max_issues_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/circen.r", "max_issues_repo_name": "hyeongmokoo/SAAR_beta1", "max_issues_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/circen.r", "max_forks_repo_name": "hyeongmokoo/SAAR_beta1", "max_forks_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-21T00:51:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-21T00:51:33.000Z", "avg_line_length": 23.380952381, "max_line_length": 69, "alphanum_fraction": 0.5987780041, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.7038683952430898}} {"text": "library(deSolve)\nlibrary(tidyr)\nlibrary(reshape)\nlibrary(magrittr)\nlibrary(plyr)\nlibrary(dplyr)\nlibrary(ggplot2)\n\n\nm <- 4 #number of age classes\nmu <- c(0,0,0,1/(55*365)) #death rate in each age group; it is assumed that only adults die\nnu <- c(1/(55*365),0,0,0) #is the birth rate into the childhood class; it is assumed only adults give birth.\nn <- c(6,4,10,55)/75 # fraction in each age class (assumption that life expectancy is 75 years)\nS0 <- c(0.05,0.01,0.01,0.008) # inital value for number of susceptible\nE0 <- c(0.0001,0.0001,0.0001,0.0001) # inital value for number of exposed\nI0 <- c(0.0001,0.0001,0.0001,0.0001) # inital value for number of infectious\nR0 <- c(0.0298, 0.04313333, 0.12313333, 0.72513333) # inital value for number of recovered\nND <- 365 # time to simulate\nbeta <- matrix(c(2.089, 2.089, 2.086, 2.037, 2.089, 9.336, 2.086, 2.037, 2.086, 2.086, \n 2.086, 2.037, 2.037, 2.037, 2.037, 2.037), nrow=4, ncol=4) # matrix of transmission rates\ngamma <- 1/5 # recovery rate\nsigma <- 1/8 # rate at which individuals move from the exposed to the infectious classes\nTS <- 1 # time step to simualte is days\n\n# combining parameter and initial values\nparms <- list(nu=nu, beta=beta, mu=mu, sigma=sigma, gamma=gamma)\nINPUT <- c(S0, E0, I0, R0)\n\n# constructing time vector\nt_start <- 0 # starting time\nt_end <- ND - 1 # ending time\nt_inc <- TS #time increment\nt_range <- seq(from= t_start, to=t_end+t_inc, by=t_inc) # vector with time steps\n\n# differential equations\ndiff_eqs <- function(times, Y, parms){\n dY <- numeric(length(Y))\n with(parms,{\n # creates an empty matrix \n for(i in 1:m){\n dY[i] <- nu[i]*n[4] - beta[,i]%*%Y[2*m + seq(1:m)] * Y[i] - mu[i] * Y[i] # S_i\n dY[m+i] <- beta[,i] %*% Y[2*m + seq(1:m)] *Y[i] - mu[i] * Y[m+i] - sigma * Y[m+i] #E_i\n dY[2*m+i] <- sigma * Y[m+i] - gamma * Y[2*m + i] - mu[i] * Y[2*m+i] #I_i\n dY[3*m+i] <- gamma * Y[2*m+i] - mu[i] * Y[3*m + i] #R_i\n }\n list(dY) \n })\n}\n\nRES2=rep(0,17) #initalizing the result vector \nnumber_years <- 100 #set the number of years to simulate \n\n# initialize the loop\nk=1\n# yearly ageing\nfor(k in 1:number_years) {\n RES = lsoda(INPUT, t_range, diff_eqs, parms)\n #taking the last entry as the the new input that then is propagated accoring to the aging\n INPUT=RES[366,-1]\n INPUT[16]=INPUT[16]+INPUT[15]/10\n INPUT[15]=INPUT[15]+INPUT[14]/4-INPUT[15]/10\n INPUT[14]=INPUT[14]+INPUT[13]/6-INPUT[14]/4\n INPUT[13]=INPUT[13]-INPUT[13]/6\n\n INPUT[12]=INPUT[12]+INPUT[11]/10\n INPUT[11]=INPUT[11]+INPUT[10]/4-INPUT[11]/10\n INPUT[10]=INPUT[10]+INPUT[9]/6-INPUT[10]/4\n INPUT[9]=INPUT[9]-INPUT[9]/6\n \n INPUT[8]=INPUT[8]+INPUT[7]/10\n INPUT[7]=INPUT[7]+INPUT[6]/4-INPUT[7]/10\n INPUT[6]=INPUT[6]+INPUT[5]/6-INPUT[6]/4\n INPUT[5]=INPUT[5]-INPUT[5]/6\n\n INPUT[4]=INPUT[4]+INPUT[3]/10\n INPUT[3]=INPUT[3]+INPUT[2]/4-INPUT[3]/10\n INPUT[2]=INPUT[2]+INPUT[1]/6-INPUT[2]/4\n INPUT[1]=INPUT[1]-INPUT[1]/6\n RES2 <- rbind(RES2,RES)\n k=k+1\n}\n\n#rescaling time to years\ntime <- seq(from=0, to=100*(ND+1))/(ND+1)\n#changing time to the rescaled time\nRES2[ ,\"time\"] <- time\n\n#labeling of the output from ODE solver\nlabel <- c(\"S1\", \"S2\", \"S3\", \"S4\",\"E1\", \"E2\", \"E3\", \"E4\", \"I1\", \"I2\", \"I3\", \"I4\", \"R1\", \"R2\", \"R3\", \"R4\")\nlabel1 <- substr(label, 1, 1)\nAge <- substr(label, 2, 2)\n\ndf <- data.frame(time = RES2[, 1],\n label1 = rep(label1, each = nrow(RES2)),\n Age = rep(Age, each = nrow(RES2)),\n value = c(RES2[, -1]))\n\n# Plot\ndf$label1 <- factor(df$label1, levels = c(\"S\",\"E\",\"I\",\"R\"))\ndf$Age <- factor(df$Age)\ndf %>% mutate(label1 = recode(label1, S = \"Susceptible\")) %>% \n mutate(label1 = recode(label1, E = \"Exposed\")) %>% \n mutate(label1 = recode(label1, I = \"Infectious\")) %>%\n mutate(label1 = recode(label1, R = \"Recovered\")) %>%\n mutate(Age = recode(Age, \"1\" = \"0-6 years \")) %>%\n mutate(Age = recode(Age, \"2\" = \"6-10 years \")) %>%\n mutate(Age = recode(Age, \"3\" = \"10-20 years \")) %>% \n mutate(Age = recode(Age, \"4\" = \"20+ years \")) %>% \nggplot() +\n geom_line(aes(x = time, y = value, color = Age)) +\n facet_wrap( ~label1, ncol=1, scales = \"free_y\")+ \n xlab(\"Time (years)\") + ylab(\" Individuals\")\n", "meta": {"hexsha": "734245f8a159bead2ed34eb30c1d42917bf1dacc", "size": 4241, "ext": "r", "lang": "R", "max_stars_repo_path": "models/keeling_rohani_2008/program_3_4_age_structured_seir.r", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/keeling_rohani_2008/program_3_4_age_structured_seir.r", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/keeling_rohani_2008/program_3_4_age_structured_seir.r", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 37.5309734513, "max_line_length": 108, "alphanum_fraction": 0.6064607404, "num_tokens": 1626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7038003368919495}} {"text": "set.seed(0)\n\ndot <- function(x){\n return(sum(x * x))\n}\n\n### DATA\n# Public data\nK = 3\nM = 10000\n\n# Alice's private data\nN1 = 1000\ny1 = rnorm(N1)\nX1 = matrix(rnorm(N1 * M), N1, M)\nC1 = matrix(rnorm(N1 * K), N1, K)\n\n# Bob's private data\nN2 = 2000\ny2 = rnorm(N2)\nX2 = matrix(rnorm(N2 * M), N2, M)\nC2 = matrix(rnorm(N2 * K), N2, K)\n\n# Carla's private data\nN3 = 1500\ny3 = rnorm(N3)\nX3 = matrix(rnorm(N3 * M), N3, M)\nC3 = matrix(rnorm(N3 * K), N3, K)\n\n### PRIVATE COMPUTE compresses the data.\n# Alice computes and secret shares...\nyy1 = dot(y1)\nXy1 = t(X1) %*% y1\nXX1 = apply(X1,2,dot)\n\nCty1 = t(C1) %*% y1\nCtX1 = t(C1) %*% X1\n\nR1 = qr.R(qr(C1))\n\n# Bob computes and secret shares...\nyy2 = dot(y2)\nXy2 = t(X2) %*% y2\nXX2 = apply(X2, 2, dot)\n\nCty2 = t(C2) %*% y2\nCtX2 = t(C2) %*% X2\n\nR2 = qr.R(qr(C2))\n\n# Carla computes and secret shares...\nyy3 = dot(y3)\nXy3 = t(X3) %*% y3\nXX3 = apply(X3, 2, dot)\n\nCty3 = t(C3) %*% y3\nCtX3 = t(C3) %*% X3\n\nR3 = qr.R(qr(C3))\n\n### SECURE MULTI-PARTY COMPUTE is now independent of the sample sizes.\nD = N1 + N2 + N3 - K - 1\n\nyy = yy1 + yy2 + yy3\nXy = Xy1 + Xy2 + Xy3\nXX = XX1 + XX2 + XX3\n\nCty = Cty1 + Cty2 + Cty3\nCtX = CtX1 + CtX2 + CtX3\n\ninvR = solve(qr.R(qr(rbind(R1, R2, R3))))\n\nQty = t(invR) %*% Cty \nQtX = t(invR) %*% CtX\n\nQtyQty = dot(Qty)\nQtXQty = t(QtX) %*% Qty\nQtXQtX = apply(QtX, 2, dot)\n\nyyq = yy - QtyQty\nXyq = Xy - QtXQty\nXXq = XX - QtXQtX\n\n# The endpoints of secure computation are effect size and squared standard error.\nbeta = Xyq / XXq\nsigma_sq = (yyq / XXq - beta^2) / D\n\n# These determine the t statistic and p-value.\nsigma = sqrt(sigma_sq)\ntstat = beta / sigma\npval = 2 * pt(-abs(tstat), D)\n\ndf = data.frame(beta=beta, sigma=sigma, tstat=tstat, pval=pval)\n\n# VERIFY correctness for the first M0 columns of X:\nM0 = 5\n\ny = c(y1 ,y2, y3)\nX = rbind(X1, X2, X3)\nC = rbind(C1, C2, C3)\n\nres = matrix(nrow=0,ncol=4)\nfor (m in 1:M0) {\n fit = lm(y ~ X[,m] + C - 1)\n res = rbind(res,as.vector(summary(fit)$coefficients[1,]))\n}\n\ndf2 = data.frame(beta=res[,1], sigma=res[,2], tstat=res[,3], pval=res[,4])\n\nall.equal(df[1:M0,],df2) # Returns TRUE\n", "meta": {"hexsha": "101a2fefa46c0ff8cc2766c119b699321281da5a", "size": 2079, "ext": "r", "lang": "R", "max_stars_repo_path": "dash.r", "max_stars_repo_name": "JamesHWade/DASH", "max_stars_repo_head_hexsha": "45a0be0164fcd91974e1ac24e0568e85d395440d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-01-29T22:03:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T08:51:58.000Z", "max_issues_repo_path": "dash.r", "max_issues_repo_name": "JamesHWade/DASH", "max_issues_repo_head_hexsha": "45a0be0164fcd91974e1ac24e0568e85d395440d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-10T23:50:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T23:50:44.000Z", "max_forks_repo_path": "dash.r", "max_forks_repo_name": "JamesHWade/DASH", "max_forks_repo_head_hexsha": "45a0be0164fcd91974e1ac24e0568e85d395440d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:39:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-10T22:12:24.000Z", "avg_line_length": 18.7297297297, "max_line_length": 81, "alphanum_fraction": 0.6012506013, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.703632239031068}} {"text": "#### estimating the algorithms for doorspread and wing spread for filling in gaps in the datras flexfile. \n\nlibrary(icesDatras)\nlibrary(mgcv)\n\n\nhh<-getDATRAS(\"HH\",\"NS-IBTS\",c(2003:2020),c(1)) ## HH data downloaded from the ICES data\nhh<-hh[hh$HaulVal==\"V\",]\n\nhh.NL<-hh[hh$Country==\"NED\",]\nhh.NL<-hh.NL[hh.NL$DoorSpread>0,]\n\n# correcting errors not yet changed in Datras\nhh.NL[hh.NL$DoorSpread==48,]$DoorSpread<-74\nhh.NL[hh.NL$Year==2005 & hh.NL$HaulNo==20,]$DoorSpread<-91\nhh.NL[hh.NL$Year==2010 & hh.NL$DoorSpread>98,]$DoorSpread<--9\nhh.NL<-hh.NL[hh.NL$DoorSpread>50,]\nhh.NL<-hh.NL[hh.NL$Warplngt>0,]\nhh.NL<-hh.NL[hh.NL$Depth>1,]\n\nhh.NL$Doorcal.Den<-79.254-(34.368*exp(-0.029*hh.NL$Depth)) ## Danish algorithm for doorspread\nhh.NL$Doorcal.MAF<-(33.251*log10(hh.NL$Depth))+ 15.744 ## Algorithm proposed by the EU project MAFCONS\n\n\nplot(hh.NL$DoorSpread~hh.NL$Depth, ylim=c(30,140))\nlines(hh.NL$Doorcal.Den~hh.NL$Depth, col=\"blue\")\nlines(hh.NL$Doorcal.MAF~hh.NL$Depth, col=\"red\")\n# clear underestimation of the Dutch values\n\nmm<-lm(hh.NL$Warplngt~hh.NL$Depth)\n\nhh.NL<-hh.NL[is.na(hh.NL$Depth)==F,]\nhh.NL<-hh.NL[is.na(hh.NL$Warplngt)==F,]\n\nDoorSpread<- hh.NL$DoorSpread\nDepth<- hh.NL$Depth\nWarplngt<- hh.NL$Warplngt\n\nt1<-nls(hh.NL$DoorSpread~a*log10(hh.NL$Depth)+d*log10(hh.NL$Warplngt)+ b, start = list(a = 16, b = -30, d = -15))\n\ntest1<-data.frame(Depth=seq(0,200,by=1))\ntest1$Warplngt<-mm$coefficients[1]+test1$Depth*mm$coefficients[2]\n\ntest1$nls.fun<-summary(t1)$parameters[1]*log10(test1$Depth)+summary(t1)$parameters[3]*log10(test1$Warplngt)+ summary(t1)$parameters[2]\nlines(test1$nls.fun~test1$Depth, col=\"gold\")\n## better fit\nsummary(t1)$parameters\n\n\n###forcing to a doorspread of zero\nzero<-hh.NL[1,]\nzero$DoorSpread<-45\nzero$Depth<-10\nzero$Warplngt<-mm$coefficients[1]+zero$Depth*mm$coefficients[2]\n\nmax<-hh.NL[1,]\nmax$DoorSpread<-100\nmax$Depth<-180\nmax$Warplngt<-mm$coefficients[1]+max$Depth*mm$coefficients[2]\n\n\n\nhh.NL1<-rbind(zero,hh.NL,max)\nwe = rep(1, dim(hh.NL1)[1])\nwe[1]<-1000 \nwe[length(we)]<-1000 \n\nd1<-hh.NL1$DoorSpread\nd2<-hh.NL1$Depth\nd3<-hh.NL1$Warplngt\n\nt1<-nls(d1~a*log10(d2)+d*log10(d3)+ b,weights=we, start = list(a = 16, b = -30, d = -15))\ntest1$nls.fun<-summary(t1)$parameters[1]*log10(test1$Depth)+summary(t1)$parameters[3]*log10(test1$Warplngt)+ summary(t1)$parameters[2]\nlines(test1$nls.fun~test1$Depth, col=\"green\")\n\n\n\n\n##### year effect\n\nplot(hh.NL$DoorSpread~hh.NL$Depth, ylim=c(30,140))\n\nfor(i in unique(hh.NL$Year)){\nd1<-hh.NL[hh.NL$Year==i,]$DoorSpread\nd2<-hh.NL[hh.NL$Year==i,]$Depth\nd3<-hh.NL[hh.NL$Year==i,]$Warplngt\n\nt1<-nls(d1~a*log10(d2)+d*log10(d3)+ b, start = list(a = 16, b = -30, d = -15))\ntest1$nls.fun<-summary(t1)$parameters[1]*log10(test1$Depth)+summary(t1)$parameters[3]*log10(test1$Warplngt)+ summary(t1)$parameters[2]\n\nlines(test1$nls.fun~test1$Depth, col=i)\nSys.sleep(3)\n}\n\n#### groups 2003+2004, 2005-2014, 2015+2016, 2017-2020\nplot(hh.NL$DoorSpread~hh.NL$Depth, ylim=c(30,120), xlab=\"Depth (m)\",ylab=\"Doorspread (m)\")\n\nzero<-hh.NL[1,]\nzero$DoorSpread<-55\nzero$Depth<-10\nzero$Warplngt<-mm$coefficients[1]+zero$Depth*mm$coefficients[2]\n\nmax<-hh.NL[1,]\nmax$DoorSpread<-110\nmax$Depth<-180\nmax$Warplngt<-mm$coefficients[1]+max$Depth*mm$coefficients[2]\n\nhh.NL1<-rbind(zero,hh.NL[hh.NL$Year %in% c(2003,2004),],max)\nwe = rep(1, dim(hh.NL1)[1])\nwe[1]<-5 \nwe[length(we)]<-50\n\n d1<-hh.NL1$DoorSpread\n d2<-hh.NL1$Depth\n d3<-hh.NL1$Warplngt\n \n t1<-nls(d1~a*log10(d2)+d*log10(d3)+ b,weights=we, start = list(a = 16, b = -20, d = 35))\n test1$nls.fun<-summary(t1)$parameters[1]*log10(test1$Depth)+summary(t1)$parameters[3]*log10(test1$Warplngt)+ summary(t1)$parameters[2]\n \n # plot(hh.NL1$DoorSpread~hh.NL1$Depth, ylim=c(30,140))\n lines(test1$nls.fun~test1$Depth, col=\"red\")\n summary(t1)$parameters\n\n#####2005-2014\n \n zero<-hh.NL[1,]\n zero$DoorSpread<-55\n zero$Depth<-10\n zero$Warplngt<-mm$coefficients[1]+zero$Depth*mm$coefficients[2]\n \n max<-hh.NL[1,]\n max$DoorSpread<-100\n max$Depth<-180\n max$Warplngt<-mm$coefficients[1]+max$Depth*mm$coefficients[2]\n \n hh.NL1<-rbind(zero,hh.NL[hh.NL$Year %in% c(2005:2014),],max)\n we = rep(1, dim(hh.NL1)[1])\n we[1]<-50 \n we[length(we)]<-50\n \n d1<-hh.NL1$DoorSpread\n d2<-hh.NL1$Depth\n d3<-hh.NL1$Warplngt\n \n t1<-nls(d1~a*log10(d2)+d*log10(d3)+ b,weights=we, start = list(a = 16, b = -20, d = 35))\n test1$nls.fun<-summary(t1)$parameters[1]*log10(test1$Depth)+summary(t1)$parameters[3]*log10(test1$Warplngt)+ summary(t1)$parameters[2]\n \n # plot(hh.NL1$DoorSpread~hh.NL1$Depth, ylim=c(30,140))\n lines(test1$nls.fun~test1$Depth, col=\"blue\")\n summary(t1)$parameters\n\n #####2015-2016\n \n zero<-hh.NL[1,]\n zero$DoorSpread<-45\n zero$Depth<-10\n zero$Warplngt<-mm$coefficients[1]+zero$Depth*mm$coefficients[2]\n \n max<-hh.NL[1,]\n max$DoorSpread<-100\n max$Depth<-180\n max$Warplngt<-mm$coefficients[1]+max$Depth*mm$coefficients[2]\n \n hh.NL1<-rbind(zero,hh.NL[hh.NL$Year %in% c(2015:2016),],max)\n we = rep(1, dim(hh.NL1)[1])\n we[1]<-50 \n we[length(we)]<-50\n \n d1<-hh.NL1$DoorSpread\n d2<-hh.NL1$Depth\n d3<-hh.NL1$Warplngt\n \n t1<-nls(d1~a*log10(d2)+d*log10(d3)+ b,weights=we, start = list(a = 16, b = -20, d = 35))\n test1$nls.fun<-summary(t1)$parameters[1]*log10(test1$Depth)+summary(t1)$parameters[3]*log10(test1$Warplngt)+ summary(t1)$parameters[2]\n \n #plot(hh.NL1$DoorSpread~hh.NL1$Depth, ylim=c(30,140))\n lines(test1$nls.fun~test1$Depth, col=\"green\")\n summary(t1)$parameters\n\n ### 2017-2020\n zero<-hh.NL[1,]\n zero$DoorSpread<-55\n zero$Depth<-10\n zero$Warplngt<-mm$coefficients[1]+zero$Depth*mm$coefficients[2]\n \n max<-hh.NL[1,]\n max$DoorSpread<-100\n max$Depth<-180\n max$Warplngt<-mm$coefficients[1]+max$Depth*mm$coefficients[2]\n \n hh.NL1<-rbind(zero,hh.NL[hh.NL$Year %in% c(2017:2020),],max)\n we = rep(1, dim(hh.NL1)[1])\n we[1]<-50 \n we[length(we)]<-50\n \n d1<-hh.NL1$DoorSpread\n d2<-hh.NL1$Depth\n d3<-hh.NL1$Warplngt\n \n t1<-nls(d1~a*log10(d2)+d*log10(d3)+ b,weights=we, start = list(a = 16, b = -20, d = 35))\n test1$nls.fun<-summary(t1)$parameters[1]*log10(test1$Depth)+summary(t1)$parameters[3]*log10(test1$Warplngt)+ summary(t1)$parameters[2]\n \n #plot(hh.NL1$DoorSpread~hh.NL1$Depth, ylim=c(30,140))\n lines(test1$nls.fun~test1$Depth, col=\"gold\")\n summary(t1)$parameters\n \n\n", "meta": {"hexsha": "b5d0fb24c0747464aa9ba5eb8748454d5a17b038", "size": 6271, "ext": "r", "lang": "R", "max_stars_repo_path": "Q1_NS_Coordination/Doorspread functie 2004-2020.new.r", "max_stars_repo_name": "ices-eg/wg_IBTSWG", "max_stars_repo_head_hexsha": "536549c5a4ff4db7d1d91040e0549fd6b1c26a21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Q1_NS_Coordination/Doorspread functie 2004-2020.new.r", "max_issues_repo_name": "ices-eg/wg_IBTSWG", "max_issues_repo_head_hexsha": "536549c5a4ff4db7d1d91040e0549fd6b1c26a21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Q1_NS_Coordination/Doorspread functie 2004-2020.new.r", "max_forks_repo_name": "ices-eg/wg_IBTSWG", "max_forks_repo_head_hexsha": "536549c5a4ff4db7d1d91040e0549fd6b1c26a21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-13T09:48:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-13T09:48:30.000Z", "avg_line_length": 30.1490384615, "max_line_length": 136, "alphanum_fraction": 0.675968745, "num_tokens": 2652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7035429633027585}} {"text": "#'@title calcHMThrustFactor\n#'\n#'@description Calculate thrust deduction factor (\\code{thrustFactor})\n#'(dimensionless) from the Holtrop & Mennen method.\n#'\n#'@param lwl Waterline length (vector of numericals, m) (see \\code{\\link{calclwl}})\n#'@param breadth Moulded breadth (vector of numericals, m)\n#'@param maxDraft Maximum summer load line draft (vector of numericals, m)\n#'@param maxDisplacement Maximum ship displacement (vector of numericals, m^3)\n#'@param nProp Number of propellers (vector of numericals, see \n#' \\code{\\link{calcPropNum}})\n#'@param Cp Prismatic coefficient (vector of numericals, dimensionless) \n#' (see \\code{\\link{calcCp}})\n#'@param propDiam Propeller diameter (vector of numericals, m) (see \n#' \\code{\\link{calcPropDia}})\n#'@param Cbw Waterline block coefficient (vector of numericals, dimensionless) (see\n#' \\code{\\link{calcCbw}})\n#'@param Cstern Afterbody form coefficient: \\itemize{\\item V-shaped Hull = -10\n#' \\item U-Shaped Hull = 10\n#' \\item Normal Hull = 0 (default)}\n#' Can supply either a vector of numericals, a single number, or rely on the default\n#'@param lcb Longitudinal position of center of buoyancy (vector of numericals, see \n#' \\code{\\link{calclcb}})\n#'@param seawaterDensity Sea water density. Default = 1.025 (g/cm^3). Can supply\n#' either a vector of numericals, a single number, or rely on the default\n#'\n#'@details\n#'Thrust deduction factor is a component of hull efficiency as well as a\n#'component of propeller efficiency. It describes the increase in resistance on\n#'the hull from water getting sucked back towards the propeller.\n#'\n#'Note: In \"A Statistical Re-Analysis of Resistance and Propulsion Data\", the\n#'authors re-analyze with the inclusion of Series 64 hull forms for a total of\n#'334 models included in the analysis. They suggest an update of the single\n#'screw thrust equation but that the original equations should be used\n#'for twin screw ships.\n#'\n#'Additionally, we are assuming conventional stern for all single screw ships.\n#'Holtrop & Mennen also include an estimation for thrust factor for single screw\n#'ships with open stern for fast sailing ships, but that is not included here.\n#'\n#'@return \\code{thrustFactor} (vector of numericals, dimensionless)\n#'\n#'@references\n#'Holtrop, J. and Mennen, G. G. J. 1982. \"An approximate power prediction\n#'method.\" International Shipbuilding Progress 29.\n#'\n#'Holtrop, J. and Mennen, G. G. J. 1984. \"A Statistical Re-Analysis of Resistance\n#'and Propulsion Data'.\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calclwl}}\n#'\\item \\code{\\link{calcPropNum}}\n#'\\item \\code{\\link{calcCp}}\n#'\\item \\code{\\link{calcPropDia}}\n#'\\item \\code{\\link{calcCbw}}\n#'\\item \\code{\\link{calclcb}}}\n#'\n#'@family Holtrop-Mennen Calculations\n#'\n#'@examples\n#' calcHMThrustFactor(c(32.25,32.20),c(218.75,209.25),c(13.57,11.49),c(80097,52382.04),\n#' c(1,1),c(0.81,0.67),c(6.7,7),c(0.81,0.65))\n#' calcHMThrustFactor(32.25,218.75,13.57,80097,\n#' 1,0.81,6.7,0.81)\n#'\n#'@export\n\ncalcHMThrustFactor<- function(breadth,lwl,maxDraft,maxDisplacement,nProp,Cp,\n propDiam,Cbw,Cstern=0,lcb=0,seawaterDensity=1.025){\n\n #================\n c10<- ifelse(lwl/breadth<5.2,#case 1\n 0.25-(0.003328402/((breadth/lwl)-0.134615385))\n ,#case 2\n breadth/lwl\n )\n #================\n\n thrustFactor<- ifelse(nProp==1,#begin single screw estimation ([2] method)\n 0.25014*((breadth/lwl)^0.28956)*\n ((sqrt(breadth*maxDraft)/maxDisplacement)^0.2624)/\n ((1-Cp+0.0225*lcb)^0.01762)+0.0015*Cstern\n\n #end single screw estimation\n ,#begin twin screw estimation ([1] method)\n 0.325*Cbw-0.1885*propDiam/sqrt(breadth*maxDraft)\n\n )#end twin screw estimation\n\n\n return(thrustFactor)\n}\n\n", "meta": {"hexsha": "7fbf59c1fd33aa55fef2565561952dff4a2d68d7", "size": 3756, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcHMThrustFactor.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipPowerModel/R/calcHMThrustFactor.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipPowerModel/R/calcHMThrustFactor.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 39.5368421053, "max_line_length": 87, "alphanum_fraction": 0.6999467519, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.7033923337353052}} {"text": "#edf plot\n# use beta distribution as an example\npar(mfrow=c(2,2))\na <- 3\nb <- 1.5\nn <- 30\nx <- seq(0, 1, length=100)\nf <- dbeta(x, a, b)\nplot(x, f, type=\"l\", main=\"pdf\")\nF <- pbeta(x, a, b)\nplot(x, F, type=\"l\", main=\"CDF\")\nX <- rbeta(n,a,b)\nhist(X, main=paste(n,\"samples\"), xlim=c(0,1))\nrug(X)\neF <- ecdf(X)\nplot(eF, main=\"EDF\", verticals=TRUE, xlim=c(0,1))\npar(mfrow=c(1,1))\n\n#bootstrap resample of martin\nmartin <- c(0.13,-0.01,-0.01,0.42,-0.02,0.01,0.09,0.03,0.04,0.06,0.12,0.03)\nnreps <- 1000\nhow.often <- matrix(NA, nrow=nreps, ncol=length(martin))\nfor(i in 1:nreps) how.often[i,] <- sample(martin,length(martin),replace=TRUE)\ntable(how.often)\n\nboot.martin <- function(data, b, alpha, type=\"nonp\") {\n# Purpose: compute 95% CI endpoints for dataset\n# Input: dataset, number of replicates, type in (\"nonp\", \"par-norm\", \"par-t\")\n# output: histogram with CI endpoints\n boot <- matrix(NA, nrow=b+1, ncol=length(data))\n m <- mean(martin)\n sd <- sd(martin)\n title <- paste(b, type, \"bootstraps\", sep=' ')\n if (type == \"nonp\") {\n for(i in 1:b) {boot[i,] <- sample(data,length(data),replace=TRUE) }\n } else {\n if (type==\"par-norm\") {\n for(i in 1:b) {boot[i,] <- rnorm(length(data),m,sd) }\n } else {\n if (type==\"par-t\") {\n for(i in 1:b) {boot[i,] <- (rt(length(martin),length(martin)-1)*sd)+m }\n } else {\n stop(\"Bootstrap type !in 'nonp', 'par-norm', 'par-t\")\n }}}\n \n n.elements <- b+1\n boot[n.elements, ] <- data\n mean.boot <- apply(boot,1,mean) # rowMeans would work equally well\n hist(mean.boot, main=title, freq=FALSE)\n m <- mean.boot[1:b]\n x <- order(m)\n lower.quantile <- floor(alpha/2 * n.elements)\n upper.quantile <- ceiling((1-alpha/2) * n.elements)\n endpoints <- c(m[x[lower.quantile]], m[x[upper.quantile]])\n abline(v=endpoints[1], lty=2)\n abline(v=endpoints[2], lty=2)\n return(endpoints)\n}\n\nboot.martin(martin, b=99, alpha=0.05)\nboot.martin(martin, b=999, alpha=0.05, 'par-norm')\nboot.martin(martin, b=999, alpha=0.05, 'par-t')\nboot.martin(martin, b=999, alpha=0.05, 'para-norm')\n\n", "meta": {"hexsha": "a542af06f728eb0cb8333e6fe4f6c9213f47b5e1", "size": 2056, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Lecture 7/martinbootstrap.r", "max_stars_repo_name": "yc59/2018", "max_stars_repo_head_hexsha": "4c74a67a4d0dadecc4213dd57289120b31806aa6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/Lecture 7/martinbootstrap.r", "max_issues_repo_name": "yc59/2018", "max_issues_repo_head_hexsha": "4c74a67a4d0dadecc4213dd57289120b31806aa6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Lecture 7/martinbootstrap.r", "max_forks_repo_name": "yc59/2018", "max_forks_repo_head_hexsha": "4c74a67a4d0dadecc4213dd57289120b31806aa6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6307692308, "max_line_length": 78, "alphanum_fraction": 0.6123540856, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7033779435437263}} {"text": "#media poblacional entre 2 muestras independientes\r\n\r\n#mtcars es un built in dataframe mpg es el gas milage de los autos en 1974\r\n#mt$am es el tipo de transmisi??n de los autos\r\n\r\n'''\r\nAssuming that the data in mtcars follows the normal distribution, \r\nfind the 95% confidence interval estimate of the difference between\r\nthe mean gas mileage of manual and automatic transmissions.\r\n'''\r\n\r\n#autos con transmision automatica\r\nL = mtcars$am == 0\r\nmpg.auto = mtcars[L,]$mpg\r\n\r\n#autos con transmision manual\r\n\r\nmpg.manual = mtcars[!L,]$mpg\r\n\r\nt.test(mpg.auto,mpg.manual)\r\n\r\n\r\n#otra forma\r\n\r\nt.test(mpg ~ am, data=mtcars)\r\n", "meta": {"hexsha": "b871d760067753de6db787dd9d6a008547c60c86", "size": 618, "ext": "r", "lang": "R", "max_stars_repo_path": "Parcial/3. Inferencia entre poblaciones/PopulationMeanTwoIndependentSamples.r", "max_stars_repo_name": "jchudb93/Exp-Numerica", "max_stars_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Parcial/3. Inferencia entre poblaciones/PopulationMeanTwoIndependentSamples.r", "max_issues_repo_name": "jchudb93/Exp-Numerica", "max_issues_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Parcial/3. Inferencia entre poblaciones/PopulationMeanTwoIndependentSamples.r", "max_forks_repo_name": "jchudb93/Exp-Numerica", "max_forks_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7692307692, "max_line_length": 75, "alphanum_fraction": 0.7249190939, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7031847346748976}} {"text": "library(GA)\n\np <- c(15, 100, 90, 60, 40, 15, 10, 1, 1, 2, 3, 4) # wartości przedmiotów\nw <- c(2, 20, 20, 30, 40, 30, 60, 10, 10, 40, 30, 50) # wagi\ncap <- 113 # pojemność plecaka\n\nknapsackFitness <- function(knapsack) {\n value <- sum(knapsack * p)\n weight <- sum(knapsack * w)\n\n # Funkcja kary, gdy nie używamy monitora\n if (weight > cap) {\n # value <- 0 # prosty element kary\n # value <- value * (cap/weight/1.1)\n value <- value - weight + cap\n }\n\n value\n}\n\nknapsackMonitor <- function(obj, digits = getOption(\"digits\"), ...)\n{\n for(i in 1:nrow(obj@population)) {\n weight <- sum(obj@population[i,] * w)\n while (weight > cap) {\n removeThing <- sample.int(length(p) - 1, 1) + 1\n obj@population[i,removeThing] <- 0\n weight <- sum(obj@population[i,] * w)\n }\n }\n \n fitness <- na.exclude(obj@fitness)\n sumryStat <- c(mean(fitness), max(fitness))\n sumryStat <- format(sumryStat, digits = digits)\n cat(paste(\"GA | iter =\", obj@iter, \"| Mean =\", sumryStat[1], \n \"| Best =\", sumryStat[2]))\n cat(\"\\n\")\n flush.console()\n}\n\nset.seed(123)\nGA <- ga(\n type = \"binary\",\n fitness = knapsackFitness,\n nBits = length(p),\n popSize = 50,\n maxiter = 1000,\n run = 100,\n seed = 123,\n monitor = knapsackMonitor\n)\n\nsummary(GA)\nplot(GA)\n", "meta": {"hexsha": "60b059954246d51b31992070568d4c2a1960cbf4", "size": 1330, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ga/ga_knapsack_problem.r", "max_stars_repo_name": "reyzeer/algorytmy-genetyczne", "max_stars_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ga/ga_knapsack_problem.r", "max_issues_repo_name": "reyzeer/algorytmy-genetyczne", "max_issues_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ga/ga_knapsack_problem.r", "max_forks_repo_name": "reyzeer/algorytmy-genetyczne", "max_forks_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1818181818, "max_line_length": 78, "alphanum_fraction": 0.5661654135, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7027889717543556}} {"text": "dev.off()\n\nx = seq(1.8, 5.2, 0.1)\n\nf1 <- function(x) {\n x^3 - 10*x^2 + 31*x - 30\n}\nf2 <- function(x) {\n 3*x^2 - 20*x + 31 \n}\n\npar(mfrow=c(2,1))\nplot(x, f1(x), type='l')\nabline(h=0)\npoints(2.45, f1(2.45))\npoints(4.22, f1(4.22))\n\nplot(x, f2(x), type='l', yaxs=\"r\")\nabline(h=0)\npoints(2.45, f2(2.45))\npoints(4.22, f2(4.22))", "meta": {"hexsha": "e38b695a7090b68e0aa3ce41629847f07a3ffe91", "size": 322, "ext": "r", "lang": "R", "max_stars_repo_path": "resolucao/r/pontos_criticos.r", "max_stars_repo_name": "rafaelbes/numericalAnalysis", "max_stars_repo_head_hexsha": "31f2b9cd5fb62cee9a649ac0257024de757eede4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "resolucao/r/pontos_criticos.r", "max_issues_repo_name": "rafaelbes/numericalAnalysis", "max_issues_repo_head_hexsha": "31f2b9cd5fb62cee9a649ac0257024de757eede4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resolucao/r/pontos_criticos.r", "max_forks_repo_name": "rafaelbes/numericalAnalysis", "max_forks_repo_head_hexsha": "31f2b9cd5fb62cee9a649ac0257024de757eede4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-15T00:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T14:52:19.000Z", "avg_line_length": 15.3333333333, "max_line_length": 34, "alphanum_fraction": 0.5310559006, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7026857499810591}} {"text": "# Abundant, deficient and perfect number classifications. 12/10/16 aev\nrequire(numbers);\npropdivcls <- function(n) {\n V <- sapply(1:n, Sigma, proper = TRUE);\n c1 <- c2 <- c3 <- 0;\n for(i in 1:n){\n if(V[i] 0\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "36490693e1af527b621c3b128c06a39be3d09959", "size": 269, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-cayleyhamilton01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-cayleyhamilton01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-cayleyhamilton01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9333333333, "max_line_length": 43, "alphanum_fraction": 0.5836431227, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.7026769083433946}} {"text": "bayes <- function(prior, likelihood, data)\n{\n\tposterior <- matrix(0, nrow=length(data), ncol=length(prior))\n\tdimnames(posterior) <- list(data, names(prior))\n\n\tinitial_prior = prior\n\tfor(i in 1:length(data))\n\t{\n\t\tposterior[i, ] <- \n\t\t\tprior*likelihood[ , data[i]]/\n\t\t\tsum(prior * likelihood[ , data[i]])\n\n\t\tprior <- posterior[i , ]\n\t}\n\n\treturn(rbind(initial_prior,posterior))\n}\n", "meta": {"hexsha": "b8dbd35f21c934806afb6f80499feafb591d9de4", "size": 377, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 01/bayes.r", "max_stars_repo_name": "PacktPublishing/Learning-Probabilistic-Graphical-Models-in-R", "max_stars_repo_head_hexsha": "dc72f58a4a9e7990d889dca23d90ccc71b681f14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2016-05-29T14:29:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:12:33.000Z", "max_issues_repo_path": "Chapter 01/bayes.r", "max_issues_repo_name": "PacktPublishing/Learning-Probabilistic-Graphical-Models-in-R", "max_issues_repo_head_hexsha": "dc72f58a4a9e7990d889dca23d90ccc71b681f14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 01/bayes.r", "max_forks_repo_name": "PacktPublishing/Learning-Probabilistic-Graphical-Models-in-R", "max_forks_repo_head_hexsha": "dc72f58a4a9e7990d889dca23d90ccc71b681f14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-05-25T10:30:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T06:08:58.000Z", "avg_line_length": 20.9444444444, "max_line_length": 62, "alphanum_fraction": 0.6578249337, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7025924312337036}} {"text": "# n = 20;\n# alpha = 0.01;\n# x = rnorm(n, mean=10.5, sd=1.3);\n# \n# # 1.1\n# hypothesisTest = t.test(x, mu=10, conf.level = 1-alpha);\n# print(hypothesisTest);\n# \n# #1.1.a\n# avg = mean(x);\n# stDev = sd(x);\n# \n# critVal = qt(1-alpha/2, n-1, lower.tail = TRUE);\n# lowBound = avg - (stDev * critVal)/sqrt(n);\n# upBound = avg + (stDev * critVal)/sqrt(n);\n# print((stDev * critVal)/sqrt(n))\n# \n# #!.1.b\n# #TODO if\n# print(lowBound);\n# print(upBound);\n# \n# #1.1.c TODO if\n# tVal = sqrt(n)*(avg-10)/stDev;\n# critVal = qt(1-alpha/2, n-1, lower.tail = TRUE);\n# \n# lowBound = pt(tVal, n-1, lower.tail = FALSE);\n# upBound = pt(tVal, n-1, lower.tail = TRUE);\n# pVal = 2*min(lowBound, upBound);\n# print(2*lowBound);\n# print(2*upBound);\n# \n# #1.2\n# #vybereme jednostranny t-test a cele to zopakujeme\n# #Expiricky vime, ze avg = 10.5 a u = 10, proto je vyhodnejsi alternativa greater, protoze s danou pravdepodobnosti jsme schopni rict, ze hodnota je vetsi nez deset. Diky vlastnostem generovanych dat takto casteji zavrhneme H0 a pouzijeme Halph\n# \n# n = 20;\n# alpha = 0.01\n# x = rnorm(n, mean=10, sd=1)\n# error = rnorm(n, mean=0.5, sd=0.8306624)\n# y = x + error\n# \n# t.test(x, y=y, paired = TRUE, alternative = \"less\", conf.level = 1-alpha)\n# \n\n#2.1\n# n = 20;\n# alpha = 0.01\n# x = rnorm(n, mean=10, sd=1)\n# error = rnorm(n, mean=0.5, sd=0.8306624)\n# y = x + error\n# \n# t.test(x, y=y, paired = TRUE, alternative = \"less\", conf.level = 1-alpha)\n \n\n# n = 20;\n# alpha = 0.01\n# x = rnorm(n, mean=10, sd=1)\n# error = rnorm(n, mean=0.5, sd=0.8306624)\n# y = x + error\n# \n# res = t.test(x, y=y, paired = TRUE, alternative = \"less\", conf.level = 1-alpha)\n# print(res)\n# if(abs(res$statistic) > qt(1-alpha, n-1, lower.tail = TRUE)) {\n# print('Reject null hypothesis!')\n# }\n\n\n# 2.1.b\n# res = t.test(x-y, alternative = \"less\", conf.level = 1-alpha)\n# print(res)\n\n#2.2\n# n1 = 20;\n# n2 = 25;\n# alpha = 0.01\n# x=rnorm(n1, mean=10, sd=1.3)\n# y=rnorm(n2, mean=11.25, sd=1.3)\n# res = t.test(x, y=y, paired = FALSE, var.equal = TRUE, alternative = \"less\", conf.level = 1-alpha)\n# print(res)\n# if(abs(res$statistic) > qt(1-alpha, n1+n2-2, lower.tail = TRUE)) {\n# print('Reject null hypothesis!')\n# }\n\n\nn1 = 20;\nn2 = 25;\nalpha = 0.01\nx=rnorm(n1, mean=10, sd=1.3)\ny=rnorm(n2, mean=11.28, sd=1.2)\nres = t.test(x, y=y, paired = FALSE, var.equal = FALSE, alternative = \"less\", conf.level = 1-alpha)\nprint(res)\nif(abs(res$statistic) > qt(1-alpha, n1+n2-2, lower.tail = TRUE)) {\n print('Reject null hypothesis!')\n}\n\n\n# \n# #2.2\n# n1 = 20;\n# n2 = 25;\n# alpha = 0.01\n# x=rnorm(n1, mean=10, sd=1.3)\n# y=rnorm(n2, mean=11.25, sd=1.3)\n# \n# res = t.test(x, y=y, paired = FALSE, var.equal = TRUE, alternative = \"less\", conf.level = 1-alpha)\n# print(res);\n\ndf = n1 + n2 - 2;\nsdiff = sqrt(var(x)/n1+var(y)/n2);\ntVal = (mean(x)-mean(y))/(sdiff);\nprint(tVal)\nif(abs(tVal) > qt(1-alpha, df, lower.tail = TRUE)) {\n print('Reject null hypothesis!')\n}\n\n# critVal = qt(1-alpha, df, lower.tail = TRUE);\n#print(pt(tVal, df, lower.tail = TRUE))\n#print(qt(res$p.value, df));\n\n#2.3\n# n1 = 20;\n# n2 = 25;\n# alpha = 0.01\n# x=rnorm(n1, mean=10, sd=1.3)\n# y=rnorm(n2, mean=11.28, sd=1.2)\n\n# t.test(x, y=y, paired = FALSE, var.equal = FALSE, conf.level = 1-alpha)\n#zodpadkovat vsechny kroky\n#bude nutne prepsat vypocet bodu 2.2 podle vzorce pro rozdilne rozptyly\n#... kdyz se muze clovek rozptylovat, muze se i ptylovat?\n\n#3.1.a,b,c\n# sequenceLength = 4000000;\n# x = runif(sequenceLength, 0, 100)\n# print(system.time(sort(x)))\n\n#pouzijeme hypotezu X1 < X2 ..tj, je algoritmus X1 v prumeru rychlejsi?\n#\n", "meta": {"hexsha": "f6e3ba85bf43f7138bd0c3221a2cc76297daa455", "size": 3536, "ext": "r", "lang": "R", "max_stars_repo_path": "task_2/task2.r", "max_stars_repo_name": "holoubekm/MI-SPI", "max_stars_repo_head_hexsha": "22cae9226de2a5c08fb769b725cefa06dd4064fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task_2/task2.r", "max_issues_repo_name": "holoubekm/MI-SPI", "max_issues_repo_head_hexsha": "22cae9226de2a5c08fb769b725cefa06dd4064fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task_2/task2.r", "max_forks_repo_name": "holoubekm/MI-SPI", "max_forks_repo_head_hexsha": "22cae9226de2a5c08fb769b725cefa06dd4064fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2571428571, "max_line_length": 245, "alphanum_fraction": 0.6134049774, "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7023995941493886}} {"text": "#равномерно разпределение - равномерно разпределени случайни величини в интервал [a,b]\n#функцията unif() с префикси d,p,q,r за съответно плътност, разпределние, квантил и случайно разпределение(симулиране)\n\n#100 случайни равномерно разпределени величини в интервала [0,2]\nx = runif(n = 100, min = 0, max = 2)\nhist(x, probability=TRUE, col=gray(.9), main=\"uniform on [0,2]\") #хистограма на разпределението\ncurve(dunif(x,0,2),add=T) #теоретична плътност -> dunif(x,0,2) всяка от случайните величини с каква вероятност да се случи е \n\n#генериране на извадка -> измежду числата x (от 1 до х, ако х е число, а не вектор), се взимат по случаен начин size числа\nsample(x = 1:10, size = 10) \nsample(x = 10, size = 10, replace = TRUE) #може да има повторения\n\n\n#геометрично разпределение - частен случай на отрицателно биномното, кoгато искаме да имаме x неуспеха преди първия успех с вероятност за успех prob\n#функцията geom() с префикси d,p,q,r за съответно плътност, разпределние, квантил и случайно разпределение(симулиране)\nY=0:10\nplot(Y, dgeom(x = Y, prob = 0.6), type=\"h\", ylim=c(0,1), main=\"Geometric distribution for p=0.6\", ylab=\"P(Y=Y)\", xlab=\"Y=Number of failures before first success\")\n\n#екцпоненциално разпределение - непрекъсната случайна величнина\n#функцията exp() с префикси d,p,q,r за съответно плътност, разпределние, квантил и случайно разпределение(симулиране)\nmu = 2500\nx = rexp(n = 100, rate = 1/mu) #100 случайни експоненциално разпределени величини с вероятност 1/mu\nhist(x,probability=TRUE,col=gray(.9),main=\"exponential mean=2500\") #хистограма\ncurve(dexp(x = x, rate = 1/2500),add=T) #теоретична плътност\n\n#нормално разпределение - очакване(средно) mu и дисперсия sigma (стандартно отклонение sigma)\n#функцията norm() с префикси d,p,q,r за съответно плътност, разпределние, квантил и случайно разпределение(симулиране)\n#на финкцията се подава очакване (mu) и стандартно отклонение (sigma)\nx=c(1:200)\nplot(dnorm(x, 100,10), ylim=c(0,0.1))\nlines(dnorm(x, 100,5), col=\"red\")\nlines(dnorm(x, 130,10), col=\"blue\")\n\n#стандартно нормално разпределение - нормално разпределение с очакване 0 и дисперсия 1\n#по подразбиране в norm(x, mu = 0, sd = 1)\n#за нормализиране се използва формулата y = (x - mu)/sigma \n#където х е нормално разпределена случайна величина с очакване mu и дисперсия sigma^2,\n#а у е стандарна нормално разпределене случайна величина\n\n\n#-----------------------------------------------------\n\n#01\n#геометрично разпределение с вероятност 1/2, 1/3, 2/3\ny=0:10 #случайни числа(за онагледяване)\nplot(x = y, dgeom(x = y, prob = 1/2), ylim=c(0,0.8), ylab = \"Probability\", xlab = \"Number of fails before the first success\")\nlines(x = y, dgeom(x = y, prob = 1/3), col=\"red\")\nlines(x = y, dgeom(x = y, prob = 2/3), col=\"blue\")\n\n#02\n#експоненциално разпределение с mu =5\nk.30 = dexp(x = 5, rate = 1/5)\nplot(x = 1:30, y = dexp(x = 1:30, rate = 1/5), main = \"Exponentila with mu = 5\", ylab = \"P(X = x)\")\n\n#03\nx = rnorm(n = 50, mean = 5, sd = 5) #N(5,5) означава дисперсия 5 = sigma^2 => стандартно отклонение sigma = sqrt(5), но в случая няма значение :) \nx.norm = (x - 5)/5\nhist(x.norm, probability = TRUE)\nx.standart = rnorm(50)\nhist(x.standart, probability = TRUE)\n\n#04\n#z стандартно нормално разоределена случайна величина\npnorm(q = 0.92 , lower.tail = FALSE) #P(Z > 0.92)\npnorm(q = -0.5, lower.tail = FALSE) #P(Z > -0.5) = P(Z < 0.5)\n#P(-0.64 < Z < 0.43) = P(Z < 0.43) - P(Z > -0.64)\npnorm(0.43) - pnorm(-0.64, lower.tail = FALSE)\n\n#05\n#x нормално разпределено с mu = 3 и sigma^2 = 4\npnorm(q = 6.2, mean = 3, sd = 2)\n\n#06\npnorm(q = 3100, mean = 3500, sd = 500)\npnorm(-4/5) #нормирано z = (3100 - 3500)/500 = -4/5 е стандартно нормално разпределено N(0,1)\n\n#07\n#X = N(80, 10^2), Y=N(78, 13^2) => X-Y = N(80-78, 10^2 + 13^3) = N(2,269)\npnorm(0,2,sqrt(269),lower.tail = FALSE) #искаме Х > Y => X - Y > 0\n\n", "meta": {"hexsha": "fdd920e3509c8f3b172dea31f4fc2a2f21804c2a", "size": 3821, "ext": "r", "lang": "R", "max_stars_repo_path": "week7.r", "max_stars_repo_name": "StelaN/Statistics-R", "max_stars_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-17T10:22:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-17T10:22:32.000Z", "max_issues_repo_path": "week7.r", "max_issues_repo_name": "StelaN/Statistics-R", "max_issues_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week7.r", "max_forks_repo_name": "StelaN/Statistics-R", "max_forks_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-06T13:38:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-06T13:38:34.000Z", "avg_line_length": 47.1728395062, "max_line_length": 162, "alphanum_fraction": 0.6883014918, "num_tokens": 1754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.7022898295998665}} {"text": "#'@title Compute and return the degree measure of the angle of the slope of the time series.\n#'\n#'@description The time series is fitted with a linear model and the degree measure of the angle of the slope is returned.\n#'\n#'@usage angleMagnitude <- getSlopeAngleSize(tsData)\n#'\n#'@param tsData A time series object.\n#'\n#'@return A numeric value representing the degree measure of the angle of the slope of the time series.\n#'\n#'@export\n\ngetSlopeAngleSize <- function(tsData)\n{\n\n tsObj <- tsData\n\ttsObj.lm <- lm(tsObj ~ time(tsObj))\n\n\tdegreeAngleMeasure <- as.numeric(atan(tsObj.lm$coefficients[2])*(180/pi))\n\t\n\treturn (degreeAngleMeasure)\n\n}\n", "meta": {"hexsha": "9dc62cb520dcff825761057ebbf9ceeb66940233", "size": 649, "ext": "r", "lang": "R", "max_stars_repo_path": "R/getSlopeAngleSize.r", "max_stars_repo_name": "OHDSI/Castor", "max_stars_repo_head_hexsha": "a64faf53509b50bfedf9057f042355fe2e17974b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-11T18:51:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T16:13:55.000Z", "max_issues_repo_path": "R/getSlopeAngleSize.r", "max_issues_repo_name": "OHDSI/Castor", "max_issues_repo_head_hexsha": "a64faf53509b50bfedf9057f042355fe2e17974b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-23T18:35:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T16:41:40.000Z", "max_forks_repo_path": "R/getSlopeAngleSize.r", "max_forks_repo_name": "OHDSI/Castor", "max_forks_repo_head_hexsha": "a64faf53509b50bfedf9057f042355fe2e17974b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0416666667, "max_line_length": 122, "alphanum_fraction": 0.7272727273, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.919642531177793, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7021321408282171}} {"text": "#' Scale variable to have range between 0 and 1\n#'\n#' @param x Vector\n#'\n#' @export\n#' @return Vector\nrange01 <- function(x)\n{\n\t(x-min(x))/(max(x)-min(x))\n}\n\n#' Translate risk from liability to probability scale\n#'\n#' @param gx score on liability scale \n#' @param h2x Disease heritability on liability scale\n#' @param prev Prevalence\n#'\n#' @export\n#' @return Vector of disease probabilities\ngx_to_gp <- function(gx, h2x, prev)\n{\n\tx_prime <- qnorm(prev, 0, 1)\n\tp <- pnorm(x_prime, mean=gx, sd = sqrt(1 - h2x), lower.tail=FALSE)\n\treturn(p)\n}\n\n#' Plot liability vs probability disease risk\n#'\n#' @param x Disease risk on liability scale\n#' @param o Disease risk on probability scale\n#' @param xlab default=\"Values (low to high)\"\n#' @param ylab default=\"\"\n#' @param title default=\"\"\n#' @param xname Name of liability. Default=\"GRS\"\n#' @param oname Name of disease. Default=\"Disease\"\n#'\n#' @export\n#' @return ggplot\nrisk_cross_plot <- function(x, o, xlab=\"Values (low to high)\", ylab=\"\", title=\"\", xname=\"GRS\", oname=\"Disease\")\n{\n\td <- dplyr::tibble(\n\t\tvalue = c(range01(o), range01(x)),\n\t\tkey = c(rep(oname, length(o)), rep(xname, length(x))),\n\t\tgr = rep(1:length(x), times=2)\n\t)\n\td$key <- factor(d$key, levels=c(xname, oname))\n\tggplot2::ggplot(d, ggplot2::aes(x=value, y=key)) +\n\tggplot2::geom_line(ggplot2::aes(group=gr), alpha=0.1) +\n\tggplot2::geom_point(ggplot2::aes(colour=key)) +\n\tggplot2::labs(x=xlab,y=ylab,title=title) +\n\tggplot2::scale_colour_discrete(guide=FALSE) +\n\tggplot2::theme(axis.text.x=ggplot2::element_blank(),axis.ticks.x=ggplot2::element_blank())\n}\n\n#' Make simulation to compare disease and liability scales\n#'\n#' Compares the liability and probability of disease under two scenarios - where all SNPs are known, and where only some SNPs are known\n#'\n#' @param G Matrix of genotypes\n#' @param eff SNP effects on liability scale\n#' @param prevalence Disease prevalence\n#' @param prop_discovered Proportion of SNPs discovered\n#'\n#' @export\n#' @return Data frame\nrisk_simulation <- function(G, eff, prevalence, prop_discovered)\n{\n\tnid <- nrow(G)\n\tnsnp <- ncol(G)\n\tgx_true <- scale(G) %*% eff\n\th2x <- var(gx_true)\n\tprob_disease <- gx_to_gp(gx_true, h2x, 1-prevalence)\n\tdisease <- rbinom(nid, 1, prob_disease)\n\teff_pred <- eff\n\teff_pred[sample(1:nsnp, nsnp * (1-prop_discovered))] <- 0\n\tgx_pred <- as.numeric(G %*% eff_pred / sqrt(nsnp))\n\tdat <- dplyr::tibble(gx_true=as.numeric(gx_true), gx_pred=gx_pred, prob_disease=as.numeric(prob_disease), disease=disease)\n\treturn(dat)\n}\n\n", "meta": {"hexsha": "8cf2efed4e02241921b5480bc1dc235a8d86ac59", "size": 2491, "ext": "r", "lang": "R", "max_stars_repo_path": "R/risk.r", "max_stars_repo_name": "explodecomputer/simulateGP", "max_stars_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-05T16:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T16:58:46.000Z", "max_issues_repo_path": "R/risk.r", "max_issues_repo_name": "aeaswar81/simulateGP", "max_issues_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T16:14:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T16:14:15.000Z", "max_forks_repo_path": "R/risk.r", "max_forks_repo_name": "aeaswar81/simulateGP", "max_forks_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-10T19:27:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T16:59:02.000Z", "avg_line_length": 30.7530864198, "max_line_length": 135, "alphanum_fraction": 0.6957045363, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7021321341975814}} {"text": "#Adjacency matrix1 i/p based on given undirected graph\nadj_mat1 <- matrix(c(0,1,0,0,3,0,1,2,2,1,0,0,0,2,0\n ,1,1,1,0,1,1,0,0,0,3,0,1,0\n ,0,0,0,0,1,0,0,2),byrow = T,6,6)\nshow(adj_mat1)\ndegree <- rowSums(adj_mat1)\nvertex <- seq(1,6)\nshow(data.frame(vertex,degree))\n\n#Adjacency matrix2 i/p based on given directed graph\nadj_mat2 <- matrix(c(0,0,0,1,0,0,0,0,1,0,0,0,1,0,0\n ,0,1,0,0,0,0,0,0,1,0,0,0,\n 1,0,1,0,1,0,0,0,0),byrow = T,6,6)\nshow(adj_mat2)\ndegree_in <- rowSums(adj_mat2)\ndegree_out <- colSums(adj_mat2)\nshow(data.frame(vertex,degree_in,degree_out))\n", "meta": {"hexsha": "2c4ab9d4c28bac7fc1019c99d81bce7e1bc4ed6f", "size": 631, "ext": "r", "lang": "R", "max_stars_repo_path": "CN_comp_assign1/1.r", "max_stars_repo_name": "ambirpatel/Complex-Networks-Codes", "max_stars_repo_head_hexsha": "6b3e347d0ddf40790f2378fa164cb27df08423a3", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CN_comp_assign1/1.r", "max_issues_repo_name": "ambirpatel/Complex-Networks-Codes", "max_issues_repo_head_hexsha": "6b3e347d0ddf40790f2378fa164cb27df08423a3", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CN_comp_assign1/1.r", "max_forks_repo_name": "ambirpatel/Complex-Networks-Codes", "max_forks_repo_head_hexsha": "6b3e347d0ddf40790f2378fa164cb27df08423a3", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0555555556, "max_line_length": 54, "alphanum_fraction": 0.5927099842, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7020704341427563}} {"text": "# Example : 3 Chapter : 8.3 Page No: 433\n# Markov matrix Application.\nA<-matrix(c(0,0.5,0.5,0.5,0,0.5,0.5,0.5,0),ncol=3)\nu0<-c(8,16,32)\nu1<-A%*%u0\nu2<-A%*%u1\nu3<-A%*%u2\nprint(\"Populations in three groups in subsequent months\")\nprint(u1)\nprint(u2)\nprint(u3)", "meta": {"hexsha": "e66f77d24b02f8a070c1a5a655e0395377f62760", "size": 262, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.3.3/Ex8.3_3.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.3.3/Ex8.3_3.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.3.3/Ex8.3_3.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 23.8181818182, "max_line_length": 57, "alphanum_fraction": 0.641221374, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.702008983418332}} {"text": "#Copyright 2016 Lingjiao Chen, Arun Kumar, Jeffrey Naughton, and Jignesh M. Patel, Version 0.8.\n#All rights reserved.\n#\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\nKmeansClustering <- function(Data,Max_Iter,Center_Number,k_center,nS)\n{\n# k_center is the k centers, and YA is the assignment\n\tAll1 = matrix(1, nS, 1);\n\tAll1_k = matrix(1,1,Center_Number);\n\tAll1_C = t(matrix(1,1,nrow(k_center)));\t\n\tT2 = rowSums(Data^{2}) %*% All1_k;\n\tT22 = Data * 2;\n\tfor( k in 1: Max_Iter )\n\t{\n\t\tDist = T2 - as.matrix(T22 %*% k_center ) + All1 %*% colSums(k_center ^2);\n\t\tYA = (Matrix(Dist == (rowMins((Dist)) %*% All1_k),sparse=TRUE))+0;\n\t\tk_center = as.matrix( ( t(Data) %*% YA ) / ( (All1_C) %*% colSums(YA) ) );\n\t}\n\treturn(list(k_center ,YA));\n}\n", "meta": {"hexsha": "2d25d5b1194e1a09a6f51525fa702d4c445e8e1b", "size": 1227, "ext": "r", "lang": "R", "max_stars_repo_path": "src/MLalgorithms/KmeansClustering.r", "max_stars_repo_name": "lchen001/Morpheus", "max_stars_repo_head_hexsha": "d94e6487dcf32982fb4322a4ed2a8a40c2319f56", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-10-30T18:39:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T16:20:23.000Z", "max_issues_repo_path": "src/MLalgorithms/KmeansClustering.r", "max_issues_repo_name": "lchen001/Morpheus", "max_issues_repo_head_hexsha": "d94e6487dcf32982fb4322a4ed2a8a40c2319f56", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MLalgorithms/KmeansClustering.r", "max_forks_repo_name": "lchen001/Morpheus", "max_forks_repo_head_hexsha": "d94e6487dcf32982fb4322a4ed2a8a40c2319f56", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-09-24T04:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-28T21:25:36.000Z", "avg_line_length": 38.34375, "max_line_length": 95, "alphanum_fraction": 0.7017114914, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7017646599075303}} {"text": "# N-мерни променливи и изследване на връзките между тях\n\n# Какво предсталяват \"n\"-мерните данни?\n# Едномерните данни, това са масиви/листа от обекти (числа, стрингове, дати, друг тип обекти).\n# При двумерните данни имаме колекция от едномерни данни. Тоест, представянето е във формата на\n# матрици, data frame-ове или друга подобна структура, при която най-често по редове са представени\n# примерите/елементите, а по колони техните признаци (променливите).\n\n# Пример за многомерни данни е\ndata(\"mtcars\")\nhead(mtcars)\nmtcars\n\n# Нека да изследваме обема на двигателя за въпроснтие коли. Първо ще построим хистограма\nhist(\n x = mtcars$disp,\n col = \"red\",\n xlab = \"Displacement (u.in.)\",\n main = \"Histogram\"\n)\n\nsummary(mtcars$disp)\nsd(mtcars$disp)\n\nabline(v = mean(mtcars$disp), lwd = 2, lty = 4)\nabline(v = median(mtcars$disp), lwd = 2, lty = 4, col = \"blue\")\n\n# От хистограмата се вижда, че имаме два пика.\n# Тоест, разпределението на променливата е\n# бимодално. Черната вертикалана прекъсната линия показва къде се намира средната стойност,\n# а синята прекъсната - медината. И в двата случая, малко трудно можем да приемем, че това е\n# очакването на разпределението.\n\n# Нека сега да проверим, какво би станало, ако групираме данните по броя на цилиндрите\ndisp_cyl4 <- mtcars$disp[which(mtcars$cyl == 4)]\ndisp_cyl6 <- mtcars$disp[which(mtcars$cyl == 6)]\ndisp_cyl8 <- mtcars$disp[which(mtcars$cyl == 8)]\n\npar(mfrow = c(2, 2))\nhist(x = disp_cyl4, col = \"red\", xlab = \"4 cylinders\", main = \"Histogram of displacement (u.in.)\")\nhist(x = disp_cyl6, col = \"lightblue\", xlab = \"6 cylinders\", main = \"Histogram of displacement (u.in.)\")\nhist(x = disp_cyl8, col = \"forestgreen\", xlab = \"8 cylinders\", main = \"Histogram of displacement (u.in.)\")\npar(mfrow = c(1, 1))\n\nsummary(disp_cyl4)\nsd(disp_cyl4)\n\nsummary(disp_cyl6)\nsd(disp_cyl6)\n\nsummary(disp_cyl8)\nsd(disp_cyl8)\n\n# За групата на двигетелите, които имат 4 цилиндъра, все още не може да получим добра оценка\n# за очакването, но за другите две групи - можем, защото имаме по един връх.\n\n# Анализирайки зависимостите на една променлива от други променливи, ние успяваме да подобрим\n# оценките на параметрите, които са ни неогходи. По този начин правим прогнозите си по-точни.\n\n################################\n# Изследване на двумерни данни\n\n# 1. Категорийни (обясняващи) VS категорийни (зависими)\n# Връзките между тези променливи най-лесно се виждат с помощта на cross таблици и barplot-ове.\n\n# Пример: Направили сме хипотетично прочуване, което измерва дали студентите, които пушат,\n# учат по-малко.\n\nsmokes <- c(\"Y\", \"N\", \"N\", \"Y\", \"N\", \"Y\", \"Y\", \"Y\", \"N\", \"Y\")\namount <- c(\"0 - 5 hours\", \"5 - 10 hours\", \"5 - 10 hours\", \"more than 10 hours\",\n \"more than 10 hours\", \"0 - 5 hours\", \"5 - 10 hours\", \"0 - 5 hours\",\n \"more than 10 hours\", \"5 - 10 hours\")\ntable(amount, smokes)\n# Данните показват, че пушачите учат по-малко от непушачите. Нека да разгледаме резулатите\n# не като честоти, а като проценти. За целта изпозлвае командата\n\nprop.table(x = table(amount, smokes))\n# Показва ни в коя група, колко процента от данните попадат.\n\nprop.table(x = table(amount, smokes), margin = 1)\n# Параметърът \"margin\" задава как желаем да изчисляваме процентите - по редове или по колони.\n# От данните виждаме, че имаме нарастване в процента на непушещите студентите, спрямо броя на\n# часовете, които отделят за учене.\n\nbarplot(table(smokes, amount))\n# Малко трудно бихме видяли разликите, освен ако не са фрапиращи.\n# В долния код ще се опитаме да нормализираме стойностите като използваме процентните\n# съотношения. При този подход, ясно се вижда превъзходствата на едни признаци в една група,\n# спрямо друга.\nbarplot(prop.table(x = table(smokes, amount), margin = 2))\n\n# Друг подход е описаният по-долу\nbarplot(table(smokes, amount), beside = TRUE, legend.text = T, col = c('green', 'red'))\n# При този подход съще лесно се забелязват разликите в отделните групи. В сегашния barplot\n# сме задали и легенда\n\n# Освен че можем да изведем легенда на графиката (legend.text = TRUE), то можем и да я\n# попълним със стойности, които ни трябват. Попълването е показано в примера по-долу.\nbarplot(\n table(amount, smokes),\n main = \"table(amount, smokes)\",\n beside = TRUE,\n legend.text = c(\"less than 5\", \"5 - 10\", \"more than 10\")\n)\n\n# 2. Категорийни (обясняващи) VS числови (зависими)\n# Когато имаме такава конфигурация при връзките, то най-удачно е да използваме One-way ANOVA\n# и t-test или техните непараемтрични еквиваленти. Тези анализи ще ги учим по-нататък в курса\n# по статистика. Ако искаме да ги изследваме графично, удачно решение е boxplot графиките.\namount <- c(5, 5, 5, 13, 7, 11, 11, 9, 8, 9, 11, 8, 4, 5, 9, 5, 10, 5, 4, 10)\ncategory <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)\ntt <- boxplot(amount ~ category)\n\n# Както се вижда, лесно могат да се сравнят двете категории.\n# - Средната дебела линия във всяки един boxplot е медианата\n# - Страните на правоъгълника са 1 и 3-ти квартил,\n# - Дължината на опашките са минималната и максималните стойности, като са изключени потенциалните outlier-и.\n# Тоест интерпретацията на тази графика е, че стойнсотите на първата група като цяло са\n# по-големи защото и медианата и третия квартил за първата група са по-големи от тези на втората.\n# Отделно, минималната стойност и първия квартил за първата група съвпадат ( = 5), докато минималната\n# стойност на втората група е 4.\n\n# ----------------------------------------------------------------------------------------------------\n# 3. Числови (обясняващи) VS категорийни (зависими)\n# Този случай на връзка е сходен с горния. Затова тук също можем да използваме One-way ANOVA или\n# t-test, непараметричните им екваваленти и boxplot-ове. Също така можем да използваме и\n# логистичната регресия.\n\n# Този тип връзка ще бъде обяснена по-нататък\n\n# ----------------------------------------------------------------------------------------------------\n# 4. Числови (обясняващи) VS числови (зависими)\n# Това е може би групата, за която съществуват най-много похвати за анализи. Променливите от\n# числов тип могат да бъдат превърнати в категорийни и следователно за тях важат горнтие типове\n# анализи. Това, разбира се, би довело до загуба на информация, но в определени случаи е по-подходящо\n# заради по-голямата стабилност на моделите.\n# Похватите, които са характерни за изследването на този тип връзки са най-често корелационен\n# анализ и регресионен анализ, както и dotplot (графично представяне на връзката).\n# Почти винаги изследването на този тип връзка следва последователността dotplot, корелационен\n# анализ и регресионен анализ\n\ndata(\"mtcars\")\nmtcars\n# Да разгледаме пример от данните \"mtcars\". Интересуват ни променливите disp (обем на двигателя)\n# и wt (тегло)\n\nplot(mtcars$disp, mtcars$wt)\n# От графиката се вижда, че съществува положителна линейна връзка. Тоест с нарастване на обема\n# на двигателя, нараства и теглото на автомобила. Следователно, можем да използваме линеен модел,\n# за да моделираме връзката.\n\n# ИНФОРМАЦИЯ, КОЯТО НЯМА ДА Я ИМА НА ИЗПИТА/КОНТРОЛНИТЕ\n# Преди да продължим с корелационния и регресионния анализ, нека да разгледаме друг пример.\n# Този път данните ще бъдат симулирани. И връзката няма да бъде линейна, а кубична.\n\nset.seed(4455)\nx <- runif(1000, -3, 3)\ny <- x^3 - 3 + rnorm(length(x), sd = 2)\nplot(x, y)\nx^3\nx^3 - 3\nrnorm(length(x), sd = 2)\n# Както се вижда от графиката, този тип връзка не прилича на линейна. Но чрез подходяща трансформация,\n# връзката може да се представи като линейна. Например, ако създадем нова променлива\nx3 <- x^3\n# Тогава, новата променлива x3 е в линейна зависимост с променливата y\npar(mfrow = c(1, 2))\nplot(x, y)\nplot(x3, y)\npar(mfrow = c(1, 1))\n\n# Корелационен анализ\n# Корелационният анализ измерва силата на линейна връзка между две променливи. Коефициентът на\n# корелация (rho) принадлежи на интервала [-1, 1]. Силата на връзката се определя от абсолютната\n# стойност на rho. Въпреки, че силата на връзката е субективна, все пак можем да определим някакви\n# нива.\nN <- 1000\n\n# abs(rho) = 1 - Детерминистична връзка (y = f(x)). За една стойност на x имаме точно една\n# единствена стойност на y.\nset.seed(3654)\nx1 <- runif(N)\ny1 <- 3*x1 + 4\nrho1 <- round(cor(x1, y1), 3)\n\n# 0.9 <= abs(rho) < 1 - Много силна корелация на между x и y\nset.seed(3654)\nx2 <- runif(N)\ny2 <- 3*x2 + 4 + rnorm(N, sd = 0.2)\nrho2 <- round(cor(x2, y2), 3)\n\n# 0.75 <= abs(rho) < 0.9 - Силна корелация на между x и y\nset.seed(3654)\nx3 <- runif(N)\ny3 <- -3*x3 + 4 + rnorm(N, sd = 0.5)\nrho3 <- round(cor(x3, y3), 3)\n\n# 0.5 <= abs(rho) < 0.75 - Средна корелация на между x и y\nset.seed(3654)\nx4 <- runif(N)\ny4 <- -3*x4 + 4 + 1*rnorm(N)\nrho4 <- round(cor(x4, y4), 3)\n\n# 0 <= abs(rho) < 0.5 - Слаба корелация на между x и y\nset.seed(3654)\nx5 <- runif(N)\ny5 <- 3*x4 + 4 + 3*rnorm(N)\nrho5 <- round(cor(x5, y5), 3)\n\npar(mfrow = c(2, 3))\nplot(x1, y1, main = paste(\"rho:\", rho1))\nabline(a = 4, b = 3, col = \"red\", lwd = 2)\n\nplot(x2, y2, main = paste(\"rho:\", rho2))\nabline(a = 4, b = 3, col = \"red\", lwd = 2)\n\nplot(x3, y3, main = paste(\"rho:\", rho3))\nabline(a = 4, b = -3, col = \"red\", lwd = 2)\n\nplot(x4, y4, main = paste(\"rho:\", rho4))\nabline(a = 4, b = -3, col = \"red\", lwd = 2)\n\nplot(x5, y5, main = paste(\"rho:\", rho5))\nabline(a = 4, b = 3, col = \"red\", lwd = 2)\npar(mfrow = c(1, 1))\n\n# От графиките се вижда, че колко по-разпръснати са наблюденията около правата,\n# толкова корелацията намалява.\n\n# Командата за корелация е cor. С командата може да се изследват както връзките\n# между две променливи, така и връзките между N-мерни ЧИСЛОВИ данни.\n\nX <- x3; Y <- y3\nX_mean <- mean(X)\nY_mean <- mean(Y)\n\nXY <- (X - X_mean)*(Y - Y_mean)\n\nXX <- (X - X_mean)^2\nYY <- (Y - Y_mean)^2\n\nsum(XY)/sqrt(sum(XX)*sum(YY)) # Стойността на корелацията\ncor(x3, y3)\n\ncor(x = mtcars$mpg, y = mtcars$hp)\n# Връща ни само едно число - корелацията между двете променливи\n\ncor(mtcars[, c(\"mpg\", \"disp\", \"hp\", \"drat\", \"wt\", \"qsec\")])\nmtcars\n# Връща СИМЕТРИЧНА матрица (A[i, j] == A[j, i]) с корелациите между отделните\n# променливи.\n# Интересно е, че, по главния диагонал, всички стойности са единици. Това е\n# следствие от формулата\n\n# ---------------------------------\n# Съществуват три основни вида корелации - Pearson, Spearman и Kendall. Първата\n# корелация е параметрична оценка на връзката между две променливи, докато останалите\n# две - непараметрични.\n\n# Тоест корелацията на Pearson е по-точна, но е неустойчива при наличието на outlier-и\n# Останалите две корелации са по-стабилни и не толкова точни.\n\n# Най-лесно това ще го демонстрираме с примера по-долу\nset.seed(4413)\nx <- sort(rnorm(200, mean = 2))\ny <- x + sqrt(1 - 0.8^2)*rnorm(length(x))\nplot(x, y, main = paste(\"Pearson's rho:\", round(cor(x, y), 2)))\nabline(lm(y ~ x), col = \"forestgreen\", lwd = 2, lty = 4)\nround(cor(x, y), 2) # 0.85\n\n\nx1 <- c(x, 3.4, 3, 3.8, 3.5, 4, 4.1)\ny1 <- c(y, 17, 18.5, 19.2, 19, 20, 22)\nplot(x1, y1)\nabline(lm(y1 ~ x1), col = \"darkred\", lwd = 2, lty = 3)\n\ntext(x = 0.5, y = 18, labels = paste0(\"Pearson's rho:\", round(cor(x1, y1), 2)))\ntext(x = 0.5, y = 17, labels = paste0(\"Spearman's rho: \", round(cor(x1, y1, method = \"spearman\"), 2)))\n\n# ---------------\n# Линейни модели\n# Линейна регресия\nNN <- 300\nset.seed(73391)\nx1 <- round(runif(NN, 0, 5), 1)\nx2 <- round(runif(NN, 2, 6), 1)\ny <- 3 + 2.5*x1 + rnorm(NN)\nDF <- data.frame(x1, x2, y)\n\n# Какво представлява линейната регресия?\n# Линейната регресия е статистически метод, който ни позволява да проучим и обобщим връзките\n# между две множества от непрекъснати променливи - X и y:\n# - в множеството X се намират обясняващите променливи (наречени още предиктори или независими\n# променливи) и върху тях се основават нашите прогнози;\n# - в множеството y се съдържа една променлива (вектор), наричаща се зависима променлива\n# променливаи или резултат, която искаме да прогнозираме.\n\n# Ако приемем, че размерът на вектора y e N, a размерът на множеството X е N x p, то\n# връзката между двете множества е y = b(0) + b(1)*x(1) + ... + b(p)*x(p) + error, където\n# b(0) е константа, а b(1), ..., b(p) са параметрите, които обясняват влиянието на X над y.\n# Линейната регресия ни позволява да оценим стойностите на тези p+1 коефцициенти.\n# Има няколко начина за намирането на тези коефициенти, но най-често използваният е OLS\n# (метод на най-малките квадрати)\n\n# В R, функцията за линейна регресия е lm()\n\n# Два начина за извикване на линейна регресия. Първият, ако виждаме нужните ни променливите\n# в средата на R. Лесно можем да проверим дали променливите са заредени в среда на R с функцията\n# ls().\nls() # List all variables\nmodel1 <- lm(y ~ x1)\n\n# RM variables\nrm(list = c(\"x1\", \"x2\", \"y\"))\n\n# Вторият начин е като посочим data frame-а или матрицата, който(която) съдържа необходимите\n# променливи.\nmodel2 <- lm(y ~ x1, data = DF)\nmodel2\nrm(list = \"model2\")\n\n# Когато изследваме връзка между една зависима и една обясняваща променлива, тогава линейната\n# регресия е едномерна (или проста). При наличието на повече предиктори (обясняващи променливи),\n# тогава имаме многомерна линейна регресия.\n# Горните два модела са пример за проста линейна регресия\n# Многомерната линейна регресия ще бъде разгледана по-подробно по-нататък в курса.\n\n# След като сме построили линееен модел, следващата стъпка е да проверим до колко този модел\n# описва добре данни и какви са оценките на коефициенти му.\nsummary(model1)\n\n# -------\n# Хипотези и проверка на хипотези\n# Накратко, статистическата хипотеза е предположение за параметър на извадката/популацията.\n# Това предположение може да бъде вярно или невярно. Ето защо съществуват две взаимоизключващи се\n# хипотези - нулева (H0) и алтернативна (H1).\n# Имаме три типа хипотези:\n# 1. H0: параметър = число, H1: параметър != число\n# 2. H0: параметър <= число, H1: параметър > число\n# 3. H0: параметър >= число, H1: параметър < число\n\n# Проверката на хипотезите става с помощта на тестове. На база вида на теста, искаме да\n# отхвърлим или не нулевата хипотеза H0. Дали нулевата хипотеза е отхвърлена се определя от\n# стойност, наречена \"p-value\". Стандартно, една H0 се отхвърля при стойност на p-value < 0.05.\n# При отхвърляне на нулева хипотеза, за вярна се приема алтернативната H1.\n# -------\n\n# Първо ще проверим дали коефициентите са статистически значими, тоест дали е необходимо да\n# участват в анализа. За всеки един коефициент проверяваме хипотезата дали коефициентът е равен\n# на 0 (b(i) ?= 0). За да бъде един коефициент значим, то трябва за него да отхвърлим горната\n# хипотеза. Както беше споменато по-горе, за да се отхвърли H0, то стойността на p-vaue трябва да\n# бъде по-малка от 0.05. Стойностите p-value се намират в колоната \"Pr(>|t|)\". Стойностите на\n# p-value за двата параметъра е 2e-16 << 0,05 и следователно двата параметъра са статистически\n# значими.\n\nsummary(model3 <- lm(y ~ x2, data = DF))\nrm(\"model3\")\n\n# Да разгледаме оценките пред коефицнета x2. Оценката на коефициента е -0,1505. Но въпреки, че\n# стойността му е различна от 0, то той е статистически незначим. Защо? Защото стойността на\n# p-value e 0,414 > 0,05. Тоест, този коефициент може да отпадне от анализа.\n\n# Следващата стъпка е да проверим до колко модела описва добре данните. За целта ще използваме\n# статистиките \"Multiple R-squared\" или \"Adjusted R-squared\". Статистиката \"Multiple R-squared\"\n# приема стойности в интервала [0-1]. Колкото тази статистика се приближава до единица, толкова\n# моделът е по-добър. И обратното, колкото стойността на R2 клони към 0, толкова моделът не се\n# справя с описването на данните. Моделите, които имат стойности за R2 под 0.5, ги приемаме за\n# слаби.\n\n# Препоръчително е да се използва обаче статистиката Adjusted R-squared, защото тя \"наказва\",\n# когато използваме ненужни променливи. По принцип, тази статистика също приема стойности в\n# интервала [0-1], но когато използваме само статистически незначими, тогава Adjusted R-squared\n# може да приеме и отрицателни стойности.\n\nsummary(model1)\n# Какво можем да кажем за model2? Стойността на Adjusted R2 е 0.9284. Тоест моделът описва\n# много добре данните.\n\n# - Какво представлява R2 и как можем да го изчислим?\n# - За целта първо ще разгледаме начините да изчисляваме прогнози и остатъците (residuals).\n\n# Регресионното уравнение придобива вида y = 3.027 + 2.247*x1.\n\n# Линейната регресия позволява не само да се оценят връзките между отделните обясняващи\n# променливи и резулатата, но както споменахме по-горе, позволява да се правят прогнози. В R\n# използваме функцията \"predict\" за прогнозиране. Функцията съдържа два основни параметъра object\n# (построения модел) и newdata (данни, за които искаме да направим прогноза)\nmodel1.predictions <- predict(object = model1, newdata = DF)\nmodel1.predictions.alt <- model1$coefficients[1] + model1$coefficients[2]*DF$x1 # Алтернативен начин\nall(model1.predictions == model1.predictions.alt)\nrm(\"model1.predictions.alt\")\n\n### ......\n\n", "meta": {"hexsha": "ac984553cd879d4f6b174c7581977ddcf334d4f8", "size": 17311, "ext": "r", "lang": "R", "max_stars_repo_path": "fmi-course-notes/ex4_correlation_models_NOT_COMPLETED.r", "max_stars_repo_name": "ymihaylov/R-playground", "max_stars_repo_head_hexsha": "70ce16567992da1d339407d506ac385c51e95099", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fmi-course-notes/ex4_correlation_models_NOT_COMPLETED.r", "max_issues_repo_name": "ymihaylov/R-playground", "max_issues_repo_head_hexsha": "70ce16567992da1d339407d506ac385c51e95099", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fmi-course-notes/ex4_correlation_models_NOT_COMPLETED.r", "max_forks_repo_name": "ymihaylov/R-playground", "max_forks_repo_head_hexsha": "70ce16567992da1d339407d506ac385c51e95099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8253164557, "max_line_length": 111, "alphanum_fraction": 0.6910057189, "num_tokens": 8221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7017066609759455}} {"text": "=begin\n[(())] \n= Algebra::LocalizedRing\n((*(Class of Localization of Ring)*))\n\nThis class creates the fraction ring of the given ring.\nTo make a concrete class, use the class method\n((<::create>)) or the function (())().\n\n== File Name:\n* ((|localized-ring.rb|))\n\n== SuperClass:\n\n* ((|Object|))\n\n== Included Ring\nnone.\n\n== Associated Functions:\n\n--- Algebra.LocalizedRing(ring)\n Same as ((<::create>))(ring).\n\n--- Algebra.RationalFunctionField(ring, obj)\n Creates the rational function field over ((|ring|)) with\n the variable expressed by ((|obj|)). This class is equipped with\n the class method ((|::var|)) which returns the variable.\n \n Example: the quotient field over the polynomial ring over Rational\n require \"algebra/localized-ring\"\n require \"rational\"\n F = Algebra.RationalFunctionField(Rational, \"x\")\n x = F.var\n p ( 1 / (x**2 - 1) - 1 / (x**3 - 1) )\n #=> x^2/(x^4 + x^3 - x - 1)\n\n\n--- Algebra.MRationalFunctionField(ring, [obj1[, obj2, ...]])\n Creates the rational function field over ((|ring|)) with\n the variables expressed by ((|obj1|)), ((|obj2|)), .... This class is equipped with\n the class method ((|::vars|)) which returns the array of variables.\n \n Example: the quotient field over the polynomial ring over Rational\n require \"algebra/localized-ring\"\n require \"rational\"\n G = Algebra.MRationalFunctionField(Rational, \"x\", \"y\", \"z\")\n x, y, z = G.vars\n f = (x + z) / (x + y) - z / (x + y)\n p f #=> (x^2 + xy)/(x^2 + 2xy + y^2)\n p f.simplify #=> x/(x + y)\n\n== Class Method:\n\n--- ::create(ring)\n Returns the fraction ring of which the numerator and the\n denominator are the elements of the ((|ring|)).\n\n This returns the subclass of Algebra::LocalizedRing. The subclass\n has the class method ((|::ground|)) and (({::[]})) which \n return ((|ring|)) and (({x/1})) respectively.\n \n Example: Yet Another Rational\n require \"localized-ring\"\n F = Algebra.LocalizedRing(Integer)\n p F.new(1, 2) + F.new(2, 3) #=> 7/6\n\n Example: rational function field over Integer\n require \"polynomial\"\n require \"localized-ring\"\n P = Algebra.Polynomial(Integer, \"x\")\n F = Algebra.LocalizedRing(P)\n x = F[P.var]\n p ( 1 / (x**2 - 1) - 1 / (x**3 - 1) )\n #=> (x^3 - x^2)/(x^5 - x^3 - x^2 + 1)\n\n--- ::zero\n Returns zero.\n \n--- ::unity\n Returns unity.\n\n#--- ::[](num, den = nil)\n\n#--- ::reduce(num, den)\n\n\n== Methods:\n\n#--- monomial?; true; end\n\n--- zero?\n Returns true if ((|self|)) is zero.\n\n--- zero\n Returns zero.\n \n--- unity\n Returns unity.\n\n--- ==(other)\n Returns true if ((|self|)) equals ((|other|)).\n\n--- +(other)\n Returns the sum of ((|self|)) and ((|other|)).\n\n--- -(other)\n Returns the difference of ((|self|)) from ((|other|)).\n\n--- *(other)\n Returns the product of ((|self|)) and ((|other|)).\n\n--- /(other)\n Returns the quotient of ((|self|)) by ((|other|)) using (()).\n\n--- **(n)\n Returns the ((|n|))-th power of ((|self|)).\n\n#--- to_s\n\n#--- inspect\n\n#--- hash\n\n=end\n\n", "meta": {"hexsha": "8f2c7481b7e5e9f2938f3dbb923e4b84bdb5e163", "size": 3135, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc/localized-ring.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/localized-ring.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/localized-ring.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6850393701, "max_line_length": 87, "alphanum_fraction": 0.5783094099, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7015839053589621}} {"text": "# An illustration written in R for the Monty Hall Problem \n# Copyright (C) 2019 Dr. Norbert Bátfai, nbatfai@gmail.com\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see \n#\n# https://bhaxor.blog.hu/2019/01/03/erdos_pal_mit_keresett_a_nagykonyvben_a_monty_hall-paradoxon_kapcsan\n# \n\nkiserletek_szama=10000000\nkiserlet = sample(1:3, kiserletek_szama, replace=T)\njatekos = sample(1:3, kiserletek_szama, replace=T)\nmusorvezeto=vector(length = kiserletek_szama)\n\nfor (i in 1:kiserletek_szama) {\n\n if(kiserlet[i]==jatekos[i]){\n \n mibol=setdiff(c(1,2,3), kiserlet[i])\n \n }else{\n \n mibol=setdiff(c(1,2,3), c(kiserlet[i], jatekos[i]))\n \n }\n\n musorvezeto[i] = mibol[sample(1:length(mibol),1)]\n\n}\n\nnemvaltoztatesnyer= which(kiserlet==jatekos)\nvaltoztat=vector(length = kiserletek_szama)\n\nfor (i in 1:kiserletek_szama) {\n\n holvalt = setdiff(c(1,2,3), c(musorvezeto[i], jatekos[i]))\n valtoztat[i] = holvalt[sample(1:length(holvalt),1)]\n \n}\n\nvaltoztatesnyer = which(kiserlet==valtoztat)\n\n\nsprintf(\"Kiserletek szama: %i\", kiserletek_szama)\nlength(nemvaltoztatesnyer)\nlength(valtoztatesnyer)\nlength(nemvaltoztatesnyer)/length(valtoztatesnyer)\nlength(nemvaltoztatesnyer)+length(valtoztatesnyer)\n", "meta": {"hexsha": "5e7652b371e6614f3aafa6bebef338e19f07df48", "size": 1834, "ext": "r", "lang": "R", "max_stars_repo_path": "Prog2/bhax/attention_raising/MontyHall_R/mh.r", "max_stars_repo_name": "mesterakos963/Prog2", "max_stars_repo_head_hexsha": "edc3e49567d29211510aa9cd3f4bf639c49c1ea6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Prog2/bhax/attention_raising/MontyHall_R/mh.r", "max_issues_repo_name": "mesterakos963/Prog2", "max_issues_repo_head_hexsha": "edc3e49567d29211510aa9cd3f4bf639c49c1ea6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prog2/bhax/attention_raising/MontyHall_R/mh.r", "max_forks_repo_name": "mesterakos963/Prog2", "max_forks_repo_head_hexsha": "edc3e49567d29211510aa9cd3f4bf639c49c1ea6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0847457627, "max_line_length": 106, "alphanum_fraction": 0.7290076336, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7013811681865881}} {"text": "pie1=413/527\r\npie2=392/608\r\n# The sample awareness proportion is higher in Wichita, so let's make Wichita region 1.\r\n#The estimated standard error is\r\nsigma=sqrt(((pie1*(1-pie1))/527)+((pie2*(1-pie2))/608))\r\nprint(sigma)\r\nalpha=0.025\r\nz.alpha=qnorm(1-alpha)\r\nerror=z.alpha*sigma\r\n# 95% confidence interval \r\nleft_i=(pie1-pie2)-error\r\nright_i=(pie1-pie2)+error\r\nprint(left_i)\r\nprint(right_i)\r\n\r\n", "meta": {"hexsha": "06d8f6960aa6c4422e57da28438ba9fb116d0a09", "size": 395, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.6/Ex10_6.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.6/Ex10_6.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.6/Ex10_6.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 24.6875, "max_line_length": 88, "alphanum_fraction": 0.7164556962, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.7012604521408101}} {"text": "f <- function(x) x^3 -3*x^2 + 2*x\n\nfindroots <- function(f, begin, end, tol = 1e-20, step = 0.001) {\n se <- ifelse(sign(f(begin))==0, 1, sign(f(begin)))\n x <- begin\n while ( x <= end ) {\n v <- f(x)\n if ( abs(v) < tol ) {\n print(sprintf(\"root at %f\", x))\n } else if ( ifelse(sign(v)==0, 1, sign(v)) != se ) {\n print(sprintf(\"root near %f\", x))\n }\n se <- ifelse( sign(v) == 0 , 1, sign(v))\n x <- x + step\n }\n}\n\nfindroots(f, -1, 3)\n", "meta": {"hexsha": "a66fcaf084b150b13deb1874a9202587a011c051", "size": 462, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Roots-of-a-function/R/roots-of-a-function.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Roots-of-a-function/R/roots-of-a-function.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Roots-of-a-function/R/roots-of-a-function.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 24.3157894737, "max_line_length": 65, "alphanum_fraction": 0.4783549784, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741298, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.701260433870647}} {"text": "beta1=.01291\r\nse=.00283\r\n# test statistic\r\nt=beta1/se\r\nprint(t)\r\nn=54\r\nk=4\r\ndf=n-(k+1)\r\nalpha=0.05\r\ntvalue=qt(1-alpha,df)\r\n #the computed value of the test statistic > tvalue . we conclude there is significant evidence to reject H0", "meta": {"hexsha": "d18c8699389d1e7d8468ba025db28288fd715560", "size": 231, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH12/EX12.15/Ex12_15.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH12/EX12.15/Ex12_15.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH12/EX12.15/Ex12_15.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 21.0, "max_line_length": 108, "alphanum_fraction": 0.70995671, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.7012166235356703}} {"text": " # odds of a randomly chosen person carrying HIV\r\np=.001/.009\r\n# occurrence of a positive test result causes the odds to change to\r\np_hiv=.001\r\np_positive_hiv=.95\r\np_nothiv=.999\r\np_positive_nothiv=.02\r\nP_occurencepositive=(p_hiv*p_positive_hiv)/(p_nothiv*p_positive_nothiv)\r\nprint(P_occurencepositive)\r\n\r\n# The odds of carrying HIV do go up given a positive test result, from about\r\n#.001 (to 1) to about .0475 (to 1). ", "meta": {"hexsha": "aed7ab4ffd1409e6789ee4c92c15099115c76c99", "size": 421, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.15/Ex10_15.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.15/Ex10_15.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.15/Ex10_15.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 35.0833333333, "max_line_length": 77, "alphanum_fraction": 0.757719715, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142217223021, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.7011422437544385}} {"text": "## Código para Cãlculos dos Dados de Galton\r\n## Prof. James Hunter\r\n## from: https://rstudio.cloud/project/1181172\r\n## 28 de maio de 2020\r\n\r\nlibrary(tidyverse)\r\n\r\ngalton <- readRDS(here::here(\"galton.rds\"))\r\nstr(galton)\r\n\r\nboys <- galton %>% \r\n filter(sex == \"M\") %>% \r\n select(-family, -mother, -sex, -nkids)\r\nglimpse(boys)\r\n\r\ngrpf <- ggplot(data = boys, aes(x = father, y = height)) + geom_point(shape = 20) + geom_rug()\r\ngrpf <- grpf + labs(x = \"Altura do Pai\", y = \"Altura do Filho\", title = \"Alturas em Polegadas\")\r\ngrpf\r\n\r\ngrpf2 <- grpf + geom_smooth(method = \"lm\", se = FALSE, color = \"red\")\r\ngrpf2\r\n\r\nsummarytools::descr(boys)\r\npaste(\"Coeficiente de Correlação:\", \r\n with(boys, round(cor(father, height), 3)))\r\n\r\nset.seed(1946)\r\nboyscoef <- coef(lm(height~father, data = boys))\r\nint <- boyscoef[1]; inc <- boyscoef[2] \r\nx <- boys %>% \r\n filter((height >= 66 & height < 71) & (father >= 67 & father < 71)) %>% \r\n sample_n(5) %>% \r\n mutate(ypred = int + inc * father)\r\nxplot <- ggplot(data = x, aes(x = father, y = height)) \r\nxplot <- xplot + geom_point(shape = 19, colour = \"darkgreen\")\r\nxplot <- xplot + geom_abline(aes(intercept = int, slope = inc), colour = \"darkred\")\r\nxplot <- xplot + geom_segment(aes(x = father[3], y = height[3], xend = father[3], \r\n yend = ypred[3]), colour = \"blue\", \r\n arrow = arrow(length = unit(0.3,\"cm\")))\r\nxplot <- xplot + geom_point(aes(x = father[3], y = ypred[3]), \r\n shape = 19, color = \"blue\" )\r\nxplot <- xplot + annotate(geom = \"text\", x = 68.2, y = 68.7, \r\n label = \"y-hat\")\r\nxplot <- xplot + annotate(geom = \"text\", x = 68.2, y = 66.8, label = \"y(i)\")\r\nxplot\r\n\r\nxplot2 <- xplot + geom_hline(yintercept = mean(boys$height), color = \"orange\")\r\nxplot2 <- xplot2 + geom_segment(aes(x = father[3], y = ypred[3], \r\n xend = father[3], \r\n yend = mean(boys$height)), \r\n colour = \"green\", \r\n arrow = arrow(length = unit(0.3,\"cm\")))\r\nxplot2 <- xplot2 + annotate(geom = \"text\", x = 67.7, y = 68.9, \r\n label = \"SSR\", color = \"darkgreen\")\r\nxplot2 <- xplot2 + annotate(geom = \"text\", x = 67.5, y = 69.3, label = \"y-bar\")\r\nxplot2 <- xplot2 + annotate(geom = \"text\", x = 67.7, y = 68, \r\n label = \"SSE\", color = \"darkblue\")\r\nxplot2 <- xplot2 + geom_segment(aes(x = father[3] + 0.05, y = height[3], \r\n xend = father[3] + .05, \r\n yend = mean(boys$height)), \r\n colour = \"red\", \r\n arrow = arrow(length = unit(0.3,\"cm\")))\r\nxplot2 <- xplot2 + annotate(geom = \"text\", x = 68.3, y = 68, \r\n label = \"SST\", color = \"darkred\")\r\nxplot2\r\n\r\nfit1 <- lm(height ~ father, data = boys)\r\nsummary(fit1)\r\n\r\nbroom::tidy(fit1) %>% knitr::kable()\r\n\r\ncoef(fit1) \r\n\r\nfit1 %>% broom::augment(newdata = data_frame(father = 72))", "meta": {"hexsha": "191607e1da51ffa8ebebfe07ba3acb7809e373dd", "size": 3098, "ext": "r", "lang": "R", "max_stars_repo_path": "codigo_galton.r", "max_stars_repo_name": "jameshunterbr/Sustentare_MAD_2020", "max_stars_repo_head_hexsha": "299a7f0af7e999e59cc53c57cf22618b6eb68092", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codigo_galton.r", "max_issues_repo_name": "jameshunterbr/Sustentare_MAD_2020", "max_issues_repo_head_hexsha": "299a7f0af7e999e59cc53c57cf22618b6eb68092", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codigo_galton.r", "max_forks_repo_name": "jameshunterbr/Sustentare_MAD_2020", "max_forks_repo_head_hexsha": "299a7f0af7e999e59cc53c57cf22618b6eb68092", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8648648649, "max_line_length": 96, "alphanum_fraction": 0.5090380891, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7010628146077942}} {"text": "#' Piecewise cosine interpolation\n#' \n#' Returns a list of points which interpolate given data points. Similar to\n#' \\link[stats]{approx}.\n#' \n#' @param x,y numeric vectors giving the coordinates of the points to be \n#' interpolated.\n#' @param xout an optional set of numeric values specifying where interpolation \n#' is to take place.\n#' @param n If xout is not specified, interpolation takes place at n equally \n#' spaced points spanning the interval [\\code{min(x)}, \\code{max(x)}].\n#' @param yleft the value to be returned when input \\code{x} values are less \n#' than \\code{min(x)}. The default is defined by the value of rule given \n#' below.\n#' @param yright the value to be returned when input \\code{x} values are greater\n#' than \\code{max(x)}. The default is defined by the value of rule given \n#' below.\n#' @param rule an integer (of length 1 or 2) describing how interpolation is to \n#' take place outside the interval [\\code{min(x)}, \\code{max(x)}]. If rule is \n#' \\code{1} then \\code{NA}s are returned for such points and if it is\n#' \\code{2}, the value at the closest data extreme is used. Use, e.g.,\n#' \\code{rule = 2:1}, if the left and right side extrapolation should differ.\n#' @param ties Handling of tied \\code{x} values. Either a function with a single\n#' vector argument returning a single number result or the string \n#' \\code{\"ordered\"}.\n#' \n#' @details This function is based on and functions similarly to\n#' \\link[stats]{approx} and \\link[stats]{spline} .\n#' \n#' @examples\n#' y <- rnorm(10)\n#' x <- 1:10\n#' plot(x, y)\n#' lines(approx.cos(x, y, n=200))\n#' @export\napprox.cos <- function(x, y=NULL, xout, n=50, yleft, yright, rule=1, ties=mean) {\n require('stats')\n \n stopifnot(is.numeric(rule), (lenR <- length(rule)) >= 1L, \n lenR <= 2L)\n if (lenR == 1) \n rule <- rule[c(1, 1)]\n \n x <- stats:::regularize.values(x, y, ties)\n y <- x$y\n x <- x$x\n \n nx <- as.integer(length(x))\n if (is.na(nx)) \n stop(\"invalid length(x)\")\n if (nx <= 1) {\n stop(\"need at least two non-NA values to interpolate\")\n }\n \n if (missing(yleft)) \n yleft <- if (rule[1L] == 1) \n NA\n else y[1L]\n if (missing(yright)) \n yright <- if (rule[2L] == 1) \n NA\n else y[length(y)]\n stopifnot(length(yleft) == 1L, length(yright) == 1L)\n if (missing(xout)) {\n if (n <= 0) \n stop(\"'approx' requires n >= 1\")\n xout <- seq.int(x[1L], x[nx], length.out = n)\n }\n x <- as.double(x)\n y <- as.double(y)\n \n # Select values of x we can actually interpolate\n xnew <- xout[xout >= min(x) & xout <= max(x)]\n \n # For each new x find which original x it is next to\n xi <- findInterval(xnew, x, TRUE)\n \n # calculate relative distance to original x\n dx <- (x[xi+1]-xnew)/(x[xi+1]-x[xi])\n \n # Interpolate with piecewise cosine function\n ynew <- (0.5 + cos(pi*dx)/2) * (y[xi+1] - y[xi]) + y[xi]\n \n # Add y values for any x values outside interval\n yout <- c(rep(yleft, sum(xoutmax(x))))\n \n list(x = xout, y = yout)\n}", "meta": {"hexsha": "0c0010e2325604d4746cb5565dc29d8322ca1ca4", "size": 3032, "ext": "r", "lang": "R", "max_stars_repo_path": "R/cos_interp.r", "max_stars_repo_name": "sushilashenoy/zoom.plot", "max_stars_repo_head_hexsha": "036aa60980fdf7d86b5168f08e63aa13ca1f9e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-30T22:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-14T22:13:21.000Z", "max_issues_repo_path": "R/cos_interp.r", "max_issues_repo_name": "sushilashenoy/zoom.plot", "max_issues_repo_head_hexsha": "036aa60980fdf7d86b5168f08e63aa13ca1f9e4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-03-30T22:17:37.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-23T16:18:28.000Z", "max_forks_repo_path": "R/cos_interp.r", "max_forks_repo_name": "sushilashenoy/zoom.plot", "max_forks_repo_head_hexsha": "036aa60980fdf7d86b5168f08e63aa13ca1f9e4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-20T19:14:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-20T19:14:21.000Z", "avg_line_length": 34.4545454545, "max_line_length": 81, "alphanum_fraction": 0.6276385224, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7008258290551664}} {"text": "# Math\r\n\r\n2+3\r\n10-5\r\n3-7\r\n2*5\r\n5/8\r\n10/2\r\n2^2\r\n\r\nx <- 5\r\ny <- 10\r\nx/y\r\ny*x\r\nx+2\r\n\r\n# character\r\n\r\n\"ali\"\r\n\"emam\"\r\nali\r\n\"ali\" + \"emam\"\r\n\"ali\" - \"emam\"\r\n\"5\" + \"5\"\r\n5 + \"5\"\r\nx <- \"ali\"\r\ny <- \"emam\"\r\n\r\n# vector\r\n\r\nc(1,2,3,4,5)\r\nc(\"ali\", \"emam\")\r\nc(1,2,3, \"ali\") # only one type of data\r\n\r\nx <- c(1,2,3,4,5)\r\ny <- c(\"ali\", \"emam\")\r\nxx <- c(10,20,30,40,50)\r\nxx + x\r\n\r\n# functions\r\n\r\nsqrt(25)\r\nsqrt(\"25\")\r\n\r\nmean(x)\r\nmean(y)\r\nmean(xx)\r\nxx <- c(10,20,30,40,50, NA)\r\nmean(xx)\r\nmean(xx, na.rm = T)\r\nmedian(xx, na.rm = T)\r\nsummary(xx)\r\n# def. new function\r\nxx <- c(10,20,30,40,40, 40,50)\r\nyy <- table(xx)\r\nyy\r\nwhich.max(yy)\r\n\r\nget.mode <- function(x){\r\n y <- table(x)\r\n mode <- which.max(y)\r\n return(mode)\r\n}\r\n\r\nget.mode(xx)\r\n\r\n# data.frame\r\n\r\ngene1 <- c(20,30,40,60)\r\ngene2 <- c(200,350,40,30)\r\ngene3 <- c(56,156,23,75)\r\ngene4 <- c(30,11,19,56)\r\ndf.genes <- data.frame(g1 = gene1, g2= gene2, g3= gene3, g4 = gene4)\r\nView(df.genes)\r\nmean(df.genes$g2)\r\nmean(df.genes$g3)\r\n\r\ndf.genes$g1 + df.genes$g4\r\n\r\napply(df.genes, 2, mean) # col. by genes\r\n\r\napply(df.genes, 1, mean) # row. by sample\r\n\r\nplot(df.genes)\r\nhist(df.genes$g1)\r\nhist(df.genes$g1,freq = F)\r\n#install.packages(\"ggplot2\")\r\n\r\nlibrary(ggplot2)\r\nggplot(df.genes,aes(x = g2))+ geom_histogram(bins = 5)\r\n", "meta": {"hexsha": "85c69b7bb52473e61a95fe0fa64611893987ef35", "size": 1251, "ext": "r", "lang": "R", "max_stars_repo_path": "maqalelmy/101.r", "max_stars_repo_name": "AliYoussef96/CUBex", "max_stars_repo_head_hexsha": "7631f11e2f1635280c9f404f29b337d73a394189", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-08T05:20:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:16:43.000Z", "max_issues_repo_path": "maqalelmy/101.r", "max_issues_repo_name": "AliYoussef96/CUBex", "max_issues_repo_head_hexsha": "7631f11e2f1635280c9f404f29b337d73a394189", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maqalelmy/101.r", "max_forks_repo_name": "AliYoussef96/CUBex", "max_forks_repo_head_hexsha": "7631f11e2f1635280c9f404f29b337d73a394189", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-18T16:23:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-18T16:23:33.000Z", "avg_line_length": 13.7472527473, "max_line_length": 69, "alphanum_fraction": 0.5507593925, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.700471512933466}} {"text": "##### Chapter 5: Classification using Decision Trees and Rules -------------------\r\n\r\n#### Part 1: Decision Trees -------------------\r\n\r\n## Understanding Decision Trees ----\r\n# calculate entropy of a two-class segment\r\n-0.60 * log2(0.60) - 0.40 * log2(0.40)\r\n\r\ncurve(-x * log2(x) - (1 - x) * log2(1 - x),\r\n col=\"red\", xlab = \"x\", ylab = \"Entropy\", lwd=4)\r\n\r\n## Example: Identifying Risky Bank Loans ----\r\n## Step 2: Exploring and preparing the data ----\r\ncredit <- read.csv(\"credit.csv\")\r\nstr(credit)\r\n\r\n# look at two characteristics of the applicant\r\ntable(credit$checking_balance)\r\ntable(credit$savings_balance)\r\n\r\n# look at two characteristics of the loan\r\nsummary(credit$months_loan_duration)\r\nsummary(credit$amount)\r\n\r\n# look at the class variable\r\ntable(credit$default)\r\n\r\n# create a random sample for training and test data\r\n# use set.seed to use the same random number sequence as the tutorial\r\nset.seed(12345)\r\ncredit_rand <- credit[order(runif(1000)), ]\r\n\r\n# compare the credit and credit_rand data frames\r\nsummary(credit$amount)\r\nsummary(credit_rand$amount)\r\nhead(credit$amount)\r\nhead(credit_rand$amount)\r\n\r\n# split the data frames\r\ncredit_train <- credit_rand[1:900, ]\r\ncredit_test <- credit_rand[901:1000, ]\r\n\r\n# check the proportion of class variable\r\nprop.table(table(credit_train$default))\r\nprop.table(table(credit_test$default))\r\n\r\n## Step 3: Training a model on the data ----\r\n# build the simplest decision tree\r\nlibrary(C50)\r\ncredit_model <- C5.0(credit_train[-17], credit_train$default)\r\n\r\n# display simple facts about the tree\r\ncredit_model\r\n\r\n# display detailed information about the tree\r\nsummary(credit_model)\r\n\r\n## Step 4: Evaluating model performance ----\r\n# create a factor vector of predictions on test data\r\ncredit_pred <- predict(credit_model, credit_test)\r\n\r\n# cross tabulation of predicted versus actual classes\r\nlibrary(gmodels)\r\nCrossTable(credit_test$default, credit_pred,\r\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\r\n dnn = c('actual default', 'predicted default'))\r\n\r\n## Step 5: Improving model performance ----\r\n\r\n## Boosting the accuracy of decision trees\r\n# boosted decision tree with 10 trials\r\ncredit_boost10 <- C5.0(credit_train[-17], credit_train$default,\r\n trials = 10)\r\ncredit_boost10\r\nsummary(credit_boost10)\r\n\r\ncredit_boost_pred10 <- predict(credit_boost10, credit_test)\r\nCrossTable(credit_test$default, credit_boost_pred10,\r\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\r\n dnn = c('actual default', 'predicted default'))\r\n\r\n# boosted decision tree with 100 trials (not shown in text)\r\ncredit_boost100 <- C5.0(credit_train[-17], credit_train$default,\r\n trials = 100)\r\ncredit_boost_pred100 <- predict(credit_boost100, credit_test)\r\nCrossTable(credit_test$default, credit_boost_pred100,\r\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\r\n dnn = c('actual default', 'predicted default'))\r\n\r\n## Making some mistakes more costly than others\r\n# create a cost matrix\r\nerror_cost <- matrix(c(0, 1, 4, 0), nrow = 2)\r\nerror_cost\r\n\r\n# apply the cost matrix to the tree\r\ncredit_cost <- C5.0(credit_train[-17], credit_train$default,\r\n costs = error_cost)\r\ncredit_cost_pred <- predict(credit_cost, credit_test)\r\n\r\nCrossTable(credit_test$default, credit_cost_pred,\r\n prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE,\r\n dnn = c('actual default', 'predicted default'))\r\n\r\n#### Part 2: Rule Learners -------------------\r\n\r\n## Example: Identifying Poisonous Mushrooms ----\r\n## Step 2: Exploring and preparing the data ---- \r\nmushrooms <- read.csv(\"mushrooms.csv\", stringsAsFactors = TRUE)\r\n\r\n# examine the structure of the data frame\r\nstr(mushrooms)\r\n\r\n# drop the veil_type feature\r\nmushrooms$veil_type <- NULL\r\n\r\n# examine the class distribution\r\ntable(mushrooms$type)\r\n\r\n## Step 3: Training a model on the data ----\r\nlibrary(RWeka)\r\n\r\n# train OneR() on the data\r\nmushroom_1R <- OneR(type ~ ., data = mushrooms)\r\n\r\n## Step 4: Evaluating model performance ----\r\nmushroom_1R\r\nsummary(mushroom_1R)\r\n\r\n## Step 5: Improving model performance ----\r\nmushroom_JRip <- JRip(type ~ ., data = mushrooms)\r\nmushroom_JRip\r\nsummary(mushroom_JRip)\r\n\r\n# Rule Learner Using C5.0 Decision Trees (not in text)\r\nlibrary(C50)\r\nmushroom_c5rules <- C5.0(type ~ odor + gill_size, data = mushrooms, rules = TRUE)\r\nsummary(mushroom_c5rules)\r\n", "meta": {"hexsha": "7bb525740b6bf0632962c4e9eae98680cb686da5", "size": 4424, "ext": "r", "lang": "R", "max_stars_repo_path": "Training/MachineLearning/code/chapter 5/2148_05.r", "max_stars_repo_name": "davidmeza1/NASADatanauts", "max_stars_repo_head_hexsha": "084ce551d47317bb9513dae1e473ba91ddfdee7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-10-05T16:45:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-25T16:23:31.000Z", "max_issues_repo_path": "Training/MachineLearning/code/chapter 5/2148_05.r", "max_issues_repo_name": "davidmeza1/NASADatanauts", "max_issues_repo_head_hexsha": "084ce551d47317bb9513dae1e473ba91ddfdee7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Training/MachineLearning/code/chapter 5/2148_05.r", "max_forks_repo_name": "davidmeza1/NASADatanauts", "max_forks_repo_head_hexsha": "084ce551d47317bb9513dae1e473ba91ddfdee7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-04-27T11:01:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-05T19:22:24.000Z", "avg_line_length": 32.0579710145, "max_line_length": 83, "alphanum_fraction": 0.686482821, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7003030519595864}} {"text": "#Series temporais e analises preditivas - Fernando Amaral\r\nlibrary(forecast)\r\nlibrary(ggplot2)\r\n\r\ntreino = window(fdeaths, start=c(1974,1), end=c(1977,12))\r\nteste = window(fdeaths, start=c(1978,1), end=c(1979,12))\r\n\r\n#regressão\r\nmodelo1 = tslm(treino ~ season + trend, data=treino)\r\nprev1 = forecast(modelo1, h=24)\r\nautoplot(prev1)\r\n\r\n#rnn\r\nmodelo2 = nnetar(treino)\r\nprev2 = forecast(modelo2, h=24)\r\nautoplot(prev2)\r\n\r\nplot(fdeaths)\r\nlines(prev1$mean, col=\"blue\")\r\nlines(prev2$mean, col=\"red\")\r\nlines(teste, col=\"green\")\r\nlegend(\"topright\",legend=c(\"Reg.\",\"Rn\",\"Teste\"), col = c(\"blue\",\"red\",\"green\"), lty=1:2, cex=0.8)\r\n\r\naccuracy(prev1,teste )\r\naccuracy(prev2,teste )\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "bcff07c31465370259d6e54d63c03cbc07bd96a0", "size": 683, "ext": "r", "lang": "R", "max_stars_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/10.1.Metricas de Desempenho.r", "max_stars_repo_name": "tarsoqueiroz/Rlang", "max_stars_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/10.1.Metricas de Desempenho.r", "max_issues_repo_name": "tarsoqueiroz/Rlang", "max_issues_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/10.1.Metricas de Desempenho.r", "max_forks_repo_name": "tarsoqueiroz/Rlang", "max_forks_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.34375, "max_line_length": 98, "alphanum_fraction": 0.6734992679, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7001959541139563}} {"text": "##### Chapter 3: Classification using Nearest Neighbors --------------------\n\n## Example: Classifying Cancer Samples ----\n## Step 2: Exploring and preparing the data ---- \n\n# import the CSV file\nwbcd <- read.csv(\"wisc_bc_data.csv\", stringsAsFactors = FALSE)\n\n# examine the structure of the wbcd data frame\nstr(wbcd)\n\n# drop the id feature\nwbcd <- wbcd[-1]\n\n# table of diagnosis\ntable(wbcd$diagnosis)\n\n# recode diagnosis as a factor\nwbcd$diagnosis <- factor(wbcd$diagnosis, levels = c(\"B\", \"M\"),\n labels = c(\"Benign\", \"Malignant\"))\n\n# table or proportions with more informative labels\nround(prop.table(table(wbcd$diagnosis)) * 100, digits = 1)\n\n# summarize three numeric features\nsummary(wbcd[c(\"radius_mean\", \"area_mean\", \"smoothness_mean\")])\n\n# create normalization function\nnormalize <- function(x) {\n return ((x - min(x)) / (max(x) - min(x)))\n}\n\n# test normalization function - result should be identical\nnormalize(c(1, 2, 3, 4, 5))\nnormalize(c(10, 20, 30, 40, 50))\n\n# normalize the wbcd data\nwbcd_n <- as.data.frame(lapply(wbcd[2:31], normalize))\n\n# confirm that normalization worked\nsummary(wbcd_n$area_mean)\n\n# create training and test data\nwbcd_train <- wbcd_n[1:469, ]\nwbcd_test <- wbcd_n[470:569, ]\n\n# create labels for training and test data\n\nwbcd_train_labels <- wbcd[1:469, 1]\nwbcd_test_labels <- wbcd[470:569, 1]\n\n## Step 3: Training a model on the data ----\n\n# load the \"class\" library\nlibrary(class)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test,\n cl = wbcd_train_labels, k = 21)\n\n## Step 4: Evaluating model performance ----\n\n# load the \"gmodels\" library\nlibrary(gmodels)\n\n# Create the cross tabulation of predicted vs. actual\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred,\n prop.chisq = FALSE)\n\n## Step 5: Improving model performance ----\n\n# use the scale() function to z-score standardize a data frame\nwbcd_z <- as.data.frame(scale(wbcd[-1]))\n\n# confirm that the transformation was applied correctly\nsummary(wbcd_z$area_mean)\n\n# create training and test datasets\nwbcd_train <- wbcd_z[1:469, ]\nwbcd_test <- wbcd_z[470:569, ]\n\n# re-classify test cases\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test,\n cl = wbcd_train_labels, k = 21)\n\n# Create the cross tabulation of predicted vs. actual\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred,\n prop.chisq = FALSE)\n\n# try several different values of k\nwbcd_train <- wbcd_n[1:469, ]\nwbcd_test <- wbcd_n[470:569, ]\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=1)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=5)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=11)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=15)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=21)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=27)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n", "meta": {"hexsha": "a110c51718270fb035712043b0922ab426ca168e", "size": 3465, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 03/MLwR_v2_03.r", "max_stars_repo_name": "PacktPublishing/Machine-Learning-with-R---Second-Edition", "max_stars_repo_head_hexsha": "426864c2fc703962ae89ae6b437ac40d1b4104f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2019-06-13T02:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T06:15:12.000Z", "max_issues_repo_path": "Chapter03/MLwR_3rdEd_03.r", "max_issues_repo_name": "derekwietelman/Machine-Learning-with-R-Third-Edition", "max_issues_repo_head_hexsha": "740ba3086fa0a8f6c669e888e0dac6128acc5c08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-28T20:03:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-01T17:08:12.000Z", "max_forks_repo_path": "Chapter03/MLwR_3rdEd_03.r", "max_forks_repo_name": "derekwietelman/Machine-Learning-with-R-Third-Edition", "max_forks_repo_head_hexsha": "740ba3086fa0a8f6c669e888e0dac6128acc5c08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 76, "max_forks_repo_forks_event_min_datetime": "2019-04-02T08:33:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T12:38:48.000Z", "avg_line_length": 31.5, "max_line_length": 89, "alphanum_fraction": 0.7090909091, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7001959501655871}} {"text": "compute_normal <- function( vertex, face ) {\n \nface <- t( face ) \nvertex <- t( vertex )\neps <- 1E-12\n\ncrossp <- function( x, y ) {\n z <- x;\n z[1,] = x[2,]*y[3,] - x[3,]*y[2,];\n z[2,] = x[3,]*y[1,] - x[1,]*y[3,];\n z[3,] = x[1,]*y[2,] - x[2,]*y[1,];\n return( z )\n}\n \nnface <- dim(face)[2]\nnvert <- dim(vertex)[2]\nnormal <- array( 0, c(3, nvert) )\n\nnormalf <- crossp( vertex[,face[2,]]-vertex[,face[1,]], vertex[,face[3,]]-vertex[,face[1,]] );\nd <- sqrt( apply( normalf^2, 2, sum ) )\nd[d0)