{"text": "#!/usr/bin/env Rscript\n\n\n### For data analysis, the typical data matrix is organized with\n### rows containing the responses of a particular subject and the\n### columns representing different variables.\n\ndata = matrix(seq(1:24), ncol = 4)\n### dim() 返回维度list, S: subject, V: variable\n### 行列标题名\nrownames(data) = paste(\"S\", seq(1, dim(data)[1]), sep = \"\")\ncolnames(data) = paste(\"V\", seq(1, dim(data)[2]), sep = \"\")\n\n### t()转置\nt(data)\n\n\nv = 1:4\n\n### 结果不是期望的 ( 一列方向(columnwise)轮着加v)\ndata + v\n\n### 这是我们需要的\nt(t(data) + v)\n\n\n### 偏差分数(deviation scores): 每个数减去列向量的均值(colMeans)\n### scale = TRUE(The default for scale is to convert a matrix to standard scores)\nscale(x = data, scale = FALSE)\nscale(x = data, scale = TRUE)\n\n\n### 矩阵相加\nx = c(1, 2, 3, 4)\n### \nx + x\n### todo: 错误\n# x %+% t(x)\n\n### 标量 (内积)\n### x %*% x = sum(x * x)\nx %*% x\nsum(x * x)\n\n### 矩阵 (×乘: 外积)\nx %*% t(x)\n\n### 求colMeans, 可以使用one vector\n# rownum = dim(data)[1]\none = rep(1, dim(data)[1])\nt(one)\n\n# data.mean = colMeans()\ndata.means = (t(one) %*% data) / dim(data)[1]\ncolMeans(data)\n\n# 偏差分数(deviation scores): == scale\ndata.diff = data - one %*% data.means\ndata.cen = scale(data, scale=FALSE)\n\n\n### 随机矩阵\nset.seed(42)\n## 从data里面的数据随机取\ndata1 = matrix(sample(data), ncol = 4)\n\n### 协方差\ndata1.means = (t(one) %*% data1) / dim(data1)[1]\ndata1.diff = data1 - one %*% data1.means\ndata1.cov = (t(data1.diff) %*% data1.diff) / (dim(data1)[1] - 1)\n### 下面两行 == \nround(data1.cov, 2)\nround(cov(data1), 2)\n\n\ndiag(data1.cov)\n\n\n#########\nx = matrix(c(1,2,3,4), ncol=2)\n\n### 每个元素对应位置上相乘(纯相乘, 没有加的操作)\n### 1 2 1 3 1*1 2*3\n### * ---> \n### 3 4 2 4 3*2 4*4\nt(x)*x\n\n### 矩阵相乘%*%: 有乘的操作和加的操作\nt(x)%*%x\n### 交叉乘积(cross product):crossprod(X,Y)等同于t(X) %*% y,crossprod(X)等价于crossprod(X, X);\n### == t(x)%*%x\ncrossprod(x)\n\n### 外积: 把矩阵分成多个向量分别计算\nx%o%x\n\n### \ninstall.packages(\"LoopAnalyst\")\nlibrary(\"LoopAnalyst\")\n\nmake.adjoint(x)\n", "meta": {"hexsha": "21375060f506d799e35f02883fa7acc9c2e8a935", "size": 1884, "ext": "r", "lang": "R", "max_stars_repo_path": "R/learn/ILAR/class2.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/ILAR/class2.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/ILAR/class2.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": 18.4705882353, "max_line_length": 83, "alphanum_fraction": 0.5865180467, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.9173026505426832, "lm_q1q2_score": 0.8497008614075713}} {"text": "############\n## Funções auxiliares\n# Exemplo 9.1.18 De Groot\nLambda <- function(y, n, theta0, log = FALSE){\n l1 <- y * (log(n*theta0)-log(y))\n if(y==0) l1 <- 0\n l2 <- (n-y)*(log(n*(1-theta0))-log(n-y))\n if(y==n) l2 <- 0\n ans <- l1 + l2\n if(!log) ans <- exp(ans) \n return(ans)\n}\nLambda <- Vectorize(Lambda)\n#\nfindSet <- function(tab, level = alpha0){\n K <- nrow(tab)\n set <- NA\n accpr <- 0\n for(i in 1:K){\n accpr.tent <- accpr + tab$Pr[i]\n if(accpr.tent < level){\n accpr <- accpr.tent\n set <- c(set, tab$y[i])\n }else{\n next\n }\n }\n set <- na.omit(set)\n return(\n list(\n confidence_set = as.vector(set),\n test_size = accpr\n )\n )\n}\n\n############\nsample.size <- 10\np0 <- 0.01\nalpha0 <- 1/5\n\n# LRT: razão de verossimilhanças\n\ntabProb <- data.frame(y = 0:sample.size,\n Lambda = Lambda(y = 0:sample.size,\n n = sample.size,\n theta0 = p0),\n Pr = dbinom(x = 0:sample.size,\n size = sample.size, prob = p0))\nround(tabProb, 3)\n\nplot(0:sample.size, Lambda(y = 0:sample.size,\n n = sample.size,\n theta0 = p0), xlab = expression(y),\n ylab = expression(Lambda(y)), type = \"b\")\n\nConjuntoRejeicao <- findSet(tab = tabProb)\nConjuntoRejeicao\n\nTabRejeicao <- \ntabProb[match(ConjuntoRejeicao$confidence_set, tabProb$y), ]\n\n\nTabRejeicao[which.max(TabRejeicao$Lambda),]\n\n######\n\nsimula_e_testa <- function(N, theta0){\n Y <- rbinom(n = 1, size = N, prob = theta0)\n ttab <- data.frame(y = 0:N,\n Lambda = Lambda(0:N, n = N, theta0 = theta0),\n Pr = dbinom(x = 0:N, size = N, prob = theta0))\n test.set <- findSet(tab = ttab)\n the.test <- Y %in% test.set$confidence_set\n return(\n list(\n res = the.test,\n attained.size = test.set$test_size\n )\n )\n}\n\nM <- 10000\nresults <- sizes <- rep(NA, M)\nfor(i in 1:M){\n temp <- simula_e_testa(N = sample.size,\n theta0 = p0)\n results[i] <- temp$res\n sizes[i] <- temp$attained.siz\n} \nmean(results)\nmean(sizes)\n\n\n\n", "meta": {"hexsha": "adbbf33a64c1c8949504c173f43d25681848f358", "size": 2146, "ext": "r", "lang": "R", "max_stars_repo_path": "code/LRT_binomial.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/LRT_binomial.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/LRT_binomial.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": 22.3541666667, "max_line_length": 67, "alphanum_fraction": 0.5200372787, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.8991213718636754, "lm_q1q2_score": 0.8496649402006646}} {"text": "mle <- function(x) max(x)/2 # W1\nunbiased <- function(x) mle(x) * (2*n+2)/(2*n +1) # W2, unbiased\nf_M <- function(t) n/theta * (t/theta - 1)^(n-1) \nf_M <- Vectorize(f_M)\n####\ntheta <- pi^2/6\nn <- 2\nM <- 10000\n####\ndata.sets <- matrix(runif(n = n*M, min = theta, max = 2*theta),\n ncol = n, nrow = M)\n\nW1 <- apply(data.sets, 1, mle)\nhist(W1, probability = TRUE)\nmean(W1)\n(2*n +1)/(2*(n+1)) * theta ## the actual E[W1]\ntheta\nvar(W1)\n( VarW1 <- theta^2/4 * ((4*n^2 + 8*n + 2)/(n^2 + 3*n + 2) - ((2*n +1)/(n+1))^2) )\n( biasW1 <- (1-(2*n +1)/(2*n+2))* theta )\nVarW1 + biasW1^2 ## MSE W1\n\nW2 <- apply(data.sets, 1, unbiased)\nhist(W2, probability = TRUE)\nmean(W2)\ntheta\nvar(W2) ## MSE W2\n## E[W1] = c* theta => W2 = W1/c => Var(W2) = Var(W1)/c^2\n## c = 1-biasW1/theta\n(1-biasW1/theta)^-2 * VarW1\n\n\n# ### Extra\n# eccdf <- function(x)\n# {\n# x <- sort(x)\n# n <- length(x)\n# if (n < 1)\n# stop(\"'x' must have 1 or more non-missing values\")\n# vals <- sort(unique(x))\n# rval <- approxfun(vals, 1-cumsum(tabulate(match(x, vals)))/n, #[CHANGED]\n# method = \"constant\", yleft = 1, yright = 0, f = 0, ties = \"ordered\")\n# class(rval) <- c(\"eccdf\", \"stepfun\", class(rval)) #[CHANGED]\n# attr(rval, \"call\") <- sys.call()\n# rval\n# }\n# \n# Ff2 <- function(y) 1- (y/theta - 1)^n\n# \n# Ms <- apply(data.sets, 1, max)\n# mean(Ms)\n# plot(eccdf(Ms))\n# curve(Ff2, theta, 2*theta, lwd = 2, col = 2, lty = 2, add = TRUE)\n# \n# \n# (2*n + 1)/(n + 1) * theta\n# n/(n + 1)* theta\n# \n# var(Ms)\n", "meta": {"hexsha": "a84b36d2efc4f4d238420a73f0cea772c368c00b", "size": 1511, "ext": "r", "lang": "R", "max_stars_repo_path": "code/estimadores_uniforme_theta_2theta.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/estimadores_uniforme_theta_2theta.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/estimadores_uniforme_theta_2theta.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.1833333333, "max_line_length": 90, "alphanum_fraction": 0.5208471211, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361156361018, "lm_q2_score": 0.8840392909114836, "lm_q1q2_score": 0.8489969956883268}} {"text": "# Example : 1 Chapter : 6.2 Page No: 299\r\n# Diagonilizing a Matrix and Power of matrix computed from power of its diagonal matrix\r\nA<-matrix(c(1,0,5,6),ncol=2)\r\nlambda<-eigen(A)$values\r\nS<-eigen(A)$vectors\r\nS<-round(S)\r\nS1<-solve(S)\r\nDiag_matrix<-round(S1%*%A%*%S)\r\nprint(\"Diagonal Matrix is \")\r\nprint(Diag_matrix)\r\nA2<-A%*%A\r\nprint(\"The square of matrix\")\r\nprint(A2)\r\nprint(\"The Power of matrix can also be computed from its diagonal matrix as follows\")\r\nA2_diag<-S%*%Diag_matrix%*%Diag_matrix%*%S1\r\nprint(\"The square of matrix computed from its diagonal matrix\")\r\nprint(A2_diag)\r\n#The answer may slightly vary due to rounding off values\r\n#The answers provided in the text book may vary because of the computation process\r\n#Both answers are correct , here it is taken -Ax+b=0 , In the text book it is considered as Ax-b=0", "meta": {"hexsha": "42b08faede3eb471911e7756f1a071f8f6549ffc", "size": 830, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.2.1/Ex6.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/CH6/EX6.2.1/Ex6.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/CH6/EX6.2.1/Ex6.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": 41.5, "max_line_length": 98, "alphanum_fraction": 0.7228915663, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.8757869884059267, "lm_q1q2_score": 0.8489215219609834}} {"text": "\nk <- 31\nmu <- 6\nstd <- 0.22\nn <- 1000000\nv <- c()\n\nfor(i in 1:n){\n rand_draw <- rnorm(k, mean = mu, sd = std)\n bool <- ifelse(rand_draw > 6, 1, 0)\n bool <- sum(bool) >= ceiling(0.52*k)\n v <- c(v, bool)\n}\nprint(sum(v)/n) #part 2\n\n# https://www.reddit.com/r/AskStatistics/comments/cewvps/normal_distribution_help/\n# I'm not sure where to begin with this problem; am I able to calculate this by hand, or am I supposed to use R-commander or something? Thanks.\n\n# The weights of cans of Ocean brand tuna are supposed to have a net weight of 6.0 ounces. The manufacturer tells you that the net weight is actually a Normal random variable with a mean of 6 ounces and a standard deviation of 0.22 ounces. Suppose that you draw a random sample of 31 such cans.\n\n# Part i) Using the information about the distribution of the net weight given by the manufacturer, find the probability that the mean weight of the sample is less than 5.98 ounces. (Please carry answers to at least six decimal places in intermediate steps. Give your final answer to the nearest three decimal places).\n\n# Probability (as a proportion) = ?\n\n# Part ii) Using the Normal approximation, which of the following is the probability that more than 52 % of the sampled cans are overweight (i.e., the net weight exceeds 6 ounces)?\n\n# A. 0.4119B. 0.5881C. 0.987D. 0.013E. 0.4557\n\n\npnorm(5.98, mean = mu, sd = std) #part 1\n\n", "meta": {"hexsha": "84a6d03c3ee4ffc75a03108e9c18f3a00897af2d", "size": 1395, "ext": "r", "lang": "R", "max_stars_repo_path": "RedditQuestion07-18-19.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": "RedditQuestion07-18-19.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": "RedditQuestion07-18-19.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": 43.59375, "max_line_length": 318, "alphanum_fraction": 0.7189964158, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.9086178981700931, "lm_q1q2_score": 0.8481319399222053}} {"text": "# Example : 4.3B Chapter : 4.3 Page No: 226\r\n# Fit a Parabola\r\nsolution<-function(A,b){\r\n ATA<-t(A)%*%A\r\n ATb<-t(A)%*%b\r\n xhat<-solve(ATA,ATb)\r\n return(xhat)\r\n}\r\nfit_parabola<-function(D){\r\n num_of_points<-nrow(D)\r\n t<-c()\r\n for(i in 1:num_of_points){\r\n t<-c(t,1)\r\n }\r\n t<-c(t,D[,1])\r\n t<-c(t,D[,1]*D[,1])\r\n A<-matrix(c(t),ncol=3)\r\n b<-D[,2]\r\n b<-matrix(c(b),ncol=1)\r\n x<-solution(A,b)# The system has no solution, we need to find the best solution \r\n return(x)\r\n}\r\nt<-c(-2,-1,0,1,2)\r\nb<-c(0,0,1,0,0)\r\nData<-matrix(c(t,b),ncol=2)\r\nx<-fit_parabola(Data)\r\nC<-x[1]\r\nD<-x[2]\r\nE<-x[3]\r\nprint(paste(\"The best Parabola that fitt in is b= \",C,\"+\",D,\"t+\",E,\"t2\"))\r\n#The answer may slightly vary due to rounding off values.", "meta": {"hexsha": "33ed77c2bd845414722ffdf87e187e1dd9050788", "size": 739, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.3.b/Ex4_4.3B.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.3.b/Ex4_4.3B.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.3.b/Ex4_4.3B.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.8387096774, "max_line_length": 83, "alphanum_fraction": 0.5656292287, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239907775086, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.8480646176259679}} {"text": "is_in <- function(x, l, u){\n below <- x >= l\n above <- x <= u\n result <- as.logical(below * above)\n return(result)\n}\n\nget_ci <- function(x, gamma = 0.95){\n n <- length(x)\n cc <- qt(p = (1+gamma)/2, df = n-1)\n x_bar <- mean(x)\n sigma_prime <- sqrt(var(x))\n Z <- cc*sigma_prime/sqrt(n)\n A <- x_bar - Z\n B <- x_bar + Z\n return(\n data.frame(xbar = x_bar, lwr = A, upr = B)\n )\n}\n\nget_ci_fixedVar <- function(x, v, gamma = 0.95){\n n <- length(x)\n zz <- qnorm(p = (1+gamma)/2)\n x_bar <- mean(x)\n Z <- zz*sqrt(v/n)\n A <- x_bar - Z\n B <- x_bar + Z\n return(\n data.frame(xbar = x_bar, lwr = A, upr = B)\n )\n}\n#####\nmu <- 42\nsigma_sq <- 30^2\nn <- 5# 919 \nM <- 5000\n\namostras <- matrix(rnorm(n*M, mean = mu,\n sd = sqrt(sigma_sq)),\n ncol = n, nrow = M)\n\nhist(amostras[1, ])\nget_ci(amostras[1, ])\n\nintervalos <- data.frame(mean = rep(NA, M),\n L = rep(NA, M),\n U = rep(NA, M),\n contem = rep(NA, M))\n\nfor( i in 1:M){\n intervalos[i, 1:3] <- get_ci(amostras[i, ])\n intervalos$contem[i] <- is_in(x = mu,\n l = intervalos[i, 2], \n u = intervalos[i, 3])\n}\nintervalos <- data.frame(amostra = 1:M, intervalos)\n\ntail(intervalos)\n\nmean(intervalos$contem)\n\n######## Variancia conhecida\n\nintervalos.vc <- data.frame(mean = rep(NA, M),\n L = rep(NA, M),\n U = rep(NA, M),\n contem = rep(NA, M))\n\nfor( i in 1:M){\n intervalos.vc[i, 1:3] <- get_ci_fixedVar(amostras[i, ], v = sigma_sq)\n intervalos.vc$contem[i] <- is_in(x = mu,\n l = intervalos.vc[i, 2], \n u = intervalos.vc[i, 3])\n}\nintervalos.vc <- data.frame(amostra = 1:M, intervalos.vc)\n\ntail(intervalos.vc)\nmean(intervalos.vc$contem)\n\n\n##### Plots\nlibrary(ggplot2)\n\n\np1 <- ggplot() + \n geom_pointrange(data = intervalos,\n mapping = aes(x = amostra, y = mean,\n ymin = L, ymax = U, colour = contem)) +\n geom_hline(yintercept = mu, linetype = \"longdash\") +\n ggtitle(\"Variância desconhecida\") +\n theme_bw(base_size = 20)\n\n\np2 <- ggplot() + \n geom_pointrange(data = intervalos.vc,\n mapping = aes(x = amostra, y = mean,\n ymin = L, ymax = U, colour = contem)) +\n geom_hline(yintercept = mu, linetype = \"longdash\") +\n ggtitle(\"Variância conhecida\") +\n theme_bw(base_size = 20)\n\n\np1 \np2 \n# gridExtra::grid.arrange(p1, p2, ncol=2)\n\nlarguras.desc <- intervalos$U-intervalos$L\nlarguras.vc <- intervalos.vc$U-intervalos.vc$L\n\nhist(larguras.desc, probability = TRUE)\nabline(v = larguras.vc[1], lwd = 3, lty = 2)\n\nmean(larguras.desc)\nlarguras.vc[1]\n", "meta": {"hexsha": "e146f9e74454d1c3a4416d29b2ecd3537396c69f", "size": 2792, "ext": "r", "lang": "R", "max_stars_repo_path": "code/IC_normal_cobertura.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/IC_normal_cobertura.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/IC_normal_cobertura.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": 24.2782608696, "max_line_length": 71, "alphanum_fraction": 0.520773639, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.8933094131553264, "lm_q1q2_score": 0.8476767259628332}} {"text": "# Example : 4.2A Chapter : 4.2 Page No: 213\r\n# Projection onto the line and onto the plane\r\n\r\nprojection_line<-function(a,b){\r\n p<-((sum(a*b))/(sum(a*a)))*a\r\n e<-b-p\r\n print(\"The projection vector is \")\r\n print(p)\r\n print(\"The error vector is \")\r\n print(e)\r\n}\r\n\r\nprojection_plane<-function(A,b){\r\n b<-matrix(c(b),ncol=1)\r\n ATA<-t(A)%*%A\r\n ATA1<-solve(ATA)\r\n P<-A%*%ATA1\r\n P<-P%*%t(A)\r\n p<-P%*%b\r\n e<-b-p\r\n print(\"The projection vector is \")\r\n print(p)\r\n print(\"The error vector is \")\r\n print(e)\r\n}\r\n\r\nb<-c(3,4,4)\r\na<-c(2,2,1)\r\nprojection_line(a,b)\r\nA<-matrix(c(a,1,0,0),ncol=2)\r\nprojection_plane(A,b)\r\n#The answer may slightly vary due to rounding off values", "meta": {"hexsha": "9d44f4f5491f7d91b926a6fa2f2113c440bafe3f", "size": 683, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.2.a/Ex4_4.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/CH4/EX4.2.a/Ex4_4.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/CH4/EX4.2.a/Ex4_4.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": 21.34375, "max_line_length": 58, "alphanum_fraction": 0.5915080527, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995742876884, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.8475544430967379}} {"text": "# Idea behind the KS test for this problem:\n# The KS test is a hypothesis test used to determine if a sample of \n# data came from a specific probability distribution,\n# though theoretically this test only works for continuous distributions. \n# The test works by comparing the CDF for a \n# given reference distribution to the empirical CDF for the sample of data.\n# In this setting, under the null hypothesis of misses occurring at random, \n# the notes (locations) of the misses can be\n# modeled with a discrete uniform distribution.\n\n\nks=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 misses = which(song==1) # determines the locations/indices of misses and stores those in the vector \"misses\"\n # which(song==1) returns a vector indicating which on which notes (indices) a miss occurs\n\n n_misses = length(misses) # number of misses in a song (basically the sample size for the sample being tested)\n\n # empirical cdf is really just number of misses at or before the current miss on note i divided by the total number of misses\n\n e_cdf = 1:n_misses/n_misses # a vector holding the empirical cdf evaluated at each miss (each index in misses)\n # Note that for the first miss (entry in misses) the e_cdf is 1/n_misses, it is 2/n_misses for the second,..., n_misses/n_misses=1 for the last\n\n # the reference cdf for a discrete uniform is F(x) = x/(# of possible values); here that will be the length of the song\n\n n = length(song)\n\n r_cdf = misses/n # a vector that stores the reference cdf evaluated at the location of each miss\n\n # to calculate the KS test statistic subtract the empirical and reference cdfs for each note (and take the absolute value of that difference)\n # the test stat is the largest one of these absolute differences\n ks_ts = max(abs(e_cdf-r_cdf))\n\n return(ks_ts) # return the KS test statistic\n\n}\n\n# Hypothesis test based on the KS test method\nks_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\n\ttest_stat = ks(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] = ks(song_tmp)\n\t}\n\t\n\tpval = sum(tstar_b > test_stat)/B\n\t\n\treturn(pval)\n}\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)\nks(songA)\nks_test(songA,5000)\n\n\nsongB = c(0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,0,0)\nks(songB)\nks_test(songB,5000)", "meta": {"hexsha": "0d0c9ab4976e89e5246315fa7074a13732b79f73", "size": 2711, "ext": "r", "lang": "R", "max_stars_repo_path": "GHSupplementaryFiles/AppendixC/ks_gh.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/ks_gh.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/ks_gh.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": 37.6527777778, "max_line_length": 146, "alphanum_fraction": 0.7226115824, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943774, "lm_q2_score": 0.8757869965109765, "lm_q1q2_score": 0.8472453210023928}} {"text": "N <- 30\ntrue_beta <- c(10, -3, 0, 8, 0, 0, 0, 0, 0)\n\nx <- runif(N, -2, 2)\nX <- cbind(rep(1, N), x, x^2, x^3, x^4, x^5, x^6, x^7, x^8)\nmatplot(X, t='l')\n\nsigma <- 10\neps <- rnorm(N, mean = 0, sd = sigma)\ny <- X %*% true_beta + eps\nplot(y,t='l')\n\nmodel <- lm(y~., data=data.frame(X[,2:ncol(X)]))\nbeta_hat <- model$coefficients\n\nplot( beta_hat, t='o', col=2, pch='x')\nlines(true_beta, t='o', col=1)\n\n# Prior precision\ndimension <- length(true_beta)\nlambda <- 0.1*diag(0.1, dimension, dimension)\n\n# Posterior covariance\nposterior_sigma <- sigma^2 * solve(t(X) %*% X + sigma^2 * lambda)\nposterior_beta <- sigma^(-2) * as.vector(posterior_sigma %*% (t(X) %*% y))\n\nt <- seq(-2,2,0.01)\nT <- cbind(rep(1, N), t, t^2, t^3, t^4, t^5, t^6, t^7, t^8)\nplot(x,y, xlim=c(-2,2), ylim=range(y, T%*%true_beta))\nlines(t,T%*%true_beta, col='black', lwd=3)\nlines(t,T%*%beta_hat, col='blue', lwd=3)\nlines(t,T%*%posterior_beta, col='red', lwd=3)\nlegend('topleft', c('True function', 'OLS estimate', 'Bayesian estimate'), col=c('black','blue','red'), lwd=3)\n\npred_sigma <- sqrt(sigma^2 + apply((T%*%posterior_sigma)*T, MARGIN=1, FUN=sum))\nupper_bound <- T%*%posterior_beta + qnorm(0.95)*pred_sigma\nlower_bound <- T%*%posterior_beta - qnorm(0.95)*pred_sigma\n\nplot(c(0,0),xlim=c(-2,2), ylim=range(y,lower_bound,upper_bound),col='white')\npolygon( c(t,rev(t)), c(upper_bound,rev(lower_bound)), col='grey', border=NA)\npoints(x,y)\nlines(t,T%*%true_beta, col='black', lwd=3)\nlines(t,T%*%beta_hat, col='blue', lwd=3)\nlines(t,T%*%posterior_beta, col='red', lwd=3)\nlegend('topleft', c('True function', 'OLS estimate', 'Bayesian estimate'), col=c('black','blue','red'), lwd=3)\n", "meta": {"hexsha": "4d68a31df90abcb1926e267b381d37fe6ab7fb3d", "size": 1646, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 06/overfit.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 06/overfit.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 06/overfit.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": 35.7826086957, "max_line_length": 110, "alphanum_fraction": 0.6263669502, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650672, "lm_q2_score": 0.8872046011730965, "lm_q1q2_score": 0.8469675807406987}} {"text": "# Suppose we are giving two students a multiple-choice exam with 40 questions, \n# where each question has four choices. We don't know how much the students\n# have studied for this exam, but we think that they will do better than just\n# guessing randomly. \n# 1) What are the parameters of interest?\n# 2) What is our likelihood?\n# 3) What prior should we use?\n# 4) What is the prior probability P(theta>.25)? P(theta>.5)? P(theta>.8)?\n# 5) Suppose the first student gets 33 questions right. What is the posterior\n# distribution for theta1? P(theta1>.25)? P(theta1>.5)? P(theta1>.8)?\n# What is a 95% posterior credible interval for theta1?\n# 6) Suppose the second student gets 24 questions right. What is the posterior\n# distribution for theta2? P(theta2>.25)? P(theta2>.5)? P(theta2>.8)?\n# What is a 95% posterior credible interval for theta2?\n# 7) What is the posterior probability that theta1>theta2, i.e., that the \n# first student has a better chance of getting a question right than\n# the second student?\n\n############\n# Solutions:\n\n# 1) Parameters of interest are theta1=true probability the first student\n# will answer a question correctly, and theta2=true probability the second\n# student will answer a question correctly.\n\n# 2) Likelihood is Binomial(40, theta), if we assume that each question is \n# independent and that the probability a student gets each question right \n# is the same for all questions for that student.\n\n# 3) The conjugate prior is a beta prior. Plot the density with dbeta.\ntheta=seq(from=0,to=1,by=.01)\nplot(theta,dbeta(theta,1,1),type=\"l\")\nplot(theta,dbeta(theta,4,2),type=\"l\")\nplot(theta,dbeta(theta,8,4),type=\"l\")\n\n# 4) Find probabilities using the pbeta function.\n1-pbeta(.25,8,4)\n1-pbeta(.5,8,4)\n1-pbeta(.8,8,4)\n\n# 5) Posterior is Beta(8+33,4+40-33) = Beta(41,11)\n41/(41+11) # posterior mean\n33/40 # MLE\n\nlines(theta,dbeta(theta,41,11))\n\n# plot posterior first to get the right scale on the y-axis\nplot(theta,dbeta(theta,41,11),type=\"l\")\nlines(theta,dbeta(theta,8,4),lty=2)\n# plot likelihood\nlines(theta,dbinom(33,size=40,p=theta),lty=3)\n# plot scaled likelihood\nlines(theta,44*dbinom(33,size=40,p=theta),lty=3)\n\n# posterior probabilities\n1-pbeta(.25,41,11)\n1-pbeta(.5,41,11)\n1-pbeta(.8,41,11)\n\n# equal-tailed 95% credible interval\nqbeta(.025,41,11)\nqbeta(.975,41,11)\n\n# 6) Posterior is Beta(8+24,4+40-24) = Beta(32,20)\n32/(32+20) # posterior mean\n24/40 # MLE\n\nplot(theta,dbeta(theta,32,20),type=\"l\")\nlines(theta,dbeta(theta,8,4),lty=2)\nlines(theta,44*dbinom(24,size=40,p=theta),lty=3)\n\n1-pbeta(.25,32,20)\n1-pbeta(.5,32,20)\n1-pbeta(.8,32,20)\n\nqbeta(.025,32,20)\nqbeta(.975,32,20)\n\n# 7) Estimate by simulation: draw 1,000 samples from each and see how often \n# we observe theta1>theta2\n\ntheta1=rbeta(1000,41,11)\ntheta2=rbeta(1000,32,20)\nmean(theta1>theta2)\n\n\n# Note for other distributions:\n# dgamma,pgamma,qgamma,rgamma\n# dnorm,pnorm,qnorm,rnorm\n", "meta": {"hexsha": "1c4184d37d6a917d0883faab2b32df824a4c0772", "size": 2927, "ext": "r", "lang": "R", "max_stars_repo_path": "Baisian analysis basics/L7_binomial.R.r", "max_stars_repo_name": "erv4gen/DS-RStats", "max_stars_repo_head_hexsha": "4440e50f57d4579094bee1bbb5ed68ce607ff4fd", "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": "Baisian analysis basics/L7_binomial.R.r", "max_issues_repo_name": "erv4gen/DS-RStats", "max_issues_repo_head_hexsha": "4440e50f57d4579094bee1bbb5ed68ce607ff4fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Baisian analysis basics/L7_binomial.R.r", "max_forks_repo_name": "erv4gen/DS-RStats", "max_forks_repo_head_hexsha": "4440e50f57d4579094bee1bbb5ed68ce607ff4fd", "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.5222222222, "max_line_length": 79, "alphanum_fraction": 0.712675094, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.8469207816270705}} {"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 01\n#\n#\n\nrm(list = ls())\n\nlibrary(ggplot2)\nlibrary(ca)\n\n# 1.\tConstruir la matriz\n\nN <- t(matrix(\n c(20,20,20,\n 40,10,40,\n 20,10,40),\n ncol=3\n))\nprint(N)\n\n\n# 2.\tConstruir las matrices F, Dr, Dc y las matrices de puntos fila y columna.\n\nF <- N / sum(N)\nprint(F)\n\nDr <- diag(rowSums(N) / sum(N))\nDc <- diag(colSums(N) / sum(N))\nprint(Dr)\nprint(Dc)\n\nPr <- solve(Dr) %*% F\nPc <- solve(Dc) %*% t(F)\nprint(Pr)\nprint(Pc)\n\n\n# 3. Calcular las distancias chi cuadrado entre los tres puntos fila\n\nd_chi_square <- function(x, y) (t(x - y) %*% solve(Dc) %*% (x - y))[1,1]\nD <- c(\n d_chi_square(Pr[1,],Pr[2,]),\n d_chi_square(Pr[1,],Pr[3,]),\n d_chi_square(Pr[2,],Pr[3,])\n)\nprint(D)\n\n\n# 4. Calcular el valor del estadístico chi cuadrado\n\nchi_value <- sum(\n (N - (rowSums(N) %*% t(colSums(N))) / sum(N)) ^ 2 /\n ((rowSums(N) %*% t(colSums(N))) / sum(N))\n)\nprint(chi_value)\n\npval <- pchisq(chi_value, df=4, lower.tail=FALSE)\nprint(pval)\n\n# 5. Calcular la inercia total como la suma ponderada de las distancias chi\n# cuadrado al centro de gravedad de los puntos fila y comprobar que es el\n# estadístico chi cuadrado dividido por n\n\nGc <- colSums(N) / sum(N)\nGr <- rowSums(N) / sum(N)\nprint(Gc)\nprint(Gr)\n\ndiag(t(t(Pr) - Gc) %*% solve(Dc) %*% t(t(t(Pr)-Gc))) %*% Gr\nG <- (diag(t(t(Pr) - Gc) %*% solve(Dc) %*% t(t(t(Pr)-Gc))) %*% Gr)[1,1]\nprint(G)\n\n\n# 6. Construir la matriz a diagonalizar, diagonalizarla calculando los\n# autovalores y autovectores unitarios\n\nX <- t(F) %*% solve(Dr) %*% F %*% solve(Dc)\nprint(X)\nX_eigenvec_1 <- eigen(X)$vectors\nX_eigenval <- eigen(X)$values\n\nprint(X_eigenval)\nnorm <- diag(t(X_eigenvec_1) %*% solve(Dc) %*% X_eigenvec_1)\nX_eigenvec <- t(t(X_eigenvec_1)/sqrt(norm))\nprint(X_eigenvec)\n\n# 7. Calcular los factores y las proyecciones de los puntos fila sobre los ejes\n\n\nfact <- solve(Dc) %*% X_eigenvec\nprint(fact)\n\nProyec_r <- Pr %*% fact\nprint(Proyec_r)\n\n\n# 8. Calcular las distancias euclídeas entre las proyecciones y compararlas con\n# las del punto 3\n\nd_euclidean <- function(x, y) sum( (x / rowSums(F) - y / rowSums(F))^2)\nprint(d_euclidean(Pr[2,], Pr[3,]))\nprint(d_chi_square(Pr[2,], Pr[3,]))\n\n\n# 9. Calcular los factores y las proyecciones de los puntos columna sobre los\n# ejes\n\nProyec_c = t(sqrt(X_eigenval) * t(fact))\n\n\n# 10. Efectuar una representación conjunta de las proyecciones de filas y\n# columnas\n\nProyec_r_df <- as.data.frame(Proyec_r[,2:3])\nProyec_c_df <- as.data.frame(Proyec_c[,2:3])\nrownames(Proyec_r_df)<-c(\"J\",\"ME\",\"M\")\nrownames(Proyec_c_df)<-c(\"A\",\"B\",\"C\")\nProyec_df<-rbind(Proyec_r_df,Proyec_c_df)\n\n\nggplot(data = Proyec_df, aes(x = V1, y = V2, label=rownames(Proyec_df))) +\n geom_text(colour = \"red\", size = 6)\n\n#\n# Comprobación de resultados con libreria CA\n#\n\nN_f <- as.data.frame.matrix(N)\ncolnames(N_f) <- c(\"c1\", \"c2\", \"c3\")\nrownames(N_f) <- c(\"r1\", \"r2\", \"r3\")\n\nfit <- ca(N_f)\nsummary(fit)\nplot(fit)\n", "meta": {"hexsha": "d5db6b1cbc47e8848bd56831f10fb1f7060440e9", "size": 3118, "ext": "r", "lang": "R", "max_stars_repo_path": "data-analysis/correspondence-analysis/practice-01/practice-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": "data-analysis/correspondence-analysis/practice-01/practice-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": "data-analysis/correspondence-analysis/practice-01/practice-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": 22.1134751773, "max_line_length": 79, "alphanum_fraction": 0.6613213598, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436405, "lm_q2_score": 0.8856314677809304, "lm_q1q2_score": 0.846060686439461}} {"text": "#' Generates data from `K` multivariate normal data populations, where each\n#' population (class) has a covariance matrix consisting of block-diagonal\n#' autocorrelation matrices.\n#'\n#' This function generates `K` multivariate normal data sets, where each\n#' class is generated with a constant mean vector and a covariance matrix\n#' consisting of block-diagonal autocorrelation matrices. The data are returned\n#' as a single matrix `x` along with a vector of class labels `y` that\n#' indicates class membership.\n#'\n#' For simplicity, we assume that a class mean vector is constant for each\n#' feature. That is, we assume that the mean vector of the \\eqn{k}th class is\n#' \\eqn{c_k * j_p}, where \\eqn{j_p} is a \\eqn{p \\times 1} vector of ones and\n#' \\eqn{c_k} is a real scalar.\n#'\n#' The \\eqn{k}th class covariance matrix is defined as\n#' \\deqn{\\Sigma_k = \\Sigma^{(\\rho)} \\oplus \\Sigma^{(-\\rho)} \\oplus \\ldots\n#' \\oplus \\Sigma^{(\\rho)},} where \\eqn{\\oplus} denotes the direct sum and the\n#' \\eqn{(i,j)}th entry of \\eqn{\\Sigma^{(\\rho)}} is\n#' \\deqn{\\Sigma_{ij}^{(\\rho)} = \\{ \\rho^{|i - j|} \\}.}\n#'\n#' The matrix \\eqn{\\Sigma^{(\\rho)}} is referred to as a block. Its dimensions\n#' are provided in the `block_size` argument, and the number of blocks are\n#' specified in the `num_blocks` argument.\n#'\n#' Each matrix \\eqn{\\Sigma_k} is generated by the\n#' [cov_block_autocorrelation()] function.\n#'\n#' The number of classes `K` is determined with lazy evaluation as the\n#' length of `n`.\n#'\n#' The number of features `p` is computed as \\code{block_size * num_blocks}.\n#'\n#' @importFrom mvtnorm rmvnorm\n#' @export\n#' @param n vector of the sample sizes of each class. The length of `n`\n#' determines the number of classes `K`.\n#' @param mu matrix containing the mean vectors for each class. Expected to have\n#' `p` rows and `K` columns.\n#' @param num_blocks the number of block matrices. See details.\n#' @param block_size the dimensions of the square block matrix. See details.\n#' @param rho vector of the values of the autocorrelation parameter for each\n#' class covariance matrix. Must equal the length of `n` (i.e., equal to\n#' `K`).\n#' @param sigma2 vector of the variance coefficients for each class covariance\n#' matrix. Must equal the length of `n` (i.e., equal to `K`).\n#' @return named list with elements:\n#' \\itemize{\n#' \\item `x`: matrix of observations with `n` rows and `p`\n#' columns\n#' \\item `y`: vector of class labels that indicates class membership for\n#' each observation (row) in `x`.\n#' }\n#' @examples\n#' # Generates data from K = 3 classes.\n#' means <- matrix(rep(1:3, each=9), ncol=3)\n#' data <- generate_blockdiag(n = c(15, 15, 15), block_size = 3, num_blocks = 3,\n#' rho = seq(.1, .9, length = 3), mu = means)\n#' data$x\n#' data$y\n#'\n#' # Generates data from K = 4 classes. Notice that we use specify a variance.\n#' means <- matrix(rep(1:4, each=9), ncol=4)\n#' data <- generate_blockdiag(n = c(15, 15, 15, 20), block_size = 3, num_blocks = 3,\n#' rho = seq(.1, .9, length = 4), mu = means)\n#' data$x\n#' data$y\ngenerate_blockdiag <- function(n, mu, num_blocks, block_size, rho,\n sigma2 = rep(1, K)) {\n n <- as.integer(n)\n block_size <- as.integer(block_size)\n num_blocks <- as.integer(num_blocks)\n p <- block_size * num_blocks\n rho <- as.numeric(rho)\n mu <- as.matrix(mu)\n\n K <- length(n)\n\n if (length(rho) != K) {\n rlang::abort(\"The length of 'rho' must equal the length of 'n'.\")\n } else if(nrow(mu) != p) {\n rlang::abort(\"The matrix 'mu' must have 'p' rows.\")\n } else if(ncol(mu) != K) {\n rlang::abort(\"The matrix 'mu' must have 'K' columns.\")\n }\n\n x <- lapply(seq_len(K), function(k) {\n if (n[k] > 0) {\n rmvnorm(n = n[k], mean = mu[, k],\n sigma = cov_block_autocorrelation(num_blocks = num_blocks,\n block_size = block_size, rho = rho[k], sigma2 = sigma2[k]))\n }\n })\n x <- do.call(rbind, x)\n y <- factor(rep(seq_along(n), n))\n\n list(x = x, y = y)\n}\n\n#' Generates a \\eqn{p \\times p} block-diagonal covariance matrix with\n#' autocorrelated blocks.\n#'\n#' This function generates a \\eqn{p \\times p} covariance matrix with\n#' autocorrelated blocks. The autocorrelation parameter is `rho`.\n#' There are `num_blocks` blocks each with size, `block_size`.\n#' The variance, `sigma2`, is constant for each feature and defaulted to 1.\n#'\n#' The autocorrelated covariance matrix is defined as:\n#' \\deqn{\\Sigma = \\Sigma^{(\\rho)} \\oplus \\Sigma^{(-\\rho)} \\oplus \\ldots \\oplus\n#' \\Sigma^{(\\rho)},} where \\eqn{\\oplus} denotes the direct sum and the\n#' \\eqn{(i,j)}th entry of \\eqn{\\Sigma^{(\\rho)}} is \\deqn{\\Sigma_{ij}^{(\\rho)} =\n#' \\{ \\rho^{|i - j|} \\}.}\n#'\n#' The matrix \\eqn{\\Sigma^{(\\rho)}} is the autocorrelated block discussed above.\n#'\n#' The value of `rho` must be such that \\eqn{|\\rho| < 1} to ensure that\n#' the covariance matrix is positive definite.\n#'\n#' The size of the resulting matrix is \\eqn{p \\times p}, where\n#' `p = num_blocks * block_size`.\n#'\n#' @export\n#' @importFrom bdsmatrix bdsmatrix\n#' @param num_blocks the number of blocks in the covariance matrix\n#' @param block_size the size of each square block within the covariance matrix\n#' @param rho the autocorrelation parameter. Must be less than 1 in absolute\n#' value.\n#' @param sigma2 the variance of each feature\n#' @return autocorrelated covariance matrix\ncov_block_autocorrelation <- function(num_blocks, block_size, rho, sigma2 = 1) {\n cov_block <- cov_autocorrelation(p = block_size, rho = rho, sigma2 = sigma2)\n cov_block <- as.vector(cov_block)\n as.matrix(bdsmatrix(blocksize = rep(block_size, num_blocks),\n blocks = replicate(num_blocks, cov_block)))\n}\n\n#' Generates a \\eqn{p \\times p} autocorrelated covariance matrix\n#'\n#' This function generates a \\eqn{p \\times p} autocorrelated covariance matrix\n#' with autocorrelation parameter `rho`. The variance `sigma2` is\n#' constant for each feature and defaulted to 1.\n#'\n#' The autocorrelated covariance matrix is defined as:\n#' The \\eqn{(i,j)}th entry of the autocorrelated covariance matrix is defined as:\n#' \\eqn{\\rho^{|i - j|}}.\n#'\n#' The value of `rho` must be such that \\eqn{|\\rho| < 1} to ensure that\n#' the covariance matrix is positive definite.\n#'\n#' @export\n#' @param p the size of the covariance matrix\n#' @param rho the autocorrelation parameter. Must be less than 1 in absolute\n#' value.\n#' @param sigma2 the variance of each feature\n#' @return autocorrelated covariance matrix\ncov_autocorrelation <- function(p, rho, sigma2 = 1) {\n p <- as.integer(p)\n rho <- as.numeric(rho)\n sigma2 <- as.numeric(sigma2)\n\n if (abs(rho) >= 1) {\n rlang::abort(\"The value of 'rho' must be between (1 - p)^(-1) and 1, exclusively.\")\n }\n if (sigma2 <= 0) {\n rlang::abort(\"The value of 'sigma2' must be positive.\")\n }\n x <- diag(p)\n sigma2 * rho^abs(row(x) - col(x))\n}\n", "meta": {"hexsha": "5859f6626dcbea09d8744c6b4ef12f256d653ca0", "size": 6826, "ext": "r", "lang": "R", "max_stars_repo_path": "R/data-block-autocorrelation.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/data-block-autocorrelation.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/data-block-autocorrelation.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": 40.1529411765, "max_line_length": 87, "alphanum_fraction": 0.6692059771, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152282, "lm_q2_score": 0.8918110490322425, "lm_q1q2_score": 0.8455746903382465}} {"text": "delta_donald <- function(x){\n x[1]\n}\n#\ndelta_huguinho <- function(x){\n kH <- (n+3)/(2*n + 2)\n (1/kH)*min(x)\n}\n#\ndelta_zezinho <- function(x){\n kZ <- (3*n+1)/(2*n + 2)\n (1/kZ) * max(x)\n}\n#\ndelta_luisinho <- function(x){\n (min(x) + max(x))/2\n}\n#\ncomputa_vies_qdd <- function(deltas, theta){\n (mean(deltas) - theta)^2\n}\ncomputa_eqm <- function(deltas, theta){\n mean((deltas-theta)^2)\n}\n#\ntheta.vdd <- 10\nn <- 30\nM <- 1e5\namostras <- matrix(NA, ncol = n, nrow = M)\nfor (j in 1:M){\n amostras[j, ] <- runif(n = n, min = theta.vdd/2, max = (3/2)*theta.vdd)\n}\n\nDs <- apply(amostras, 1, delta_donald)\nHs <- apply(amostras, 1, delta_huguinho)\nZs <- apply(amostras, 1, delta_zezinho)\nLs <- apply(amostras, 1, delta_luisinho)\n\npar(mfrow = c(2, 2))\nhist(Ds, probability = TRUE, main = \"Pato Donald\",\n xlab = expression(delta[D]))\nabline(v = theta.vdd, lwd = 3, lty = 2)\nhist(Hs, probability = TRUE, main = \"Huguinho\",\n xlab = expression(delta[UH]))\nabline(v = theta.vdd, lwd = 3, lty = 2)\nhist(Zs, probability = TRUE, main = \"Zezinho\",\n xlab = expression(delta[UZ]))\nabline(v = theta.vdd, lwd = 3, lty = 2)\nhist(Ls, probability = TRUE, main = \"Luisinho\",\n xlab = expression(delta[L]))\nabline(v = theta.vdd, lwd = 3, lty = 2)\n\n###\n#### Variância\n# Donald\nvar(Ds)\ntheta.vdd^2/12\n# Huguinho\nvar(Hs)\n(4*n)/((n+3)^2*(n+2)) * theta.vdd^2\n# Zezinho\nvar(Zs)\n(4*n)/((3*n+1)^2*(n+2)) * theta.vdd^2\n# Luisinho\nvar(Ls)\n1/(2*(n+1)*(n+2)) * theta.vdd^2\n\n#### Viés\n# Donald\ncomputa_vies_qdd(Ds, theta.vdd)\n# Huguinho\ncomputa_vies_qdd(Hs, theta.vdd)\n# Zezinho\ncomputa_vies_qdd(Zs, theta.vdd)\n# Luisinho\ncomputa_vies_qdd(Ls, theta.vdd)\n\n#### EQM\n# Donald\ncomputa_eqm(Ds, theta.vdd)\ntheta.vdd^2/3\n# Huguinho\ncomputa_eqm(Hs, theta.vdd)\n(4*n)/((n+3)^2*(n+2)) * theta.vdd^2\n# Zezinho\ncomputa_eqm(Zs, theta.vdd)\n(4*n)/((3*n+1)^2*(n+2)) * theta.vdd^2\n# Luisinho\ncomputa_eqm(Ls, theta.vdd)\n1/(2*(n+1)*(n+2)) * theta.vdd^2\n\n#### Agora, o Tio Patinhas\n\nvar_alpha <- function(x){\n a <- (n+3)/(2*n + 2)\n b <- (3*n+1)/(2*n + 2)\n gamma <- theta.vdd^2 /( (n+1)^2*(n+2))\n obj <- (n*x^2)/b^2+(2*(1-x)*x)/(a*b)+(n*(1-x)^2)/a^2\n return(gamma*obj)\n}\n\npar(mfrow = c(1, 1))\ncurve(var_alpha)\n\n\nalpha_opt <- function(n){\n a <- (n+3)/(2*n + 2)\n b <- (3*n+1)/(2*n + 2)\n (b^2*n-a*b)/((b^2+a^2)*n-2*a*b)\n}\nalpha.opt <- alpha_opt(n)\n\nalpha.numopt <- optimise(var_alpha, interval = c(0, 1))\n\nalpha.numopt$minimum\nalpha.opt\n(1/2) * (n/(n^2-n+1))\n\ndelta_patinhas <- function(x, w){\n (1-w)*delta_huguinho(x) + w*delta_zezinho(x)\n} \n \nPs <- apply(amostras, 1,\n function(x) delta_patinhas(x = x, w = alpha.opt))\n\ncomputa_eqm(Ps, theta.vdd)\nvar(Ps)\nvar_alpha(alpha.opt)\nvar_alpha(alpha.numopt$minimum)\n2/((5*n+3)*(n+2))*theta.vdd^2\n\ncomputa_vies_qdd(Ps, theta.vdd)\n\npar(mfrow = c(1, 2))\nhist(Zs, probability = TRUE, main = \"Zezinho\",\n xlab = expression(delta[UZ]))\nabline(v = theta.vdd, lwd = 3, lty = 2)\nhist(Ps, probability = TRUE, main = \"Tio Patinhas\",\n xlab = expression(delta[P]))\nabline(v = theta.vdd, lwd = 3, lty = 2)\n\n###\n## Comparando todo mundo em relação ao EQM\n# Donald\ntheta.vdd^2/3\n# Huguinho\n(4*n)/((n+3)^2*(n+2)) * theta.vdd^2\n# Zezinho\n(4*n)/((3*n+1)^2*(n+2)) * theta.vdd^2\n# Luisinho\n1/(2*(n+1)*(n+2)) * theta.vdd^2\n# Tio Patinhas\n2/((5*n+3)*(n+2))*theta.vdd^2", "meta": {"hexsha": "885f6ad69a1a30c5bef6ecd21afa3ff7ac857304", "size": 3274, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Q_4_P1_2021.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/Q_4_P1_2021.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/Q_4_P1_2021.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": 21.3986928105, "max_line_length": 73, "alphanum_fraction": 0.6017104459, "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.8426806849765571}} {"text": "#########################################################################\n## Problema Amostre 12 variaveis aleatorias independentes uniforme(0, 1) \n## Defina x_bar = soma(X)/12\n## Quanto vale Pr(|x_bar - 0.5| < 0.1)?\n## Para a solução exata, notar que a soma de n v.a.s U(0, 1) tem \n### distribuição Irwin-Hall (https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution)\n### e que Pr(|X - 1/2| < 0.1) = Pr(0.4 < X < 0.6) = Pr(X<0.6)-Pr(X<0.4).\n#########################################################################\n## Funcoes auxiliares\nIW_cdf <- function(x, n){\n if(x > n) return(1)\n ks <- 0:floor(x)\n vals <- sapply(ks, function(k) (-1)^k * choose(n, k) * (x-k)^n)\n S <- sum(vals)\n ans <- exp(log(S)-lfactorial(n))\n return(ans)\n}\nIW_cdf <- Vectorize(IW_cdf)\n######################\n## Usando TCL\naproximacao.normal <- pnorm(1.2)-pnorm(-1.2)\n\n## Usando Monte Carlo\nM <- 1E6\namostras <- matrix(NA, nrow = M, ncol = 12)\nfor(i in 1:M) amostras[i, ] <- runif(12)\n\nmedias <- apply(amostras, 1, mean)\n\naproximacao.monte.carlo <- mean(abs(medias-0.5) < 0.1)\n\n## Exato\ncurve(IW_cdf(x, n = 12), 0, 12)\nabline(v = 0.4 * 12, lwd = 2, lty = 2)\nabline(v = 0.6 * 12, lwd = 2, lty = 2)\n\nexato <- IW_cdf(0.6*12, n = 12)-IW_cdf(0.4*12, n = 12)\n\n#### Comparando\naproximacao.normal\naproximacao.monte.carlo\nexato\n\naproximacao.normal - exato\naproximacao.monte.carlo - exato", "meta": {"hexsha": "5feb987d65e8360afdfcd6ac75bc5ea182c56077", "size": 1365, "ext": "r", "lang": "R", "max_stars_repo_path": "code/DeGroot_example_6.3.3.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/DeGroot_example_6.3.3.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/DeGroot_example_6.3.3.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": 30.3333333333, "max_line_length": 91, "alphanum_fraction": 0.5509157509, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527684, "lm_q2_score": 0.9005297847831081, "lm_q1q2_score": 0.8423073993201129}} {"text": "### 主成分分析の例\n### - Nutritional and Marketing Information on US Cereals\n\n## パッケージの読み込み\nrequire(MASS) \nrequire(tidyverse) \nrequire(ggfortify)\nrequire(GGally)\n\n## データの読み込み (\"MASS::UScereal\"を用いる)\ndata(UScereal) # データの読み込み\n\n## データの内容を確認\nhelp(UScereal) # 内容の詳細を表示\n## print(UScereal) # 全データの表示\nhead(UScereal,n=5) # 最初の5個を表示\ntail(UScereal,n=5) # 最後の5個を表示\n\n## 解析に使う変数だけ取り出しデータを整理しておく\nidx <- which(sapply(UScereal,is.numeric)) # 量的変数のindexを取得\nidx <- idx[names(idx)!=\"shelf\"] # \"shelf\"を取り除く\n\n## データの散布図: 図(a)\nggscatmat(UScereal, columns=idx, color=\"mfr\", alpha=.8)\n## ## ggpairsでの例\n## ggpairs(UScereal, columns=idx, lower=list(mapping=aes(colour=mfr)))\n\n## 主成分分析 (データの正規化(scale.=TRUE)による違いを見る)\nmodel1 <- prcomp(~ ., data=dplyr::select(UScereal,idx), scale.=FALSE) \nmodel2 <- prcomp(~ ., data=dplyr::select(UScereal,idx), scale.=TRUE) \n\n## 寄与率の違いを表示\nsummary(model1)\nsummary(model2)\n## 寄与率 (正規化なし): 図(b)\nplot(model1, col=\"lightblue\", main=\"PCA without scaling\")\n## 寄与率 (正規化あり): 図(c)\nplot(model2, col=\"lightblue\", main=\"PCA with scaling\")\n\n## biplotによる表示\n## 主成分得点 (正規化なし): 図(d)\nautoplot(model1, data=UScereal,\n colour=\"mfr\", shape=19, size=\"calories\", alpha=.2,\n label=TRUE, label.size=4,\n loadings=TRUE, loadings.colour=\"blue\",\n loadings.label=TRUE, loadings.label.size=6,\n loadings.label.colour=\"blue\", \n main=\"PCA without scaling\")\n## 主成分得点 (正規化あり): 図(e)\nautoplot(model2, data=UScereal,\n colour=\"mfr\", shape=19, size=\"calories\", alpha=.2,\n label=TRUE, label.size=4,\n loadings=TRUE, loadings.colour=\"blue\",\n loadings.label=TRUE, loadings.label.size=6,\n loadings.label.colour=\"blue\", \n main=\"PCA with scaling\")\n## 主成分得点 (中心部拡大): 図(f)\nautoplot(model2, data=UScereal, colour=\"mfr\", shape=FALSE,\n label=TRUE, label.size=4,\n xlim=c(-.15,.15), ylim=c(-.15,.15),\n main=\"PCA (zoomed)\")\n## ## optionの例\n## autoplot(model2, data=UScereal,\n## colour=\"mfr\", shape=19, size=\"calories\",\n## frame=TRUE, frame.type=\"norm\", label=FALSE,\n## loadings=TRUE, loadings.colour=\"blue\",\n## loadings.label=TRUE, loadings.label.size=5,\n## loadings.label.colour=\"blue\", \n## main=\"PCA with oval frames\")\n", "meta": {"hexsha": "021fd2dc4584df8906ef64410a8af532dd7db4ed", "size": 2253, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/code/p-uscereal.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/p-uscereal.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/p-uscereal.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.1857142857, "max_line_length": 70, "alphanum_fraction": 0.6409232135, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.8420255890985535}} {"text": "\n\n##' @title\n##' Negative log loss, also known as logarithmic loss or cross-entropy loss.\n##'\n##'\n##' @description\n##'\n##' Log loss is an effective metric for measuring the performance of a\n##' classification model where the prediction output is a probability value\n##' between 0 and 1.\n##'\n##' Log loss quantifies the accuracy of a classifier by penalizing false\n##' classifications. A perfect model would have a log loss of 0. Log loss\n##' increases as the predicted probability diverges from the actual label. This\n##' is the cost function used in logistic regression and neural networks.\n##'\n##' \\code{mtr_log_loss} computes the elementwise log loss between two numeric\n##' vectors. While \\code{mtr_mean_log_loss} computes the average log loss\n##' between two numeric vectors\n##'\n##'\n##' @note\n##' The logarithm used is the natural logarithm (base-e)\n##'\n##'\n##' @param actual \\code{[numeric]} Ground truth binary numeric vector containing\n##' 1 for the positive class and 0 for the negative class.\n##' @param predicted \\code{[numeric]} A vector of estimated probabilities.\n##' @param eps \\code{[numeric]} In case of predicted probability is equal zero\n##' or one, log loss is undefined, so probabilities are clipped to max(eps,\n##' min(1 - eps, p)). The default value of eps is 1e-15.\n##' @return A numeric vector output\n##' @name logloss\n##' @seealso \\code{\\link{mtr_brier_score}}\n##' @author An Chu\n##' @include helper-functions.r\n##' @examples\n##'\n##' ## log loss for scalar inputs, see how log loss is converging to zero\n##' mtr_log_loss(1, 0.1)\n##' mtr_log_loss(1, 0.5)\n##' mtr_log_loss(1, 0.9)\n##' mtr_log_loss(1, 1)\n##'\n##' ## sample data\n##' act <- c(0, 1, 1, 0, 0)\n##' pred <- c(0.12, 0.45, 0.9, 0.3, 0.4)\n##'\n##' ## log loss vector\n##' mtr_log_loss(act, pred)\n##' mtr_cross_entropy(act, pred)\n##'\n##' ## mean log loss\n##' mtr_mean_log_loss(act, pred)\n##' mtr_mean_cross_entropy(act, pred)\n##'\n##'\n##' @export\nmtr_log_loss <- function(actual, predicted, eps = 1e-15) {\n\n check_equal_length(actual, predicted)\n check_binary(actual)\n\n predicted <- clip(predicted, mi = eps, ma = 1 - eps)\n\n logloss <- (-1) * (actual * log(predicted) + (1 - actual) * log(1 - predicted))\n\n logloss\n}\n\n\n##' @rdname logloss\n##' @export\nmtr_cross_entropy <- mtr_log_loss\n\n\n\n##' @rdname logloss\n##' @export\nmtr_mean_log_loss <- function(actual, predicted, eps = 1e-15) {\n\n logloss <- mtr_log_loss(actual, predicted, eps = eps)\n\n mean(logloss)\n}\n\n\n##' @rdname logloss\n##' @export\nmtr_mean_cross_entropy <- mtr_mean_log_loss\n", "meta": {"hexsha": "e6aaba17744f5f61593b2ff37b267024c1ec2479", "size": 2546, "ext": "r", "lang": "R", "max_stars_repo_path": "R/log-loss.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/log-loss.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/log-loss.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": 27.6739130435, "max_line_length": 83, "alphanum_fraction": 0.6767478397, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.9019206844384594, "lm_q1q2_score": 0.8418805526192299}} {"text": "# Packages used : pracma\r\n# To install pracma,type following in command line while connected to internet\r\n# install.packages(\"pracma\") \r\n# package can be included by command \" library(pracma) \"\r\n# for more information about pracma visit https://cran.r-project.org/web/packages/pracma/index.html\r\n\r\n# Example : 4.1B Chapter : 4.1 Page No: 201\r\n# Null space Basis of a plane subspace\r\nlibrary(pracma)\r\nnullspacebasis <- function(A){\r\n R<-rref(A)\r\n m<-nrow(A)\r\n n<-ncol(A)\r\n pivotcol<-c() #vector to store the column numbers of pivot columns\r\n freecol<-c() #vector to store the column numbers of free columns\r\n i<-1\r\n j<-1\r\n \r\n # to find which columns are pivot and which are free\r\n while(i<=m & j<=n){\r\n if(R[i,j]==1){\r\n pivotcol<-c(pivotcol,j)\r\n i<-i+1\r\n j<-j+1\r\n }\r\n else{\r\n j<-j+1\r\n }\r\n }\r\n y<-length(pivotcol)\r\n freecol<-c(1:n)\r\n freecol<-freecol[!freecol%in%pivotcol]\r\n x<-length(freecol)\r\n N<-c()\r\n #find the basis for null space based on Row reduced echelon form of given matrix\r\n if(y==n){\r\n return(N)\r\n }\r\n for(i in 1:x){\r\n temp<-c(1:n)\r\n for(j in 1:x){\r\n temp[freecol[j]]<-0\r\n }\r\n temp[freecol[i]]<-1\r\n temp[freecol[i]]\r\n for(j in 1:y){\r\n temp[pivotcol[j]]<-R[j,freecol[i]]*-1\r\n }\r\n N<-c(N,temp)\r\n }\r\n N<-matrix(N,nrow=n,ncol=x)\r\n #Basis for the nullspace of given matrix\r\n return(N)\r\n}\r\n\r\nA<-matrix(c(1,-3,-4),ncol=3)\r\nprint(\"Given Plane x-3y-4z=0 is a null space of following 1*3 matrix\")\r\nprint(A)\r\n#to make matrix copatible for our function\r\nA<-rbind(A,c(0,0,0),c(0,0,0))\r\nN<-nullspacebasis(A)\r\nprint(\"SPecial solutions or nullspace basis of given plane subspace is\")\r\nprint(N)\r\nA<-A[-c(2,3),]\r\nprint(\"Row space is \")\r\nprint(A)\r\ntemp<-cbind(N,c(1,-3,-4))\r\nx<-c(1,1,-1)\r\nprint(\"vector 6,4,5 is split into vn + vs as 1 of each vector in nullspace basis and -1 of rowspace basis\")\r\nv<-temp%*%x\r\nprint(v)", "meta": {"hexsha": "21632e7631b79a96c0b506de368a170eb4b62fd8", "size": 1913, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.1.b/Ex4_4.1B.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.b/Ex4_4.1B.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.b/Ex4_4.1B.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": 26.9436619718, "max_line_length": 108, "alphanum_fraction": 0.6157867224, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.9046505318875316, "lm_q1q2_score": 0.8417395592209671}} {"text": "## 2. Observed Data vs Expected Data ##\n\nfemale_diff <- (10771 - 16280.5) / 16280.5\nmale_diff <- (21790 - 16280.5) / 16280.5\n\n## 3. Dealing With Cancellation ##\n\nfemale_diff_sq <- (10771 - 16280.5)^2 / 16280.5\nmale_diff_sq <- (21790 - 16280.5)^2 / 16280.5\nsquared_diff_sum <- female_diff_sq + male_diff_sq\n\n## 5. Developing a null hypothesis ##\n\npvalue <- 1 - pchisq(3728, 1)\nreject_null <- TRUE\n\n## 6. Importance of sample size ##\n\npvalue <- 1 - pchisq(1.8, 1)\nreject_null <- FALSE\n\n## 7. Considering More Categories ##\n\nrace_chisq <- 0\nobserved <- c(27816, 3124, 1039, 311, 271)\nexpected <- c(26146.5, 3939.9, 944.3, 260.5, 1269.8)\n\nfor (i in 1:length(observed)) {\n E <- expected[i]\n O <- observed[i]\n race_chisq <- race_chisq + ((O - E)^2/E)\n}\n\n## 8. Adjusting The Distribution Under The Null ##\n\npvalue <- 1 - pchisq(785, 4)", "meta": {"hexsha": "703bda804300ea19ff778f4e7c2015494873e65e", "size": 837, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/5. Hypothesis Testing in R/3. Categorical Data and The Chi-Squared Test.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/5. Hypothesis Testing in R/3. Categorical Data and The Chi-Squared Test.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/5. Hypothesis Testing in R/3. Categorical Data and The Chi-Squared Test.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.25, "max_line_length": 52, "alphanum_fraction": 0.6451612903, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075744568837, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.8409563317683831}} {"text": "## 1. The Importance of Counting ##\n\nn_outcomes <- 6 * 6\n\np_six_six <- 1 / n_outcomes\np_five_five <- 1 / n_outcomes\np_not_five_five <- 1 - p_five_five\n\n## 2. Extending The Rule of Product ##\n\ntotal_outcomes <- 6 * 6 * 6 * 52\np_666_ace_diamonds <- 1 / total_outcomes\np_no_666_ace_diamonds <- 1 - p_666_ace_diamonds\n\n## 3. A More Concrete Example ##\n\ntotal_outcomes_4_pin <- 10^4 # 10 multiplied by itself 4 times\np_crack_4 <- 1 / total_outcomes_4_pin\n\ntotal_outcomes_6_pin <- 10^6 # 10 multiplied by itself 6 times\np_crack_6 <- 1/total_outcomes_6_pin\n\n## 4. With Replacement vs Without Replacement ##\n\nsize_num_4 <- 10 * 9 * 8 * 7\nsize_num_6 <- 10 * 9 * 8 * 7 * 6 * 5\n\n## 5. Permutations ##\n\nfactorial <- function(n) {\n final_product <- 1\n for (i in 1:n) {\n final_product = final_product * i\n }\n return(final_product)\n}\n\npermutations_1 <- factorial(6) # because there are 6 letters\npermutations_2 <- factorial(52)\n\n## 6. More About Permutations ##\n\nfactorial <- function(n) {\n final_product <- 1\n for (i in 1:n) {\n final_product = final_product * i\n }\n return(final_product)\n}\npermutation <- function(n, k) {\n return(factorial(n) / factorial(n - k))\n}\n\nperm_3_52 <- permutation(52,3)\nperm_4_20 <- permutation(20, 4)\n\n## 7. Sometimes Order Doesn't Matter ##\n\nfactorial <- function(n) {\n final_product <- 1 \n for (i in 1:n) {\n final_product <- final_product * i\n }\n return(final_product)\n}\n\npermutation <- function(n, k) {\n return(factorial(n) / factorial(n - k))\n}\nc <- permutation(52, 5) / factorial(5)\np_aces_7 <- 1/c\n\nc_lottery <- permutation(49,6) / factorial(6)\np_big_prize <- 1/c_lottery\n\n## 8. Combination Notation ##\n\nfactorial <- function(n) {\n final_product <- 1 \n for (i in 1:n) {\n final_product <- final_product * i\n }\n return(final_product)\n}\ncombination <- function(n, k) {\n return(factorial(n)/(factorial(n - k) * factorial(k)))\n}\n\nc_18 <- combination(34, 18)\n\np_Y <- 1/c_18\np_non_Y <- 1 - p_Y", "meta": {"hexsha": "6c8caaa80685a9e442e0a9376800aa3891fb79c4", "size": 1991, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/3. Probability Fundamentals in R/4. Permutations and Combinations.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/3. Probability Fundamentals in R/4. Permutations and Combinations.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/3. Probability Fundamentals in R/4. Permutations and Combinations.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.6413043478, "max_line_length": 62, "alphanum_fraction": 0.6504269211, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992960608886, "lm_q2_score": 0.868826777936422, "lm_q1q2_score": 0.8409368267635129}} {"text": "library(dslabs)\ndata(murders)\n\n# 1. Remake the temperature data frame, adding a line that converts the temperature from Fahrenheit to Celsius.\n\nfahrenheit <- c(35, 88, 42, 84, 81, 30)\ncelsius <- (5/9) * (fahrenheit - 32)\ncity <- c(\"Beijing\", \"Lagos\", \"Paris\", \"Rio de Janeiro\",\n \"San Juan\", \"Toronto\")\ncity_temps <- data.frame(name = city, temperature = celsius)\ncity_temps\n\n# 2. The Basel Problem: the sum of 1 + 1/2² + 1/3² + ... + 1/100² equals to aproximately π²/6\n\nrange <- (1:100)\nbasel <- sum(1/(range^2))\nbasel\n\n# 3. Compute the per 100,000 murder rate for each state and store it in the object murder_rate. Then compute the average murder rate for the US using the function mean. What is the average?\n\npopulation <- murders$population\ntotal <- murders$total\nmurder_rate <- (total / population) * 100000\navg_murder_rate = mean(murder_rate)\navg_murder_rate\n\n# Now we can build a data frame with state and murder rate, from lowest to highest\n\nstates <- murders$state\nindex <- order(murder_rate)\nmurder_df = data.frame(state = states[index], murder_rate = murder_rate[index])\nmurder_df\n\n # We can do the same, but ordering highest to lowest (in this case that's more convenient!)\n\nindex <- order(murder_rate, decreasing=TRUE)\nmurder_df = data.frame(state = states[index], murder_rate = murder_rate[index])\nmurder_df\n", "meta": {"hexsha": "1b115a48ad953370df1cd80e24c8015aa3f51d6e", "size": 1330, "ext": "r", "lang": "R", "max_stars_repo_path": "edx/harvardx_ph125/chapter_02/02-12_exercises.r", "max_stars_repo_name": "pbittencourt/datasciencestudies", "max_stars_repo_head_hexsha": "85f0b2a4366fe7c6daa5628ed4bd2994355963c0", "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": "edx/harvardx_ph125/chapter_02/02-12_exercises.r", "max_issues_repo_name": "pbittencourt/datasciencestudies", "max_issues_repo_head_hexsha": "85f0b2a4366fe7c6daa5628ed4bd2994355963c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "edx/harvardx_ph125/chapter_02/02-12_exercises.r", "max_forks_repo_name": "pbittencourt/datasciencestudies", "max_forks_repo_head_hexsha": "85f0b2a4366fe7c6daa5628ed4bd2994355963c0", "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.1025641026, "max_line_length": 189, "alphanum_fraction": 0.7263157895, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142221377825, "lm_q2_score": 0.8824278587245936, "lm_q1q2_score": 0.8393143937529876}} {"text": "\r\nheat_loss <- c(86,80,77 , 78,84,75 ,33,38,43)\r\ntemperature <- c(81,81,81,79,79,79,38,38,38)\r\n\r\n# Apply the lm() function.\r\nrelation <- lm(heat_loss~temperature)\r\n\r\naov(relation)\r\n\r\nSSPexp=134\r\nSSresidual=894.5 #calculated in 11.10\r\nSSlack=SSresidual-SSPexp\r\n\r\nMSPexp=SSPexp/6\r\nMSlack=SSlack/1\r\n# test statistic\r\nF=MSlack/MSPexp\r\nprint(F)\r\nalpha=0.05\r\n\r\nfvalue=qf(1-alpha,df1 = 1,df2 = 6)\r\nif(F>fvalue){\r\n print(\" we reject H0 and conclude that there is significant lack of fit for a linear regression model\")\r\n}else{\r\n print(\"we do not reject H0 and conclude that there is no significant lack of fit for a linear regression model\")\r\n}\r\n", "meta": {"hexsha": "5f55af198a6c7c41f3d8e3a03d2273d0151726c3", "size": 641, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH11/EX11.11/Ex11_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/CH11/EX11.11/Ex11_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/CH11/EX11.11/Ex11_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": 23.7407407407, "max_line_length": 116, "alphanum_fraction": 0.7020280811, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791214, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.8390816940271976}} {"text": "##### Chapter 6: Regression Methods -------------------\n\n#### Part 1: Linear Regression -------------------\n\n## Understanding regression ----\n## Example: Space Shuttle Launch Data ----\nlaunch <- read.csv(\"challenger.csv\")\n\n# estimate beta manually\nb <- cov(launch$temperature, launch$distress_ct) / var(launch$temperature)\nb\n\n# estimate alpha manually\na <- mean(launch$distress_ct) - b * mean(launch$temperature)\na\n\n# calculate the correlation of launch data\nr <- cov(launch$temperature, launch$distress_ct) /\n (sd(launch$temperature) * sd(launch$distress_ct))\nr\ncor(launch$temperature, launch$distress_ct)\n\n# computing the slope using correlation\nr * (sd(launch$distress_ct) / sd(launch$temperature))\n\n# confirming the regression line using the lm function (not in text)\nmodel <- lm(distress_ct ~ temperature, data = launch)\nmodel\nsummary(model)\n\n# creating a simple multiple regression function\nreg <- function(y, x) {\n x <- as.matrix(x)\n x <- cbind(Intercept = 1, x)\n b <- solve(t(x) %*% x) %*% t(x) %*% y\n colnames(b) <- \"estimate\"\n print(b)\n}\n\n# examine the launch data\nstr(launch)\n\n# test regression model with simple linear regression\nreg(y = launch$distress_ct, x = launch[2])\n\n# use regression model with multiple regression\nreg(y = launch$distress_ct, x = launch[2:4])\n\n# confirming the multiple regression result using the lm function (not in text)\nmodel <- lm(distress_ct ~ temperature + pressure + launch_id, data = launch)\nmodel\n\n## Example: Predicting Medical Expenses ----\n## Step 2: Exploring and preparing the data ----\ninsurance <- read.csv(\"insurance.csv\", stringsAsFactors = TRUE)\nstr(insurance)\n\n# summarize the charges variable\nsummary(insurance$expenses)\n\n# histogram of insurance charges\nhist(insurance$expenses)\n\n# table of region\ntable(insurance$region)\n\n# exploring relationships among features: correlation matrix\ncor(insurance[c(\"age\", \"bmi\", \"children\", \"expenses\")])\n\n# visualing relationships among features: scatterplot matrix\npairs(insurance[c(\"age\", \"bmi\", \"children\", \"expenses\")])\n\n# more informative scatterplot matrix\nlibrary(psych)\npairs.panels(insurance[c(\"age\", \"bmi\", \"children\", \"expenses\")])\n\n## Step 3: Training a model on the data ----\nins_model <- lm(expenses ~ age + children + bmi + sex + smoker + region,\n data = insurance)\nins_model <- lm(expenses ~ ., data = insurance) # this is equivalent to above\n\n# see the estimated beta coefficients\nins_model\n\n## Step 4: Evaluating model performance ----\n# see more detail about the estimated beta coefficients\nsummary(ins_model)\n\n## Step 5: Improving model performance ----\n\n# add a higher-order \"age\" term\ninsurance$age2 <- insurance$age^2\n\n# add an indicator for BMI >= 30\ninsurance$bmi30 <- ifelse(insurance$bmi >= 30, 1, 0)\n\n# create final model\nins_model2 <- lm(expenses ~ age + age2 + children + bmi + sex +\n bmi30*smoker + region, data = insurance)\n\nsummary(ins_model2)\n\n#### Part 2: Regression Trees and Model Trees -------------------\n\n## Understanding regression trees and model trees ----\n## Example: Calculating SDR ----\n# set up the data\ntee <- c(1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 6, 7, 7, 7, 7)\nat1 <- c(1, 1, 1, 2, 2, 3, 4, 5, 5)\nat2 <- c(6, 6, 7, 7, 7, 7)\nbt1 <- c(1, 1, 1, 2, 2, 3, 4)\nbt2 <- c(5, 5, 6, 6, 7, 7, 7, 7)\n\n# compute the SDR\nsdr_a <- sd(tee) - (length(at1) / length(tee) * sd(at1) + length(at2) / length(tee) * sd(at2))\nsdr_b <- sd(tee) - (length(bt1) / length(tee) * sd(bt1) + length(bt2) / length(tee) * sd(bt2))\n\n# compare the SDR for each split\nsdr_a\nsdr_b\n\n## Example: Estimating Wine Quality ----\n## Step 2: Exploring and preparing the data ----\nwine <- read.csv(\"whitewines.csv\")\n\n# examine the wine data\nstr(wine)\n\n# the distribution of quality ratings\nhist(wine$quality)\n\n# summary statistics of the wine data\nsummary(wine)\n\nwine_train <- wine[1:3750, ]\nwine_test <- wine[3751:4898, ]\n\n## Step 3: Training a model on the data ----\n# regression tree using rpart\nlibrary(rpart)\nm.rpart <- rpart(quality ~ ., data = wine_train)\n\n# get basic information about the tree\nm.rpart\n\n# get more detailed information about the tree\nsummary(m.rpart)\n\n# use the rpart.plot package to create a visualization\nlibrary(rpart.plot)\n\n# a basic decision tree diagram\nrpart.plot(m.rpart, digits = 3)\n\n# a few adjustments to the diagram\nrpart.plot(m.rpart, digits = 4, fallen.leaves = TRUE, type = 3, extra = 101)\n\n## Step 4: Evaluate model performance ----\n\n# generate predictions for the testing dataset\np.rpart <- predict(m.rpart, wine_test)\n\n# compare the distribution of predicted values vs. actual values\nsummary(p.rpart)\nsummary(wine_test$quality)\n\n# compare the correlation\ncor(p.rpart, wine_test$quality)\n\n# function to calculate the mean absolute error\nMAE <- function(actual, predicted) {\n mean(abs(actual - predicted)) \n}\n\n# mean absolute error between predicted and actual values\nMAE(p.rpart, wine_test$quality)\n\n# mean absolute error between actual values and mean value\nmean(wine_train$quality) # result = 5.87\nMAE(5.87, wine_test$quality)\n\n## Step 5: Improving model performance ----\n# train a M5' Model Tree\nlibrary(RWeka)\nm.m5p <- M5P(quality ~ ., data = wine_train)\n\n# display the tree\nm.m5p\n\n# get a summary of the model's performance\nsummary(m.m5p)\n\n# generate predictions for the model\np.m5p <- predict(m.m5p, wine_test)\n\n# summary statistics about the predictions\nsummary(p.m5p)\n\n# correlation between the predicted and true values\ncor(p.m5p, wine_test$quality)\n\n# mean absolute error of predicted and true values\n# (uses a custom function defined above)\nMAE(wine_test$quality, p.m5p)\n", "meta": {"hexsha": "9090ce45cd729404f935e421706cfb99f854dc15", "size": 5561, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 06/MLwR_v2_06.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 06/MLwR_v2_06.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 06/MLwR_v2_06.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": 27.1268292683, "max_line_length": 94, "alphanum_fraction": 0.6996942996, "num_tokens": 1564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780479, "lm_q2_score": 0.8824278540866547, "lm_q1q2_score": 0.8380147007118427}} {"text": "#estimae sigma^2 and mu\n\n#mu: Normal\n#sigma: Inverse Gamma\n\nupdateMu = function(n, yBar, sig2, mu_0, sig2_0){\n sig2_1 = 1.0 / (n / sig2 + 1.0 / sig2_0)\n mu_1 = sig2_1 * (n * yBar / sig2 + mu_0 / sig2_0)\n rnorm(n=1, mean=mu_1, sd=sqrt(sig2_1))\n}\n\n\nupdateSig2 = function(n, y, nu, nu_0, beta_0){\n nu_1 = nu_0 + n / 2.0\n sumSq = sum( (y-nu)^2)\n beta_1 = beta_0 + sumSq / 2.0\n outGamma = rgamma(n=1, shape=nu_1, rate=beta_1)\n 1.0 / outGamma # inverse must be down manually \n}\n\ngibbs = function(y, nIter, init, prior){\n yBar = mean(y)\n n = length(y)\n\n muOut = numeric(nIter)\n sig2Out = numeric(nIter)\n \n muNow = init$mu\n\n # Gibs sampler \n for (i in 1:nIter){\n sig2Now = updateSig2(n=n, y=y, nu=muNow, nu_0=prior$nu_0, beta_0=prior$beta_0)\n muNow = updateMu(n=n, yBar=yBar, sig2=sig2Now, mu_0=prior$mu_0, sig2_0=prior$sig2_0)\n\n sig2Out[i] = sig2Now\n muOut[i] = muNow\n }\n cbind(mu=muOut, sig2=sig2Out)\n}\n\n\n#y = c(1.2, 1.4, -0.5, 0.3, 0.9, 2.3, 1.0, 0.1, 1.3, 1.9) \ny = c(-0.2, -1.5, -5.3, 0.3, -0.8, -2.2)\nn = length(y)\nyBar = mean(y)\n\nprior = list()\n\nprior$mu_0 = 1.0\nprior$sig2_0 = 1.0 #variance, prior confidence in mean \nprior$n_0 = 2.0\nprior$s2_0 = 1.0\nprior$nu_0 = prior$n_0 / 2.0\nprior$beta_0 = prior$n_0 * prior$s2_0 / 2.0\n\n\nhist(y, freq=FALSE, xlim=c(-1.0,3.0))\ncurve(dnorm(x=x, mean=prior$mu_0, sd=sqrt(prior$sig2_0)), lty=2, add=TRUE)\npoints(y, rep(0,n), pch=1)\npoints(yBar, 0, pch=19)\n\nset.seed(53)\n\ninit = list()\ninit$mu = 0.0\n\n\npost = gibbs(y=y,nIter=5000,init=init,prior=prior)\nhead(post)\ntail(post)\n\nlibrary(\"coda\")\nplot(as.mcmc(post))\n\nmean(post[,1])", "meta": {"hexsha": "7e29fa66f2a18a834e12d8898f0a56f3e1576a53", "size": 1643, "ext": "r", "lang": "R", "max_stars_repo_path": "montyCarlo/gibbsNormalLikelyhood.r", "max_stars_repo_name": "CharlieShelbourne/algos_practice", "max_stars_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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": "montyCarlo/gibbsNormalLikelyhood.r", "max_issues_repo_name": "CharlieShelbourne/algos_practice", "max_issues_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "montyCarlo/gibbsNormalLikelyhood.r", "max_forks_repo_name": "CharlieShelbourne/algos_practice", "max_forks_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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.9066666667, "max_line_length": 92, "alphanum_fraction": 0.6031649422, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.8377632848667192}} {"text": "yi=c(0,1,2,3,4,5,6,7)\r\nni=c(6,23,29,31,27,13,8,13)\r\nn=sum(ni)\r\nybar=sum(yi*ni)/sum(ni)\r\nprint(ybar)\r\n# ybar value in book is calculated wrong\r\n# The Poisson probabilities\r\nPyi=c(dpois(0,ybar),dpois(1,ybar),dpois(2,ybar),dpois(3,ybar),dpois(4,ybar),dpois(5,ybar),dpois(6,ybar),dpois(7,ybar))\r\nprint(Pyi)\r\n# Expected cell count\r\nEi=n*Pyi\r\nprint(Ei)\r\n\r\n# test statistic\r\ni=1\r\nX2=0\r\nwhile(i<9){\r\n X2=X2+(((ni[i]-Ei[i])^2)/Ei[i])\r\n i=i+1\r\n}\r\nprint(X2) # ans in book is calculate wrong\r\ndf=6\r\n\r\npvalue=pchisq(X2,df,lower.tail = FALSE)\r\nprint(pvalue)\r\n# as p-value <=.01 model is Poisson model provides an Unacceptable fit to data\r\n\r\n ", "meta": {"hexsha": "cad6b5f857aeb6be14b155ef5f49cc23d485ac6e", "size": 642, "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.11/Ex10_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/CH10/EX10.11/Ex10_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/CH10/EX10.11/Ex10_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": 22.9285714286, "max_line_length": 119, "alphanum_fraction": 0.6448598131, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748207, "lm_q2_score": 0.8705972801594706, "lm_q1q2_score": 0.8371087151312866}} {"text": "si=c(.1204,.1269,.1196,.1249,.1265)\r\n# data fom example 9.3\r\nFmax=max(si)^2/min(si)^2\r\nprint(Fmax)\r\n# four test statistic\r\nSSC1=.2097 # these value are computed in 9.3\r\nSSC2=.1297\r\nSSC3=.0037\r\nSSC4=.0217\r\nMSError=.0153\r\nF1=SSC1/MSError\r\nF2=SSC2/MSError\r\nF3=SSC3/MSError\r\nF4=SSC4/MSError\r\n\r\nprint(F1)\r\nprint(F2)\r\nprint(F3)\r\nprint(F4)\r\n\r\nalpha=0.05\r\ndf1=1\r\ndf2=25\r\nF_0.05_1_25=qf(1-alpha,df1,df2)\r\nprint(F_0.05_1_25)\r\n\r\n# we conclude that contrasts l1 and l2 were significantly\r\n#different from zero but contrasts l3 and l4 were not significantly different from zero.\r\n\r\n", "meta": {"hexsha": "63f2e1d5c08c20d7b51b63214847a8abe9c88539", "size": 569, "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.5/Ex9_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/CH9/EX9.5/Ex9_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/CH9/EX9.5/Ex9_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": 18.9666666667, "max_line_length": 89, "alphanum_fraction": 0.7117750439, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611563610179, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.8360878090865194}} {"text": "#Calculate the likelihood ratio----\nn<-10 #set total trials\nx<-8#set successes\nH0 <- .5 #specify one hypothesis you want to compare with the likihood ratio\nH1 <- .5 #specify another hypothesis you want to compare with the likihood ratio (you can use 1/20, or 0.05)\ndbinom(x,n,H0)/dbinom(x,n,H1) #Returns the likelihood ratio of H0 over H1\ndbinom(x,n,H1)/dbinom(x,n,H0) #Returns the likelihood ratio of H1 over H0\n\ntheta<- seq(0,1,len=100) #create theta variable, from 0 to 1\nlike <- dbinom(x,n,theta)\n#png(file=\"LikRatio.png\",width=4000,height=3000, , units = \"px\", res = 900)\nplot(theta,like,type='l',xlab=expression(theta), ylab='Likelihood', lwd=2)\npoints(H0,dbinom(x,n,H0))\npoints(H1,dbinom(x,n,H1))\nsegments(H0, dbinom(x,n,H0), x/n, dbinom(x,n,H0), lty=2, lwd=2)\nsegments(H1, dbinom(x,n,H1), x/n, dbinom(x,n,H1), lty=2, lwd=2)\nsegments(x/n, dbinom(x,n,H0), x/n, dbinom(x,n,H1), lwd=2)\ntitle(paste('Likelihood Ratio H0/H1:',round(dbinom(x,n,H0)/dbinom(x,n,H1),digits=2),\" Likelihood Ratio H1/H0:\",round(dbinom(x,n,H1)/dbinom(x,n,H0),digits=2)))\n#dev.off()\n\n#? Daniel Lakens, 2016. \n# This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. https://creativecommons.org/licenses/by-nc-sa/4.0/", "meta": {"hexsha": "b8a34e8be0bce43498b34b068e1163c11bbc5da3", "size": 1249, "ext": "r", "lang": "R", "max_stars_repo_path": "week_2/CalculateLikelihoodRatio.r", "max_stars_repo_name": "whobbes/improving_statistical_inferences", "max_stars_repo_head_hexsha": "b7ffcc3df42a8257753e533a7b27fa32ee666622", "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": "week_2/CalculateLikelihoodRatio.r", "max_issues_repo_name": "whobbes/improving_statistical_inferences", "max_issues_repo_head_hexsha": "b7ffcc3df42a8257753e533a7b27fa32ee666622", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week_2/CalculateLikelihoodRatio.r", "max_forks_repo_name": "whobbes/improving_statistical_inferences", "max_forks_repo_head_hexsha": "b7ffcc3df42a8257753e533a7b27fa32ee666622", "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": 56.7727272727, "max_line_length": 163, "alphanum_fraction": 0.7141713371, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075777163566, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.8359048284094054}} {"text": "## 1. Individual Values ##\n\nlibrary(readr)\n# Heads up that the following instruction can generate a column specification warnings, you can ignore that.\n# These warnings are related to that `readr` has misguidedly guessed the type of values in the column `Pool QC`. \n# To avoid this warning we can manually specify the type of this column the `col_types` parameter.\nhouses <- read_tsv('AmesHousing_1.txt', col_types = cols(`Pool QC` = col_character())) \n\nstandard_deviation <- function(vector) {\n distances <- (vector - mean(vector))**2 \n sqrt(sum(distances) / length(distances) )\n}\n\nst_dev <- standard_deviation(houses$SalePrice)\nmean <- mean(houses$SalePrice)\n\nlibrary(ggplot2)\n#ggplot(data = houses,\n# aes(x = SalePrice)) +\n# geom_density(alpha = 0.1, \n# color='blue', \n# fill='blue') +\n# geom_vline(aes(xintercept = mean, \n# color = 'Mean'), \n# size = 1.2 ) +\n# geom_vline(aes(xintercept = 220000, \n# color = '220,000'), \n# size = 1.2 ) +\n# geom_vline(aes(xintercept = mean+st_dev, \n# color = 'Standard deviation'), \n# size = 1.2 ) +\n# scale_y_continuous(labels = scales::comma) +\n# scale_x_continuous(labels = scales::comma, \n# lim = c(min(houses$SalePrice), \n# max(houses$SalePrice))) +\n# scale_colour_manual(values = c(\"Mean\"=\"black\", \n# \"220,000\"=\"red\", \n# \"Standard deviation\"=\"orange\"), \n# name = \"\") +\n# theme_bw() + \n# theme(legend.position='top') +\n# xlab(\"Sale Price\") + \n# ylab(\"Density\")\nvery_expensive <- FALSE\n\n## 2. Number of Standard Deviations ##\n\nstandard_deviation <- function(vector) {\n distances <- (vector - mean(vector))**2 \n sqrt(sum(distances) / length(distances) )\n}\ndistance <- 220000 - mean(houses$SalePrice)\nst_devs_away <- distance / standard_deviation(houses$SalePrice)\n\n## 3. Z-scores ##\n\nmin_val <- min(houses$SalePrice)\nmean_val <- mean(houses$SalePrice)\nmax_val <- max(houses$SalePrice) \n\nstandard_deviation <- function(vector) {\n distances <- (vector - mean(vector))**2 \n sqrt(sum(distances) / length(distances) )\n}\nz_score <- function(value, vector, bessel = FALSE) {\n mean <- mean(vector)\n \n st_dev <- ifelse(!bessel, sd(vector), standard_deviation(vector)) \n \n (value - mean) / st_dev\n}\n\nmin_z <- z_score(min_val, houses$SalePrice)\nmean_z <- z_score(mean_val, houses$SalePrice)\nmax_z <- z_score(max_val, houses$SalePrice)\n\n## 4. Locating Values in Different Distributions ##\n\nstandard_deviation <- function(vector) {\n distances <- (vector - mean(vector))**2 \n sqrt(sum(distances) / length(distances) )\n}\n\nz_score <- function(value, vector, bessel = FALSE) {\n mean <- mean(vector)\n \n st_dev <- ifelse(!bessel, sd(vector), standard_deviation(vector)) \n \n (value - mean) / st_dev\n}\n\ntarget_neighborhoods <- c('NAmes', 'CollgCr', 'OldTown', 'Edwards', 'Somerst')\n# Filter only the interesting locations from the dataset\n# Group by neighborhood and find the z-score for 200000 for every location\n# Sort the result by zcore\nlibrary(dplyr)\nhouses %>%\n filter(Neighborhood %in% target_neighborhoods) %>%\n group_by(Neighborhood) %>%\n summarise(zscore = abs(z_score(200000, SalePrice))) %>%\n ungroup() %>%\n arrange(zscore)\n\n# Find the location with the z-score closest to 0\nbest_investment <- 'College Creek'\n\n## 5. Transforming Distributions ##\n\nstandard_deviation <- function(vector) {\n distances <- (vector - mean(vector))**2 \n sqrt(sum(distances) / length(distances) )\n}\n\nlibrary(dplyr)\nhouses <- houses %>%\n mutate(z_prices = (SalePrice - mean(SalePrice)) / standard_deviation(SalePrice))\nz_mean_price <- mean(houses$z_prices)\nz_stdev_price <- standard_deviation(houses$z_prices)\n\n# Transforming 'Lot Area'\nhouses <- houses %>%\n mutate(z_area = (`Lot Area` - mean(`Lot Area`)) / standard_deviation(`Lot Area`))\n\nz_mean_area <- mean(houses$z_area)\nz_stdev_area <- standard_deviation(houses$z_area)\n\n## 6. The Standard Distribution ##\n\npopulation <- c(0, 8, 0, 8)\n\nstandard_deviation <- function(vector) {\n distances <- (vector - mean(vector))**2 \n sqrt(sum(distances) / length(distances) )\n}\nmean_pop <- mean(population)\nstdev_pop <- standard_deviation(population)\n\nstandardized_pop <- (population - mean_pop) / stdev_pop\n\nmean_z <- mean(standardized_pop)\nstdev_z <- standard_deviation(standardized_pop)\n\n## 7. Standardizing Samples ##\n\nsample <- c(0, 8, 0, 8)\n\nx_bar <- mean(sample)\ns <- sd(sample)\n\nstandardized_sample <- (sample - x_bar) / s\nstdev_sample <- sd(standardized_sample)\n\n## 8. Using Standardization for Comparisons ##\n\nstandard_deviation <- function(vector) {\n distances <- (vector - mean(vector))**2 \n sqrt(sum(distances) / length(distances) )\n}\n\nhouses <- houses %>%\n mutate(index_1 = SalePrice/ 100000 + 37) %>%\n mutate(index_1 = replace(index_1, row_number() %% 2 != 0, NA_real_) ) %>%\n mutate(index_2 = SalePrice/ 90000 - 2.8) %>%\n mutate(index_2 = replace(index_2, row_number() %% 2 == 0, NA_real_) )\n\nmean_index_1 <- mean(houses$index_1, na.rm = T)\nmean_index_2 <- mean(houses$index_2, na.rm = T)\n\nsd_index_1 <- standard_deviation(na.omit(houses$index_1))\nsd_index_2 <- standard_deviation(na.omit(houses$index_2))\nhouses <- houses %>%\n mutate(z_1 = (index_1 - mean_index_1) / sd_index_1 ) %>%\n mutate(z_2 = (index_2 - mean_index_2) / sd_index_2 ) \n\nhead(houses %>% select(z_1, z_2), 2)\n\nbetter <- 'first'\n\n## 9. Converting Back from Z-scores ##\n\nhouses_merged <- bind_rows(houses_1,houses_2) %>%\n mutate(z_1 = tidyr::replace_na(z_1,0)) %>%\n mutate(z_2 = tidyr::replace_na(z_2,0)) %>%\n mutate(z_merged = z_1 + z_2)\nmean <- 50\nst_dev <- 10\nhouses_merged <- houses_merged %>%\n mutate(transformed = z_merged * st_dev + mean)\n \nmean_transformed <- mean(houses_merged$transformed)\nstdev_transformed <- standard_deviation(houses_merged$transformed)", "meta": {"hexsha": "17d5e24c3615eb9fd2d3c7242e3030608eb80241", "size": 6135, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/2. Statistics Intermediate in R Averages and Variability/5. Z-scores.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/2. Statistics Intermediate in R Averages and Variability/5. Z-scores.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/2. Statistics Intermediate in R Averages and Variability/5. Z-scores.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": 32.1204188482, "max_line_length": 113, "alphanum_fraction": 0.6425427873, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762052772658, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.8355662166323331}} {"text": "#pontos\nx1 = c(0,1,2,3)\ny1 = c(2,-2,2,0)\nplot (x1,y1,\"b\", main=\"Pontos\")\n\n#bezier\nt = seq(0,1,0.01)\n\nx2 = ((1-t)^3 * x1[1] + 3*t*(1-t)^2 * x1[2] + 3*t^2 * (1-t)*x1[3] + t^3*x1[4])\ny2 = ((1-t)^3 * y1[1] + 3*t*(1-t)^2 * y1[2] + 3*t^2 * (1-t)*y1[3] + t^3*y1[4])\n\nplot(x2, y2,type=\"l\",xlim=c(0,3), ylim=c(-2,2), main=\"Bezier\")\n\nplot (x1,y1,type=\"b\",xlim=c(0,3), ylim=c(-2,2),col=\"blue\", main=\"Pontos+Bezier\")\nlines (x2,y2, type=\"l\", col=\"red\")\n\n#pesos\np1 = (1-t)^3\np2 = 3*t*(1-t)^2 \np3 = 3*t^2*(1-t)\np4 = t^3\n\nplot(t, p1, \"l\", c(0,1), c(0,1), col=\"cyan\", main=\"Pesos\")\nlines(t, p2, \"l\", col=\"orange\")\nlines(t, p3, \"l\", col=\"green\")\nlines(t, p4, \"l\", col=\"red\")", "meta": {"hexsha": "c2c7d1c4c2419a0a0d2bc2c7be1cde689e835c5e", "size": 656, "ext": "r", "lang": "R", "max_stars_repo_path": "bezier.r", "max_stars_repo_name": "luanrivello/curvas", "max_stars_repo_head_hexsha": "507dc6f5e0f0b36833e56e19a21667a83643278d", "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": "bezier.r", "max_issues_repo_name": "luanrivello/curvas", "max_issues_repo_head_hexsha": "507dc6f5e0f0b36833e56e19a21667a83643278d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bezier.r", "max_forks_repo_name": "luanrivello/curvas", "max_forks_repo_head_hexsha": "507dc6f5e0f0b36833e56e19a21667a83643278d", "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.2307692308, "max_line_length": 80, "alphanum_fraction": 0.4984756098, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517469248845, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.8351708652000258}} {"text": "### 多次元尺度構成法の例\n### - 人工データによる計量的・非計量的方法の比較\n\n## パッケージの読み込み\nrequire(MASS)\nrequire(lattice)\n\n## 3次元データの作成 (格子状に作成してサンプルする)\n## 3次元空間内に2次元の曲面を埋め込む\ns <- seq(0, 1.5*pi, length=1000)\nmydata <- do.call('rbind',\n lapply(s, function(t){\n data.frame(\n X=seq(sin(t), -sin(t), length=100), \n Y=seq(cos(t), -cos(t), length=100), \n Z=t)}\n )\n )\nmydata$class <- rep(1:8, each=100*1000/8)\nmydata <- mydata[sample(nrow(mydata),400),]\n\n## 人工データの視覚化: 図(a-d)\nfor (i in seq(20,80,by=20)) { \n print(cloud(Z ~ X + Y, data=mydata, groups=class,\n screen=list(z=i, x=-80),distance=.6))\n}\n\n## ユークリッド距離の計算\ndst <- dist(mydata[,1:3])\n\n## 計量的方法: 図(e)\nplot(cmdscale(dst),col=rainbow(8)[mydata$class],\n xlab=\"axis 1\", ylab=\"axis 2\",\n main=\"Torgerson's MDS\")\n## 曲面のねじれのため一部の構造がつぶれている\n\n## 非計量的方法: 図(f)\nplot(isoMDS(dst)$points,col=rainbow(8)[mydata$class],\n xlab=\"axis 1\", ylab=\"axis 2\",\n main=\"Kruskal's MDS\")\n## 曲面を平面上に引き伸ばした尺度が構成されている\n", "meta": {"hexsha": "049d08935bf3bca1d73df7fafb3e6ef5143136b8", "size": 1084, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/code/m-compare.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/m-compare.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/m-compare.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": 25.8095238095, "max_line_length": 62, "alphanum_fraction": 0.5424354244, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723353, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.8350787820482115}} {"text": "bioclite(\"multtest\")\r\nlibrary(multtest)\r\ndata(golub)\r\n\r\n##Principal component analysis\r\neigen(cor(golub))$values[1:5]\r\np<-ncol(data);n<-row(data);nboot<-1000\r\neigenvalues <- array(dim=c(nboot,p))\r\nfor (i in 1:nboot){dat.star <-data[sample(1:n,replace=TRUE),] \r\neigenvalues[i,] <- eigen(cor(dat.star))$values}\r\nfor (j in 1:p) print(quantile(eigenvalues[,j],c(0.025,0.975)))\r\nfor (j in 1:5) cat(j,as.numeric(quantile(eigenvalues[,j], + c(0.025,0.975))),\"\\n\" ) \r\nsum(eigen(cor(golub))$values[1:2])/38*100 \r\neigen(cor(golub))$vec[,1:2]\r\npca < princomp(golub, center = TRUE, cor=TRUE, scores=TRUE)\r\no < order(pca$scores[,2])\r\ngolub.gnames[o[1:10],2]\r\ngolub.gnames[o[3041:3051],2]\r\n\r\n##correlation\r\ncorgol<- apply(golub, 1, function(x) cor(x,golub.cl))\r\no <- order(corgol)\r\ngolub.gnames[o[3041:3051],2]\r\n\r\n##K-means\r\ndata <- data.frame(golub[ccnd3,],golub[zyxin,],golub[829,],golub[808,],golub[2670,])\r\ncl <- kmeans(data, 2,nstart = 10)\r\ncl\r\nfit<-kmeans(data, 2,nstart = 10)\r\nfit$cluster\r\nfit$centers\r\naggregate(data,by=list(fit$cluster),FUN=mean)\r\nplot(data, col = cl$cluster)\r\nrequire(cluster)\r\nfit<-pam(x=data,k=8)\r\nfit$clustering\r\nfit$medoids\r\nsummary(fit)\r\n\r\n##hierarchial clustering\r\nd<-dist(data,method=\"euclidean\")\r\nfit<-hclust(d,method = \"ward.D\")\r\nplot(fit)\r\ngroups<-cutree(fit,k=8)\r\nrect.hclust(fit,k=8,border=\"red\")\r\n\r\n##correlation plot visualization\r\nrequire(corrplot)\r\ncorrplot(cor(data[1:2]))\r\n\r\n## biplot\r\nbiplot(princomp(data,cor=TRUE),pc.biplot=TRUE,cex=0.5,expand=0.8)\r\n\r\n##Linear Discriminant Analysis\r\n> data(golub)\r\n> golubY<-golub[,1]\r\n> golubX<-as.matrix(golub[,2:11])\r\n> ratio<-2/3\r\n> set.seed(111)\r\n> learnind<-sample(length(golubY), size=floor(ratio*length(golubY)))\r\n> ldaresult<-ldaCMA(X=golubX, y=golubY, learnind=learnind)\r\n> show(ldaresult)\r\nbinary Classification with linear discriminant analysis\r\nnumber of predictions: 13\r\n> ftable(ldaresult)\r\nnumber of missclassifications: 5 \r\nmissclassification rate: 0.385 \r\nsensitivity: 0.167 \r\nspecificity: 1 \r\n predicted\r\ntrue 0 1\r\n 0 7 0\r\n 1 5 1\r\n> plot(ldaresult)\r\n\r\n##Quadratic Discriminant Analysis:\r\n> data(golub)\r\n> golubY<-golub[,1]\r\n> golubX<-as.matrix(golub[,2:11])\r\n> ratio<-2/3\r\n> set.seed(112)\r\n> learnind<-sample(length(golubY), size=floor(ratio*length(golubY)))\r\n> qdaresult<-qdaCMA(X=golubX,y=golubY,learnind=learnind)\r\n> show(qdaresult)\r\nbinary Classification with quadratic discriminant analysis\r\nnumber of predictions: 13\r\n> ftable(qdaresult)\r\nnumber of missclassifications: 3 \r\nmissclassification rate: 0.231 \r\nsensitivity: 0 \r\nspecificity: 0.833 \r\n predicted\r\ntrue 0 1\r\n 0 10 2\r\n 1 1 0\r\n> plot(qdaresult)\r\n\r\n##Diagonal Discriminant Analysis:\r\n> data(golub)\r\n> golubY<-golub[,1]\r\n> golubX<-as.matrix(golub[,-1])\r\n> ratio<-2/3\r\n> set.seed(111)\r\n> learnind<-sample(length(golubY), size=floor(ratio*length(golubY)))\r\n> dldaresult<-dldaCMA(X=golubX,y=golubY,learnind=learnind)\r\n> show(dldaresult)\r\nbinary Classification with diagonal discriminant analysis\r\nnumber of predictions: 13\r\n> ftable(dldaresult)\r\nnumber of missclassifications: 0 \r\nmissclassification rate: 0 \r\nsensitivity: 1 \r\nspecificity: 1 \r\n predicted\r\ntrue 0 1\r\n 0 7 0\r\n 1 0 6\r\n> plot(dldaresult)\r\n\r\n##Shrunken Centroids Discriminant Analysis \r\n> data(golub)\r\n> golubY<-golub[,1]\r\n> golubX<-as.matrix(golub[,-1])\r\n> set.seed(111)\r\n> learnind<-sample(length(golubY), size=floor(2/3*length(golubY)))\r\n> scdaresult<-scdaCMA(X=golubX,y=golubY,learnind=learnind)\r\n> show(scdaresult)\r\nbinary Classification with shrunken centroids discriminant analysis\r\nnumber of predictions: 13\r\n> ftable(scdaresult)\r\nnumber of missclassifications: 0 \r\nmissclassification rate: 0 \r\nsensitivity: 1 \r\nspecificity: 1 \r\n predicted\r\ntrue 0 1\r\n 0 7 0\r\n 1 0 6\r\n> plot(scdaresult)\r\n\r\n##Shrinkage Linear Discriminant Analysis:\r\n> library(sda)\r\n> data(golub)\r\n> golubY<-golub[,1]\r\n> golubX<-as.matrix(golub[,-1])\r\n> ratio<-2/3\r\n> set.seed(111)\r\n> learnind<-sample(length(golubY), size=floor(ratio*length(golubY)))\r\n> result<-shrinkldaCMA(X=golubX,y=golubY,learnind=learnind)\r\n> show(result)\r\nbinary Classification with shrinkage linear discriminant analysis\r\nnumber of predictions: 13\r\n> ftable(result)\r\nnumber of missclassifications: 4 \r\nmissclassification rate: 0.308 \r\nsensitivity: 0.333 \r\nspecificity: 1 \r\n predicted\r\ntrue 0 1\r\n 0 7 0\r\n 1 4 2\r\n> plot(result)\r\n\r\n##Fisher’s Linear Discriminant Analysis\r\n> data(golub)\r\n> golubY<-golub[,1]\r\n> golubX<-as.matrix(golub[,2:11])\r\n> ratio<-2/3\r\n> set.seed(111)\r\n> learnind<-sample(length(golubY), size=floor(ratio*length(golubY)))\r\n> fdaresult<-fdaCMA(X=golubX,y=golubY,learnind=learnind,comp=1,plot=TRUE)\r\n> show(fdaresult)\r\nbinary Classification with Fisher's linear discriminant\r\nnumber of predictions: 13\r\n> ftable(fdaresult)\r\nnumber of missclassifications: 5 \r\nmissclassification rate: 0.385 \r\nsensitivity: 0.5 \r\nspecificity: 0.714 \r\n predicted\r\ntrue 0 1\r\n 0 5 2\r\n 1 3 3\r\n> plot(fdaresult)\r\n\r\n## Flexible Discriminant Analysis \r\n> data(golub)\r\n> golubY<-golub[,1]\r\n> golubX<-as.matrix(golub[,2:11])\r\n> ratio<-2/3\r\n> set.seed(111)\r\n> learnind<-sample(length(golubY), size=floor(ratio*length(golubY)))\r\n> result<-flexdaCMA(X=golubX,y=golubY,learnind=learnind,comp=1)\r\n> show(result)\r\nbinary Classification with flexible discriminant analysis\r\nnumber of predictions: 13\r\n> ftable(result)\r\nnumber of missclassifications: 5 \r\nmissclassification rate: 0.385 \r\nsensitivity: 0.5 \r\nspecificity: 0.714 \r\n predicted\r\ntrue 0 1\r\n 0 5 2\r\n 1 3 3\r\n> plot(result)\r\n ", "meta": {"hexsha": "de017d57c79513bd90016fc8843d2c21445cfcf6", "size": 5503, "ext": "r", "lang": "R", "max_stars_repo_path": "Methuku_R_Project.r", "max_stars_repo_name": "m-vaishnavi/R-Programming-BiologicalDataAnalysis", "max_stars_repo_head_hexsha": "f28590e3e2719033fb4ff895d9a8c2eafb02ee83", "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": "Methuku_R_Project.r", "max_issues_repo_name": "m-vaishnavi/R-Programming-BiologicalDataAnalysis", "max_issues_repo_head_hexsha": "f28590e3e2719033fb4ff895d9a8c2eafb02ee83", "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": "Methuku_R_Project.r", "max_forks_repo_name": "m-vaishnavi/R-Programming-BiologicalDataAnalysis", "max_forks_repo_head_hexsha": "f28590e3e2719033fb4ff895d9a8c2eafb02ee83", "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.5845410628, "max_line_length": 85, "alphanum_fraction": 0.6983463565, "num_tokens": 1924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.8348658915148042}} {"text": "## Are x,y inside Sierpinski carpet (and where)? (1-yes, 0-no)\ninSC <- function(x, y) {\n while(TRUE) {\n if(!x||!y) {return(1)}\n if(x%%3==1&&y%%3==1) {return(0)}\n x=x%/%3; y=y%/%3;\n } return(0);\n}\n## Plotting Sierpinski carpet fractal. aev 4/1/17\n## ord - order, fn - file name, ttl - plot title, clr - color\npSierpinskiC <- function(ord, fn=\"\", ttl=\"\", clr=\"navy\") {\n m=640; abbr=\"SCR\"; dftt=\"Sierpinski carpet fractal\";\n n=3^ord-1; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);\n cat(\" *** START\", abbr, date(), \"\\n\");\n if(fn==\"\") {pf=paste0(abbr,\"o\", ord)} else {pf=paste0(fn, \".png\")};\n if(ttl!=\"\") {dftt=ttl}; ttl=paste0(dftt,\", order \", ord);\n cat(\" *** Plot file:\", pf,\".png\", \"title:\", ttl, \"\\n\");\n for(i in 0:n) {\n for(j in 0:n) {if(inSC(i,j)) {M[i,j]=1}\n }}\n plotmat(M, pf, clr, ttl);\n cat(\" *** END\", abbr, date(), \"\\n\");\n}\n## Executing:\npSierpinskiC(5);\n", "meta": {"hexsha": "75be2b91e3af16ebc59b0d919cf707a778d9c902", "size": 889, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Sierpinski-carpet/R/sierpinski-carpet-1.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/Sierpinski-carpet/R/sierpinski-carpet-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/Sierpinski-carpet/R/sierpinski-carpet-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": 34.1923076923, "max_line_length": 69, "alphanum_fraction": 0.5399325084, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.8346720044754223}} {"text": "###################################################################################################\r\n# Project: GV300 - LABa02 sessions - Problem Set 2 answers #\r\n# #\r\n# University: University of Essex #\r\n# #\r\n# Programmer: Lorenzo Crippa #\r\n# #\r\n###################################################################################################\r\n\r\n# exercise 6\r\ny <- 0:7 # the number of successful applications in 7 countries can go from 0 to 7\r\nmass.function <- dbinom(y, size = 7, prob = 0.3) # probabilities associated with each value of x\r\n\r\n# check:\r\nsum(mass.function) # 1, ok\r\n\r\ndf <- data.frame(y, prob=mass.function) # turn the values into a data frame\r\n\r\nplot(df$y, df$prob, type = \"l\", frame = F, ylab = \"probability\", xlab = \"y\", \r\n main = \"Probability mass function\")\r\n\r\n# Expected value is the mean: n*p:\r\nmean <- 7*0.3 # 2.1\r\n\r\n# variance is n*p*(1-p):\r\nvar <- 7*0.3*0.7 # 1.47\r\n\r\n############\r\n# GV300: Problem set 2, exercise 7\r\n\r\n# draw 1000 random observations from a binomial distribution with n = 7 and p = 0.3\r\n\r\nobs <- rbinom(1000, size = 7, p = 0.3)\r\n\r\nhist(obs, probability = T)\r\nlines(df$y, df$prob, col = \"red\")\r\n\r\nmean(obs) # 2.205, very close to 2.1\r\nvar(obs) # 1.49, very close to 1.47\r\n############", "meta": {"hexsha": "281f67f6f4ae0d1b31c69377ecf82dcf34a1b100", "size": 1695, "ext": "r", "lang": "R", "max_stars_repo_path": "2019_20/r_files/week_7.r", "max_stars_repo_name": "lorenzo-crippa/GV300_2019-20", "max_stars_repo_head_hexsha": "f449e42af13a617adf8c430eb4159f244b7dd469", "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": "2019_20/r_files/week_7.r", "max_issues_repo_name": "lorenzo-crippa/GV300_2019-20", "max_issues_repo_head_hexsha": "f449e42af13a617adf8c430eb4159f244b7dd469", "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": "2019_20/r_files/week_7.r", "max_forks_repo_name": "lorenzo-crippa/GV300_2019-20", "max_forks_repo_head_hexsha": "f449e42af13a617adf8c430eb4159f244b7dd469", "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": 42.375, "max_line_length": 100, "alphanum_fraction": 0.3746312684, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307668889047, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.8344631963160516}} {"text": "### 多次元尺度構成法の例\n### - おむすびに関するアンケートデータ\n\n## パッケージの読み込み\nrequire(MASS) \n\n## データの読み込み(\"omusubi.csv\"を用いる)\nraw <- read.csv(file=\"data/omusubi.csv\",row.names=1) # データの読み込み\nscan(file=\"data/omusubi.txt\",what=character(),sep=\";\") # データの説明の表示\n\n## データの内容を表示\n## print(raw) # 全データの表示\nhead(raw,n=4) # 最初の4県を表示\ntail(raw,n=4) # 最後の4県を表示\n\n## 非計量的多次元尺度構成法: 図(a)\ndst <- dist(sqrt(raw)) # Hellinger距離\nmds <- isoMDS(dst) # 2次元のユークリッド座標を構成\n## cmdscaleとは異なり,座標はpointsに,評価値はstressに収められている\nplot(mds$points,type='n',xlab=\"axis 1\",ylab=\"axis 2\")\ntext(mds$points,labels=rownames(mds$points),cex=.8)\n\n## Shepard ダイアグラム: 図(b)\nshprd <- Shepard(dst, mds$points)\nplot(shprd, pch = 20, col=\"blue\",\n xlab=\"Observed Dissimilarity\", ylab=\"Estimated Distance\")\nlines(shprd$x, shprd$yf, type = \"S\", col=\"red\", lwd=2)\n\n## マンハッタン距離による尺度構成: 図(c)\nmds <- isoMDS(dst, p=1)\nplot(mds$points,type='n',main=\"p=1\",xlab=\"axis 1\",ylab=\"axis 2\")\ntext(mds$points,labels=rownames(mds$points),cex=.8) \n\n## 近似的な最大距離による尺度構成: 図(d)\nmds <- isoMDS(dst, p=10)\nplot(mds$points,type='n',main=\"p=10\",xlab=\"axis 1\",ylab=\"axis 2\")\ntext(mds$points,labels=rownames(mds$points),cex=.8) \n\n## 3次元尺度構成: 図(e)\nmds <- isoMDS(dst, k=3)\nopar <- par(mfrow=c(2,2),mar=c(4,4,1,1))\nplot(mds$points[,c(1,2)],type='n',\n xlab=\"axis 1\",ylab=\"axis 2\", xlim=c(-2.5,2.5),asp=1)\ntext(mds$points[,c(1,2)],labels=rownames(mds$points),cex=.5) \nplot.new()\nplot(mds$points[,c(1,3)],type='n',\n xlab=\"axis 1\",ylab=\"axis 3\", xlim=c(-2.5,2.5),asp=1)\ntext(mds$points[,c(1,3)],labels=rownames(mds$points),cex=.5) \nplot(mds$points[,c(2,3)],type='n',\n xlab=\"axis 2\",ylab=\"axis 3\", xlim=c(-2.5,2.5),asp=1)\ntext(mds$points[,c(2,3)],labels=rownames(mds$points),cex=.5) \npar(opar)\n\n## 3次元尺度のShepard ダイアグラム: 図(f)\nshprd <- Shepard(dst, mds$points)\nplot(shprd, pch = 20, col=\"blue\",\n xlab=\"Observed Dissimilarity\", ylab=\"Estimated Distance\")\nlines(shprd$x, shprd$yf, type = \"S\", col=\"red\", lwd=2)\n", "meta": {"hexsha": "f55acc03a33c24476781279bb160a7125c4fb723", "size": 1938, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/code/m-omusubi.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/m-omusubi.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/m-omusubi.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.8474576271, "max_line_length": 66, "alphanum_fraction": 0.6496388029, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812354689081, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.8342974390952113}} {"text": "\n#' Metropolis-Hastings sampler\n#' \n#' sample xhat from the target distribution p(xhat), with given proposal distribution q(xhat|x), the acceptance rate is: \\cr\n#' min( 1 , dp(xhat)/dp(x) * dq(x|xhat)dq(xhat|x) ) \\cr\n#' where dp() is the density function of the target distribution, dq() the the density function of the proposal distribution. A new sample xhat is drawn from the sampler of the proposal distribution rq(). See examples.\n#' \n#' @param nsamples integer, number of samples to draw\n#' @param xini initial sample, the chain of samples starts from here. xini must be a matrix of one row, or a numeric vector that will be converted to a matrix of one row.\n#' @param dp function(x), the LOG density function of the target distribution log dp(x), DON'T FORGET THE LOG.\n#' @param dq function(xhat,x), the LOG density function of the proposal distribution log dq(xhat | x), DON'T FORGET THE LOG.\n#' @param rq function(x), the generator of the proposal distribution rq(xhat | x).\n#' @return a matrix of nsamples rows.\n#' @export\n#' @examples\n#' \\donttest{\n#' \n#' ## example1: independent Metropolis-Hastings algorithm, get 5000 samples from Beta(2.7,6.3)\n#' ## with independent uniform proposal U(0,1), and independent normal proposal N(0.5,1).\n#' \n#' ## step1: define p() and q()\n#' dp <- function(x) if(x>0&x<1) dbeta(x,2.7,6.3,log = TRUE) else -Inf\n#' dq1 <- function(xnew,x) 0 #uniform proposal log density\n#' dq2 <- function(xnew,x) dnorm(xnew,0.5,1) #normal proposal log density\n#' rq1 <- function(x) runif(1,0,1) #uniform proposal sampler\n#' rq2 <- function(x) rnorm(1,0.5,1) #normal proposal sampler\n#' ## step2: get 5000 samples, with two different proposals\n#' X1 <- MetropolisHastings(nsamples = 5000,xini = runif(1,0,1),dp=dp,dq=dq1,rq=rq1)\n#' X2 <- MetropolisHastings(nsamples = 5000,xini = runif(1,0,1),dp=dp,dq=dq2,rq=rq2)\n#' ## step3: plot the result, calculate acceptance rate\n#' sum(diff(X1)!=0)/nrow(X1) #the acceptance rate of uniform proposal\n#' sum(diff(X2)!=0)/nrow(X2) #the acceptance rate of normal proposal\n#' ## Clearly Uniform, compare to Normal, can better resemble Beta, so the acceptance rate is higher\n#' ## plot the results\n#' hist(X1)\n#' hist(X2)\n#' hist(rbeta(5000,2.7,6.3))\n#' \n#' ## example2: independent Metropolis-Hastings algorithm, sample from an improper distribution\n#' ## p(x) = -|x|+1, where -1 length(theta)) return(0)\t\n\ttheta_k = c(1,theta)\n theta_kh = c(theta_k[(h+1):length(theta_k)], rep(0,h ))\n g = sigma^2 * sum(theta_k * theta_kh ) #The formula for ACVF of MA(q)\n return (g)\n}\n\nh = 0:10\n'''\nsapply(X, FUN)\nArguments:\n-X: A vector or an object\n-FUN: Function applied to each element of x\n'''\ngam = sapply(h, gammaX, theta=theta, sigma=sigma)\nprint(gam)\nplot(h, gam, type=\"h\", col=4)\n\n#aacvf \nlibrary(\"itsmr\")\na = specify(ar=c(0),ma=theta, sigma2=sigma^2)\ngamma.itsmr = aacvf(a,10)\n\nplot(h, gamma.itsmr, type=\"h\")\ngamma.itsmr\n\n\n# b) Make an R program for IA and find (θ∞, ν∞) = {(θ∞j, j = 1, . . . , q), ν∞}\nN = 100\nq = 5\nIA = function(N, gamma.vec){\n\t#I) Initialisation page 30\n\tv = numeric(N) #initialize nu\n\tgamma = c(gamma.vec[1:(q+1)], rep(0,N)) #initialize\n\tTheta = matrix(0, ncol=N, nrow=N) #initialize\n\tv[1] = gamma[1] #gamma0\n\tTheta[1,1] <- gamma[2]/v[1] #theta1,1=gamma(1)/nu0\n\tv[2] = (1-Theta[1,1]^2)*v[1] #nu1 = (1-theta1,1^2)nu0\n\t\n\t#II) Start up part, for n=2,..,q\n\tfor(n in 2:q) {\n\t\tTheta[n,n] = gamma[n+1]/v[1] #theta(n,n) = gamma(n)/nu0\n\t\tfor (k in 1:(n-1)) {\n\t\t\tTheta[n,n-k] = (gamma[n+1-k]-sum(Theta[k, k:1]*Theta[n, n:(n+1-k)]*v[1:k]))/v[k+1] \n\t\t}\n\t\tv[n+1] = gamma[1] - sum( Theta[n,n:1]^2*v[1:n] ) #nu(n)\n\t}\t\n\n\t#III) Steady state part; for n>=q+1, formula on IA slide page 31\n\tfor(n in (q+1):N) {\n\t\tTheta[n,q] = gamma[q+1]/v[n+1-q] #Theta(n,q)=gamma(q)/nu(n-q)\n\t\tfor(k in 1:q-1){\n\t\t\tTheta[n,q-k] = (gamma[q+1-k] - sum(Theta[n-q+k,k:1]*Theta[n,q:(q-k+1)]*v[(n-q):(n-q+k-1)]))/v[n-q+k]\n\t\t}\n\t\tv[n+1] = gamma[1] - sum(Theta[n,n:1]*Theta[n,n:1]*v[1:n]) #nu(n)\n\t}\n\treturn(list(theta=Theta, nu=v))\n}\t\n\nia = IA(N, gam)\ntheta.inf = ia$theta[N, 1:q];theta.inf\n#[1] -0.1114082 0.2216191 -0.0309017 -0.3244026 0.3339867\nnu.inf = ia$nu[N];nu.inf\n#[1] 0.7816983\n\n# c) Calculate and plot the autocovariance function defined by the parameters from b).\n# Compare with a).\n\ngamma.ia = sapply(h, FUN=gammaX, theta=theta.inf, sigma=sqrt(nu.inf));gamma.ia\nsum(gamma.ia-gam)\n#[1] 0.0261705 difference is less than 0.03\n# smal difference in last term\nplot(h, gamma.ia, type=\"h\", col=\"blue\", ylab = \"ACVF\") #from b)\nlines(h+0.01, gam, type=\"h\", col=\"red\") #from a)\n\n#d) If the two parameter sets are different then at most one of them \n# gives an invertible model. Which of them does that with probability one?\n\ntheta = runif(n=q, min = -2, max = 2);theta\nMod(polyroot(c(1,theta)))\n#[1] 0.7795998 0.8878476 0.8878476 2.2131556 12.8982231 - non-invertible\nMod(polyroot(c(1,theta.inf)))\n# [1] 1.438013 1.200501 1.438013 1.098225 1.098225 - invertible\n#IA found the invertible model\n\n# 5.2\n# a) For N = 1000, \n# generate {Xt, t = 1, . . . , N} according to (5.1)MA(q)\n\nq = 5\nset.seed(1234)\ntheta = runif(q, -2, 2);theta\nsigma2z = 1/(1+sum(theta^2));sigma2z\n\n#(5.1) \\ X_t = \\sum_{j=0}^{q}\\theta_j Z_{t-j}, \\ \\theta_0=1\n\nN = 1000\nsigmaz = sqrt(sigma2z)\n#rlaplace -> lib(extraDistr)\nlibrary(extraDistr)\nset.seed(1234)\nZt = rlaplace(n=N, mu=0, sigma=sigmaz/sqrt(2))\nXt = arima.sim(list(ma=theta), n=N, innov = Zt)\nhead(Xt)\n\n#b) Calculate and plot the empirical autocovariance function\nacf(Xt, type=\"covariance\")\n\n#c) Find {theta_inf,j | j = 1..q, v_inf} from the IA with input \n# {gamma(h) | h = 0..q} If the algortihm does not converge, \n# increase q to q' and use gamma(h) ;h = 0..q' as input\nemp.gamma = as.vector(acf(Xt, type=\"covariance\", plot=FALSE)$acf)\nlength(emp.gamma)\nia2 = IA(N, emp.gamma)\ntheta.inf2 = ia2$theta[N, 1:5];theta.inf2\nnu.inf2 = ia2$nu[N];nu.inf2\n\n# d) Compute and plot the autocovariance function defined the \n# parameters from the IA given in c). Compare with b)\ngamma.acvf <- sapply(h, FUN=gammaX, theta=theta.inf2, sigma=sqrt(nu.inf2))\nacf(Xt, type=\"covariance\", lag.max = 15)\nlines(h+0.08, gamma.acvf, type=\"h\", col=\"green\")\ngamma.acvf\n# [1] 1.00313296 -0.14888739 0.09920841 0.06194804 -0.24862657 0.23970684 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000\nemp.gamma[1:(q+1)]\n#[1] 1.00313296 -0.14888739 0.09920841 0.06194804 -0.24862657 0.22084301\n\n# gamma.ia2 which is ACVF and emp.gamma which is empirical ACVF \n# is the same expect last term. ACVF sligtly larger than empirical ACVF\n\n# e) \n'''\nThe estimators theta_hat, sigma_hat from IA - satisfy the equation because, we see from the plot\nthat the emprical ACVF is approximately equal to the theoretical ACVF (mentioned in 5.1 a) \n\nWhat do you call these estimators?\nMoment estimators.\n\nHow can you do this without using IA?\nCould have used Newton-Rhapson/newton method - root finding algorithm\n'''\n\n# 5.4 An AR(6) model\n# Do basic descriptive statistics and estimation for the there cases. \n# Present plots and for the estimation use both Yule Walker, least square and maximum likelihood\nphi = c(0.40, 0.36, -0.47, 0.45, 0.21, -0.03)\nset.seed(1234)\n\nMod(polyroot(c(1,phi)))\n\nN1=100\nXt.1 = arima.sim(list(ar=phi), n=N1, innov = rnorm(N1) )\nN2=1000\nXt.2 = arima.sim(list(ar=phi), n=N2, innov = rnorm(N2) )\nN3=100000\nXt.3 = arima.sim(list(ar=phi), n=N3, innov = rnorm(N3) )\n\n#descriptive statistics\nsummary(Xt.1);var(Xt.1)\nsummary(Xt.2);var(Xt.2)\nsummary(Xt.3);var(Xt.3)\npar(mfrow=c(3,1))\nplot(1:N1, Xt.1, type=\"l\")\nplot(1:N2, Xt.2, type=\"l\")\nplot(1:N3, Xt.3, type=\"l\")\npar(mfrow=c(3,1))\nacf(Xt.1, type=\"covariance\")\nacf(Xt.2, type=\"covariance\")\nacf(Xt.3, type=\"covariance\")\n\n\nar_order=6\n\n# AR: c(0.40, 0.36, -0.47, 0.45, 0.21, -0.03)\nar.ols(x = Xt.1, aic = FALSE, order.max = 6)\nar(Xt.1, order=ar_order, method=\"yw\")\nar(Xt.1, order=ar_order, method=\"mle\")\nar(Xt.1, order=ar_order, method=\"burg\")\n'''\nols: 0.4659 0.2360 -0.4993 0.4478 0.1301 0.0372 \nyw:\t 0.4595 0.1501 -0.4686 0.4738 \nmle: 0.5231 0.1386 -0.4991 0.5357 \nburg:0.5001 0.1534 -0.5121 0.5110\n'''\n\nar.ols(x = Xt.2, aic = FALSE, order.max = ar_order)\nar(Xt.2, order=ar_order, method=\"yw\")\nar(Xt.2, order=ar_order, method=\"mle\")\nar(Xt.2, order=ar_order, method=\"burg\")\n'''\nols: 0.3880 0.4106 -0.4998 0.4686 0.2161 -0.1100 \nyw:\t 0.3855 0.4031 -0.4921 0.4684 0.2103 -0.1042 \nmle: 0.3855 0.4031 -0.4921 0.4684 0.2103 -0.1042 \nburg:0.3868 0.4068 -0.4984 0.4713 0.2156 -0.1102 \n'''\n\nar.ols(x = Xt.3, aic = FALSE, order.max = ar_order)\nar(Xt.3, order=ar_order, method=\"yw\")\nar(Xt.3, order=ar_order, method=\"mle\")\nar(Xt.3, order=ar_order, method=\"burg\")\n'''\nols: 0.3989 0.3646 -0.4747 0.4507 0.2132 -0.0366 \nyw:\t 0.3989 0.3646 -0.4746 0.4507 0.2131 -0.0366 \nmle: 0.3988 0.3646 -0.4747 0.4506 0.2132 -0.0366 \nburg:0.3988 0.3646 -0.4747 0.4506 0.2132 -0.0366 \n\nphi = c(0.40, 0.36, -0.47, 0.45, 0.21, -0.03)\n#Pretty close to ground truth when N is large\n'''\n\n#spectrum(Xt.1, ..., )\n#method - specifying the method used to estimate the spectral density. Allowed methods are \"pgram\" (default), \"ar\"\npar(mfrow = c(2,2))\nspectrum(Xt.1 ) #method = c(\"pgram\", \"ar\")\nspectrum(Xt.1, spans = 3)\nspectrum(Xt.1, spans = c(3,3))\nspectrum(Xt.1, spans = c(3,5))\n\npar(mfrow = c(2,2))\nspectrum(Xt.2 ) #method = c(\"pgram\", \"ar\")\nspectrum(Xt.2, spans = 3)\nspectrum(Xt.2, spans = c(3,3))\nspectrum(Xt.2, spans = c(3,5))\n\npar(mfrow = c(2,2))\nspectrum(Xt.3 ) #method = c(\"pgram\", \"ar\")\nspectrum(Xt.3, spans = 3)\nspectrum(Xt.3, spans = c(3,3))\nspectrum(Xt.3, spans = c(3,5))\n\n# acf, spectrum, spec.pgram, spectrum, arima, ar\n# 1. Discuss which parameters that are significant for the different situations. \n# 2. How mabny observations are need for this size of the model? \n# 3. Comment a parametric versus a nonparametric estimate of the spectral density. \n# 4. Can you see any connection between the data and the empirical ACF or the spectral density?\n# 5. You have used 3 different estimation methods for the autoregressive parameter vector. Do they differ much?\n\n#Answere:\n# 5: OLS, YW, MLE are equal for large N and different for smal N\n# 2: bservations need:\n# coeftest is a generic function for performing z and (quasi-)t Wald tests of \n# estimated coefficients. coefci computes the corresponding Wald confidence intervals.\nlibrary(lmtest)\norder_ar=6\ncoeftest(arima(Xt.1, order=c(order_ar,0,0), method=\"ML\"))\n'''\nz test of coefficients:\n\n Estimate Std. Error z value Pr(>|z|) \nar1 0.450212 0.100279 4.4896 7.136e-06 ***\nar2 0.200640 0.110741 1.8118 0.070016 . \nar3 -0.507068 0.105346 -4.8134 1.484e-06 ***\nar4 0.459391 0.104804 4.3833 1.169e-05 ***\nar5 0.132699 0.115263 1.1513 0.249622 \nar6 0.034579 0.107562 0.3215 0.747844 \nintercept -1.188528 0.417712 -2.8453 0.004437 ** \n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\n'''\n\ncoeftest(arima(Xt.2, order=c(order_ar,0,0), method=\"ML\"))\n'''\nz test of coefficients:\n\n Estimate Std. Error z value Pr(>|z|) \nar1 0.388763 0.031453 12.3602 < 2.2e-16 ***\nar2 0.405273 0.033031 12.2696 < 2.2e-16 ***\nar3 -0.499476 0.032276 -15.4750 < 2.2e-16 ***\nar4 0.471797 0.032224 14.6411 < 2.2e-16 ***\nar5 0.215453 0.033085 6.5122 7.405e-11 ***\nar6 -0.110041 0.031498 -3.4936 0.0004765 ***\nintercept 0.213069 0.245183 0.8690 0.3848372 \n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n'''\n\n# 2: n=1000 is needed for low p value of phi. N=1000. All phi_i significant.\n\n\n# 3: parametric versus a nonparametric\n# non-parametric: periodogram, parametric: AR estimation\n# er to metoder i spectrum, en parametrisk og en ikke.\n\n#From wiki:\n#https://en.wikipedia.org/wiki/Spectral_density_estimation?fbclid=IwAR1azWt2zz6iM5O8gO5AaJpvHehBv28tM-dgPGbTGILagk5E5xX0zHy3kko #Techniques\n# Below is a partial list of parametric techniques:\n# - AR which assumes that the nth sample is correlated with the previous p samples.\nspectrum(Xt.1, method=\"ar\")\n\n#Following is a partial list of non-parametric spectral density estimation techniques\n# periodogram - the modulus-squared of the discrete Fourier transform\nspectrum(Xt.1, method=\"pgram\")\n\n\npar(mfrow=c(3,2))\nspectrum(Xt.1, method=\"pgram\")\nspectrum(Xt.2, method=\"pgram\")\nspectrum(Xt.3, method=\"pgram\")\nspectrum(Xt.1, method=\"ar\")\nspectrum(Xt.2, method=\"ar\")\nspectrum(Xt.3, method=\"ar\")\n\n# The spectrum function estimates the spectral density of a time series.\n\n# spec.pgram calculates the periodogram using a fast Fourier transform, \n# and optionally smooths the result with a series of modified \n# Daniell smoothers (moving averages giving half weight to the end values)\n\n# So spectrum( X, method=\"pgram\") === spec.pgram(X)\n\n# 4: empirical ACF or the spectral density:\n#The relation between the autocovariance (or autocorrelation) \n#and the spectral density (for which the periodogram is an estimator) \n#is given by the Fourier transform. The two form a \n#so-called Fourier-transform pair meaning the two are \n#time(or space)-domain vs. frequency-domain representations of the \n#same thing\npar(mfrow=c(3,1))\nspectrum(Xt.3, method=\"pgram\")\nacf(Xt.3, type=\"covariance\")\nplot(1:N3, Xt.3, type=\"l\")\n\n\n# 5.5\n# Xt be a stationary and linear causal time series with white noise process Zt in WN(0,sig^2)\n# Find empi(Z_n+1) = P_n (Z_n+1) where P_n is linear prediction based on X_1,..,X_n\n# Let X_t= theta(B)Z_t with q finitie - non-invertible - and find empi(Z_n+1)\n\n#a) Let p = 10 and draw a sample of size p from the standard uniform distribution on\n#[-1; 1]. Define theta = choose(n,k)*U\n#Let sigma2 = 1 and Zt be iid Gaussian white noise with variance sigma2\nset.seed(1234)\np = 10\nU = runif(p, -0.001,0.001)\n \nphi_est = numeric(p)\n#definition of a causal AR(p) process\nfor (j in 1:p){\n\t#choose - binomial coefficient: n choose k\n\tphi_est[j] = choose(p,j)*U[j]\n}\narima.sim( list( ar = phi_est ), n = NN, innov = rnorm(NN) )\nphi_est\nsigma2_emp = 1 \nZt = rnorm(1, 0, sigma2_emp)\n\n# b) Calulate the spectral density\nspectral_density = function(omega, phi_est, sigma2_emp){\n w = complex(real = cos(omega) , imaginary = sin(omega)) #z= exp(i*omega) by euler\n w_bar = Conj(z) #z_bar= exp(-i*omega) by euler \n z_i = polyroot(c(1, (-1)*phi_est))\n w_vektor = rep(z, p)^(1:p)\n w_vektor_bar = rep(w_bar, p)^(1:p)\n is_ar = -1\n z = c(1, is_ar*phi_est*w_vektor)\n z_bar = c(1, is_ar*phi_est*w_vektor_bar)\n return ( sigma2_emp/((2*pi)*(z*z_bar)) )\n}\n\nomega = pi/4 # r=sqrt(2) then r*exp(i*omega) = 1+i\nspd = spectral_density(omega, phi_est, sigma2_emp)\n\nNN=100000\nempirical = arima.sim(list( ar = phi_est), n=NN, innov = rnorm(NN) )\nspectrum(empirical, method=\"pgram\")\npar(mfrow=c(2,1))\nplot(spd)\n\n# c) Find the roots, and plot them\nlibrary(plotrix)\nz_i = polyroot(c(1,-phi_est))\nplot(z_i, type=\"p\", pch = 17)\ndraw.circle(0, 0, radius=1)\n\n# d) Exchange all roots that are inside the unit circle by their corresponding inverses.\n\n#find non-causal AR roots /or non-invertible MA q roots\nnon_causal = function(z_i) {\n causal_roots = numeric(length(z_i))\n for ( i in 1:length(z_i) ) {\n if ( Mod( z_i[i] ) <= 1) {causal_roots[i] = 1/z_i[i]\n } else {causal_roots[i] = z_i[i]}\n }\n return (causal_roots)\n}\n\n#e) Check that all the roots are located outside the unit disk You may use R to plot them\ncausal = non_causal(c(1,-phi_est))\nplot(causal, type=\"p\", pch = 17, xlim=c(-5,15), ylim=c(-5,max(Mod(causal)+1)) )\ndraw.circle(0, 0, radius=1)\n\n# f) Calculate and plot the spectral density\nspectral_density = function(omega, phi_est, sigma2_emp){\n w = complex(real = cos(omega) , imaginary = sin(omega)) #z= exp(i*omega) by euler\n w_bar = Conj(z) #z_bar= exp(-i*omega) by euler \n z_i = polyroot(c(1, (-1)*phi_est))\n z_i = non_causal(z_i)\n w_vektor = rep(z, p)^(1:p)\n w_vektor_bar = rep(w_bar, p)^(1:p)\n is_ar = -1\n z = c(1, is_ar*phi_est*w_vektor)\n z_bar = c(1, is_ar*phi_est*w_vektor_bar)\n return ( sigma2_emp/((2*pi)*(z*z_bar)) )\n}\n\n# 5.7 \n# Write an R-program that calculates the phis given the roots of the \n# characteristic polynomialof an AR(p) model. \n# Apply your program to the situation in the previous problem.\nlibrary(utils)\n#Last term has sign (-1)^(p+1)\ngetPhiFromCausalRoots = function( z_i ) {\n\tp = length(z_i)\n\tif ( p == 1 ) {return (1/z_i)}\n\tphi = numeric( p )\n\tphi[1] = sum(1/z_i)\n\tfor( i in 2:(p-1) ) {\n\t\t#sum the product of all i-tuples. Tuples in column-space => Margin=2\n\t\tphi[i] = (-1)^(i-1) * sum(apply(combn(1/z_i, i), MARGIN=2, FUN=prod) )\n\t}\n\treturn (phi)\n}\n\ncausal_phi = Re( getPhiFromCausalRoots( causal ) )\n\n# 5.8\n# Simulate with N = 1000 the model\nN=1000\npolyroot(causal_phi)\n\nXt = arima.sim( list( ar = causal_phi ), n = N, innov = rnorm(NN) )", "meta": {"hexsha": "391d067d40583d524ceca02917901c6c5d2e1707", "size": 15046, "ext": "r", "lang": "R", "max_stars_repo_path": "hw5/hw5.r", "max_stars_repo_name": "emoen/Time_Series_stat211", "max_stars_repo_head_hexsha": "f30eb0c6a34c1eab8d347670c3b7a54f2c4c89c0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-06T19:14:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:14:00.000Z", "max_issues_repo_path": "hw5/hw5.r", "max_issues_repo_name": "emoen/Time_Series_stat211", "max_issues_repo_head_hexsha": "f30eb0c6a34c1eab8d347670c3b7a54f2c4c89c0", "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": "hw5/hw5.r", "max_forks_repo_name": "emoen/Time_Series_stat211", "max_forks_repo_head_hexsha": "f30eb0c6a34c1eab8d347670c3b7a54f2c4c89c0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-22T07:40:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T07:40:48.000Z", "avg_line_length": 33.2876106195, "max_line_length": 139, "alphanum_fraction": 0.657516948, "num_tokens": 5887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.891811044719067, "lm_q1q2_score": 0.8333039244568137}} {"text": "### X1, ..., Xn ~ exponencial(lambda)\n## Estimadores\ndelta <- function(samp) samp[1]\ndelta0 <- function(samp){ ## estimador melhorado por Rao-Blackwell\n s <- sum(samp)\n x1 <- samp[1]\n n <- length(samp)\n # est <- (n-1)/s * (1 - x1/s)^(n-2)\n est <- exp( ## versão numericamente estável\n log(n-1)-log(s) + (n-2)*log1p(- x1/s)\n )\n return(est)\n}\n\n## Simulando dados\nNsim <- 1000\nN <- 500\nlambda <- 3\n\namostras <- matrix(rexp(n = Nsim*N, rate = lambda),\n ncol = N, nrow = Nsim)\n\n### Aplicando os estimadores\n\nDs <- apply(amostras, 1, delta)\nD0s <- apply(amostras, 1, delta0)\n\npar(mfrow = c(1, 2))\nhist(Ds, probability = TRUE,\n xlab = expression(delta))\nabline(v = lambda, lwd = 2, lty = 2)\n\nhist(D0s, probability = TRUE,\n xlab = expression(delta[0]))\nabline(v = lambda, lwd = 2, lty = 2)\n\n## EQM\n\nmean((Ds-lambda)^2)\nmean((D0s-lambda)^2)\n\nmean(Ds)\nmean(D0s)\n\nvar(Ds)\nvar(D0s)\n", "meta": {"hexsha": "7225096d9282a589378ca63326f362c28686114a", "size": 906, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Rao_Blackwell_exemplo.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/Rao_Blackwell_exemplo.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/Rao_Blackwell_exemplo.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": 19.2765957447, "max_line_length": 66, "alphanum_fraction": 0.5938189845, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371972, "lm_q2_score": 0.8670357477770336, "lm_q1q2_score": 0.8331794801545417}} {"text": "# Example : 4 Chapter : 7.3 Page No: 404\n# Pseduoinverse of matrix\nA<-matrix(c(2,1,2,1),ncol=2)\nV<-svd(A)$v\nUT<-t(svd(A)$u)\nd<-svd(A)$d\nsigma1<-matrix(c(1/d[1],0,0,0),ncol=2)\nA1<-V%*%sigma1%*%UT\nprint(\"The Pseduo inverse of the given matrix\")\nprint(A1)\n#The answer may slightly vary due to rounding off values\n#The answers provided in the text book may vary because of the computation method followed.\n", "meta": {"hexsha": "eb937da92b3b7028c833d185cfe886ebf39b8069", "size": 410, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH7/EX7.3.4/Ex7.3_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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH7/EX7.3.4/Ex7.3_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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH7/EX7.3.4/Ex7.3_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": 31.5384615385, "max_line_length": 91, "alphanum_fraction": 0.6926829268, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760639, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.8326233594480403}} {"text": "#######################################################\n### Gamma distribution with Lambda = 8, Alpha = 0.5 ###\n#######################################################\n\n\n\n## Sample the samples\nnSamples <- 10000\nlambda = 8\nalpha = 0.5\nxVal <- rgamma(nSamples, shape=lambda, rate=alpha)\n\n\n## Make a histogram\npng(\"gamma_hist.png\", height = 800, width = 600)\nxHist <- hist(xVal, breaks=20)\n\n\n## Calculate characteristics\nxA1 <- mean(xVal) # mean\nxM2 <- mean((xVal - xA1)^2) # biased sample variance\nxS2 <- nSamples * xM2 / (nSamples - 1) # unbiased sample variance\nxS22 <- var(xVal) # unbiased sample variance\nxSigma2 <- sqrt(xS22)\nxSigma <- sd(xVal) # standard deviation (sqrt(m2))\nxSem <- xSigma / sqrt(nSamples) # error of mean\nxMed <- median(xVal) # median\nxMax <- max(xVal) # max value\nxMin <- min(xVal) # min value\nxQuant <- quantile(xVal) # quantiles\nxIqr <- IQR(xVal) # interquartile range\nxM3 <- mean((xVal - xA1)^3) # third central moment\nxGamma1 <- xM3 / xSigma^3 # skewness\nxM4 <- mean((xVal - xA1)^4) # forth central moment\nxGamma2 <- xM4 / xSigma^4 # kurtosis\n\nprint(paste0('Mean: ', xA1))\nprint(paste0('Biased sample variance: ', xM2))\nprint(paste0('Unbiased sample variance: ', xS2))\nprint(paste0('Unbiased sample variance 2: ', xS22))\nprint(paste0('Standard deviation: ', xSigma))\nprint(paste0('Standard deviation 2: ', xSigma2))\nprint(paste0('Error of mean: ', xSem))\nprint(paste0('Median: ', xMed))\nprint(paste0('Max value: ', xMax))\nprint(paste0('Min value: ', xMin))\ncat('Quantiles: ', xQuant, '\\n')\nprint(paste0('Interquantile range: ', xIqr))\nprint(paste0('Skewness: ', xGamma1))\nprint(paste0('Kurtosis: ', xGamma2))\n\n\n", "meta": {"hexsha": "a5d2f77d17610db69eff342a3998075d00468ff3", "size": 1639, "ext": "r", "lang": "R", "max_stars_repo_path": "TASK1/lab1/charac/distAnalys.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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": "TASK1/lab1/charac/distAnalys.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TASK1/lab1/charac/distAnalys.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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.9245283019, "max_line_length": 65, "alphanum_fraction": 0.6357535082, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.8323575642274977}} {"text": "# Example : 1 Chapter : 6.1 Page No: 284\r\n# Eigen values and eigen vectors\r\nA<-matrix(c(0.8,0.2,0.3,0.7),ncol=2)\r\nsol<-eigen(A)\r\nlambda<-sol$values\r\nx<-sol$vectors\r\nprint(\"The eigen values of the matrix are\")\r\nprint(lambda)\r\nprint(\"The eigen vectors of the matrix in normalised form are\")\r\nprint(x)\r\n#to get eigen vectors in the textbook multiply normalised vectors by scalars\r\nx[,1]<-x[,1]*(0.6/x[1,1])\r\nx[,2]<-x[,2]*(1/x[1,2])\r\nprint(\"Eigen vectors with respect to the above eigen values respectively are\")\r\nprint(x)\r\nprint(A%*%x)\r\n#The answer may slightly vary due to rounding off values\r\n#The answers provided in the text book may vary because of the computation process\r\n#Both answers are correct , here it is taken -Ax+b=0 , In the text book it is considered as Ax-b=0\r\n", "meta": {"hexsha": "bb43e3c8ef9dcd539985cc7f5378abf79f59b51b", "size": 784, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.1.1/Ex6.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/CH6/EX6.1.1/Ex6.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/CH6/EX6.1.1/Ex6.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": 39.2, "max_line_length": 99, "alphanum_fraction": 0.7028061224, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832345, "lm_q2_score": 0.8723473680407889, "lm_q1q2_score": 0.8321898121587739}} {"text": "# Configuring the working directory. (for running in Repl.it don't configure a working directory)\nsetwd(\"C:/Users/Weatherlly/Desktop/Estatistica\")\n# Entering values from the stem and leaf diagram.\nMilimetros <- c(0.50,1.50,2.50,3.60,5.30,5.30,5.30,5.80,5.80,6.10,6.40,6.40,6.40,6.40,6.40,6.40,6.60,7.40,7.60,7.60,8.10,8.10,8.10,8.40,8.40,8.40,8.40,8.60,8.60,9.10,9.10,9.40,9.70,9.90,10.2,10.4,10.7,10.7,10.7,10.9,11.2,11.2,11.2,11.4,11.4,11.4,11.9,12.2,12.2,12.2,12.4,12.4,13.2,14.0,14.2,22.9)\n# Configuring the amplitures of the branches.\nMilimetros2 <- (cut(Milimetros,breaks=c(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,16.0,18.0,20.0,23.0)))\n# Calculation of absolute and relative frequencies.\nN <- length(Milimetros2); N # Number of objects (number of data)\nni <- table(Milimetros2); ni \t # Absolute frequencies\nfi <- ni/N ; fi\t\t \t # Relative frequencies\nNi <- cumsum(ni); Ni\t # Cumulative absolute frequencies\nFi <- cumsum(fi); Fi\t # Cumulative relative frequencies\n# Using the summary function to calculate the quartiles, mean, median, minimum and maximum.\nsummary(Milimetros)\n# Calculating the variance\nvar(Milimetros) \n# Calculating the standard deviation\nsd(Milimetros)\n# plotting the histogram\nhist(Milimetros,c(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,16.0,18.0,20.0,23.0))\n# Plotting the Boxplot\nboxplot(Milimetros)\n", "meta": {"hexsha": "4da75368cc930b768554c5e9473fcbfeb8d10687", "size": 1408, "ext": "r", "lang": "R", "max_stars_repo_path": "rain-analysis/Codigo.r", "max_stars_repo_name": "Weatherlly/Analyzes-in-R", "max_stars_repo_head_hexsha": "585c4274ba132982bfe875e624bfdcf8cf0ff69e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-28T19:45:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T19:45:02.000Z", "max_issues_repo_path": "rain-analysis/Codigo.r", "max_issues_repo_name": "Weatherlly/Analyzes-in-R", "max_issues_repo_head_hexsha": "585c4274ba132982bfe875e624bfdcf8cf0ff69e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rain-analysis/Codigo.r", "max_forks_repo_name": "Weatherlly/Analyzes-in-R", "max_forks_repo_head_hexsha": "585c4274ba132982bfe875e624bfdcf8cf0ff69e", "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": 61.2173913043, "max_line_length": 296, "alphanum_fraction": 0.6896306818, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.8991213874066956, "lm_q1q2_score": 0.8318940501057384}} {"text": "dados.nuvens <- read.csv(\"cloud_seeding.csv\")\n\n## Y ~ lognormal(mu, sigma_sq)\n## log(Y) ~ normal(mu, sigma_sq)\nhist(dados.nuvens$Seeded)\nhist(log(dados.nuvens$Seeded))\n\nX <- log(dados.nuvens$Seeded)\n\nmean(X)\nvar(X)\nsum((X-mean(X))^2)/26\nsum((X-mean(X))^2)/25\n\nx_bar <- mean(X)\nS2_bar <- sum((X-mean(X))^2)/26\n\nsqrt(26)/5\n\n### P1 = Pr(|U| < 1/5 * sqrt(n))\n### = Pr(U < 1/5 * sqrt(n))\n#### U = n * (mu_h - mu)^2/sigma_sq\na <- 1/5\np1 <- function(n){\n pchisq(q = a * sqrt(n), df = 1)\n}\n### P2 = Pr(0.64n < V < 1.44 n)\n#### Pr(V < 1.44n) - Pr(V < 0.64n)\np2 <- function(n){\n pchisq(q = 1.44*n, df = n-1)-\n pchisq(q = 0.64*n, df = n-1)\n}\n\npar(mfrow = c(1, 2))\ncurve(p1, 1, 20, xlab = \"n\", main = \"P_1(n)\")\ncurve(p2, 1, 20, xlab = \"n\", main = \"P_2(n)\")\n\np3 <- function(n) p1(n)*p2(n)\nns <- 1:1500\ntabelinha <- data.frame(\n n = ns,\n prob = p3(ns)\n)\n\nhead(tabelinha)\n\nhead(subset(tabelinha, prob >= 0.99))\n", "meta": {"hexsha": "355f6b4ccd76a3b0265368251647cd05d2546d6f", "size": 904, "ext": "r", "lang": "R", "max_stars_repo_path": "code/exemplo_8.3.1_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_8.3.1_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_8.3.1_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": 18.8333333333, "max_line_length": 45, "alphanum_fraction": 0.546460177, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611597645271, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.8309276000623549}} {"text": "## Vectorized operations continued\n\n# Now we will use what we have learned to perform actual calculations that would otherwise be hella complicated\n\n# For example\n\n# What is the sum of the following equation:\n1 + 1/2^2 + 1/3^2 + ... 1/100^2\n\n# This is similar to \n$\\pi^2/6$. \n\n# Now we will define an object that holds the values 1 to 100\n1 + 1/2^2 + 1/3^2 + ... + 1/100^2\n\n# Remember you can use vectorization to obtain the series with 1/x^2\n# Now you just sum these vectors\n\nx <- seq(1, 100) # For example, define an object with values 1 to 100 and compute the sum\nsum(1/x^2) # Sum the equation\n", "meta": {"hexsha": "18b1fc374688552ea55f30d2e605b8505dc90bbd", "size": 598, "ext": "r", "lang": "R", "max_stars_repo_path": "Vectors/Vectorized Operations 2.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": "Vectors/Vectorized Operations 2.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": "Vectors/Vectorized Operations 2.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": 28.4761904762, "max_line_length": 111, "alphanum_fraction": 0.6989966555, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947148047778, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.8307890413535629}} {"text": "# 1. Eucldian Distance\nx1 <- rnorm(30)\nx2 <- rnorm(30)\neuc_dist <- dist(rbind(x1, x2), method = \"euclidian\")\nx1\nx2\neuc_dist\n\n\n# 2. Cosine Similarity\nlibrary(lsa)\nvec1 <- c(1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0)\nvec2 <- c(0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0)\ncosine_similarity <- cosine(vec1, vec2)\ncosine_similarity\n\n\n# 3. Jaccard Similarity\nlibrary(clusteval)\nvec1 <- c(1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0)\nvec2 <- c(0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0)\njaccard_similarity <- cluster_similarity(vec1, vec2, similarity = \"jaccard\")\njaccard_similarity\n\n\n# 4. Pearson Correlation\ncor(mtcars, method = \"pearson\")", "meta": {"hexsha": "6afea502a3da2ea2fdf77f70ad670bb776cd8ed1", "size": 603, "ext": "r", "lang": "R", "max_stars_repo_path": "chapter04/r/neighbor_method.r", "max_stars_repo_name": "coco-in-bluemoon/building-recommendation-engines", "max_stars_repo_head_hexsha": "b337b2ba75b6c9b08612ab1720a2858e64e9de09", "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": "chapter04/r/neighbor_method.r", "max_issues_repo_name": "coco-in-bluemoon/building-recommendation-engines", "max_issues_repo_head_hexsha": "b337b2ba75b6c9b08612ab1720a2858e64e9de09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter04/r/neighbor_method.r", "max_forks_repo_name": "coco-in-bluemoon/building-recommendation-engines", "max_forks_repo_head_hexsha": "b337b2ba75b6c9b08612ab1720a2858e64e9de09", "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.3333333333, "max_line_length": 76, "alphanum_fraction": 0.6301824212, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147185726374, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.8303573239243787}} {"text": "#########################################\n######### Question 2.1 ###########\n#########################################\n#### data input\nlibrary(\"alr3\")\nht <- htwt$Ht\nwt <- htwt$Wt\n\n#### 2.1.1 draw a scatterplot of ht and wt\nplot(ht, wt)\nfit <- lm(wt~ht)\nabline(fit, col=\"blue\")\n\n#### 2.1.2 \nxbar <- mean(ht)\nybar <- mean(wt)\nsxx <- sum((ht-xbar)^2)\nsyy <- sum((wt-ybar)^2)\nsxy <- sum((ht-xbar)*(wt-ybar))\nc(xbar, ybar, sxx, syy, sxy)\n## estimate the slope(b1) and intercept(b0)\nb1 <- sxy/sxx\nb0 <- ybar-b1*xbar\nc(b0, b1)\nabline(b0, b1, col=\"red\")\n\n#### 2.1.3 estimate RSS and theta\n##\nn <- length(ht)\nrss <- syy - b1^2*sxx\ntheta <- rss/(n-2)\n##\nse.b1 <- sqrt(theta/sxx)\nse.b0 <- sqrt(theta*(1/n+xbar^2/sxx))\ncov.b0b1 <- -theta*xbar/sxx\nc(theta, se.b0, se.b1, cov.b0b1)\n## t-test\nt1 <- b1/se.b1\nt0 <- b0/se.b0\n## p.t <- 2*(1-pt(c(t0, t1), 8))\nc(t0, t1)\n\n#### 2.1.4 do f-test\n##\nssreg <- sxy^2/sxx\nf <- ssreg/theta\np.f <- 1-pf(f, 1, 8)\nc(ssreg, f, p.f)\n## show f=sqr(t)\nts <- t1^2\nc(f, ts)\n##\nanova(fit)\n\n########################################\n########## Question 2.5 ###########\n########################################\n##### 2.5.1\nhead(\"wblake\")\nfish.len <- wblake$Length\nfish.age <- wblake$Age\nfit.wblake <- lm(fish.len~fish.age)\npredict(fit.wblake, data.frame(fish.age=c(2, 4, 6)), interval=\"confidence\",level=0.95)\n\n#####\t2.5.2\npredict(fit.wblake, data.frame(fish.age=c(9)), interval=\"confidence\",level=0.95)\n\n#####\t2.5.3\nplot(fish.age, fish.len)\nabline(fit.wblake, col=\"green\")\nlines(lowess(wblake), col=\"red\")\n\n########################################\n##########\t\tQuestion 2.13 \t########\n########################################\n#####\t2.13.1\ncspd <- wm1$CSpd\nrspd <- wm1$RSpd\nplot(rspd, cspd)\nfit.wm <- lm(cspd~rspd)\nabline(fit.wm, col=\"red\")\n\n####\t2.13.2\nsummary(fit.wm)\n\n####\t2.13.3\npredict(fit.wm, data.frame(rspd=7.4285), interval=\"confidence\", level=0.95)\n\n####\t2.13.5\nse <- function(m, n, xstar){\n\tcspd <- wm1$CSpd\n\trspd <- wm1$RSpd\n\tcspd.bar <- mean(cspd)\n\trspd.bar <- mean(rspd)\n\tsxx <- sum((cspd-cspd.bar)^2)\n\tsyy <- sum((rspd-rspd.bar)^2)\n\tsxy <- sum((cspd-cspd)*(rspd-rspd))\n\trss <- syy-sxy^2/sxx\n\ttheta <- rss/(n-2)\n\tvar.m <- theta/m+theta*(1/n+(xstar-rspd.bar)^2/sxx)\n\treturn (var.m)\n}\nse(62039, 1116, 7.4285)\n\n", "meta": {"hexsha": "23161f09df758908d42afd353e433bb5c697c8bd", "size": 2244, "ext": "r", "lang": "R", "max_stars_repo_path": "Simple Linear Regression Model.r", "max_stars_repo_name": "lancezlin/Applied_Linear_Model_with_R", "max_stars_repo_head_hexsha": "4948c9b2ca7794199d51a545591f7fd7135d7cf1", "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": "Simple Linear Regression Model.r", "max_issues_repo_name": "lancezlin/Applied_Linear_Model_with_R", "max_issues_repo_head_hexsha": "4948c9b2ca7794199d51a545591f7fd7135d7cf1", "max_issues_repo_licenses": ["MIT"], "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 Linear Regression Model.r", "max_forks_repo_name": "lancezlin/Applied_Linear_Model_with_R", "max_forks_repo_head_hexsha": "4948c9b2ca7794199d51a545591f7fd7135d7cf1", "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.3714285714, "max_line_length": 86, "alphanum_fraction": 0.5151515152, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.8299940811521818}} {"text": "##### Chapter 6: Regression Methods -------------------\r\n\r\n#### Part 1: Linear Regression -------------------\r\n\r\n## Understanding regression ----\r\n## Example: Space Shuttle Launch Data ----\r\nlaunch <- read.csv(\"challenger.csv\")\r\n\r\n# estimate beta manually\r\nb <- cov(launch$temperature, launch$distress_ct) / var(launch$temperature)\r\nb\r\n\r\n# estimate alpha manually\r\na <- mean(launch$distress_ct) - b * mean(launch$temperature)\r\na\r\n\r\n# calculate the correlation of launch data\r\nr <- cov(launch$temperature, launch$distress_ct) /\r\n (sd(launch$temperature) * sd(launch$distress_ct))\r\nr\r\ncor(launch$temperature, launch$distress_ct)\r\n\r\n# computing the slope using correlation\r\nr * (sd(launch$distress_ct) / sd(launch$temperature))\r\n\r\n# confirming the regression line using the lm function (not in text)\r\nmodel <- lm(distress_ct ~ temperature, data = launch)\r\nmodel\r\nsummary(model)\r\n\r\n# creating a simple multiple regression function\r\nreg <- function(y, x) {\r\n x <- as.matrix(x)\r\n x <- cbind(Intercept = 1, x)\r\n solve(t(x) %*% x) %*% t(x) %*% y\r\n}\r\n\r\n# examine the launch data\r\nstr(launch)\r\n\r\n# test regression model with simple linear regression\r\nreg(y = launch$distress_ct, x = launch[3])\r\n\r\n# use regression model with multiple regression\r\nreg(y = launch$distress_ct, x = launch[3:5])\r\n\r\n# confirming the multiple regression result using the lm function (not in text)\r\nmodel <- lm(distress_ct ~ temperature + pressure + launch_id, data = launch)\r\nmodel\r\n\r\n## Example: Predicting Medical Expenses ----\r\n## Step 2: Exploring and preparing the data ----\r\ninsurance <- read.csv(\"insurance.csv\", stringsAsFactors = TRUE)\r\nstr(insurance)\r\n\r\n# summarize the charges variable\r\nsummary(insurance$charges)\r\n\r\n# histogram of insurance charges\r\nhist(insurance$charges)\r\n\r\n# table of region\r\ntable(insurance$region)\r\n\r\n# exploring relationships among features: correlation matrix\r\ncor(insurance[c(\"age\", \"bmi\", \"children\", \"charges\")])\r\n\r\n# visualing relationships among features: scatterplot matrix\r\npairs(insurance[c(\"age\", \"bmi\", \"children\", \"charges\")])\r\n\r\n# more informative scatterplot matrix\r\nlibrary(psych)\r\npairs.panels(insurance[c(\"age\", \"bmi\", \"children\", \"charges\")])\r\n\r\n## Step 3: Training a model on the data ----\r\nins_model <- lm(charges ~ age + children + bmi + sex + smoker + region,\r\n data = insurance)\r\nins_model <- lm(charges ~ ., data = insurance) # this is equivalent to above\r\n\r\n# see the estimated beta coefficients\r\nins_model\r\n\r\n## Step 4: Evaluating model performance ----\r\n# see more detail about the estimated beta coefficients\r\nsummary(ins_model)\r\n\r\n## Step 5: Improving model performance ----\r\n\r\n# add a higher-order \"age\" term\r\ninsurance$age2 <- insurance$age^2\r\n\r\n# add an indicator for BMI >= 30\r\ninsurance$bmi30 <- ifelse(insurance$bmi >= 30, 1, 0)\r\n\r\n# create final model\r\nins_model2 <- lm(charges ~ age + age2 + children + bmi + sex +\r\n bmi30*smoker + region, data = insurance)\r\n\r\nsummary(ins_model2)\r\n\r\n#### Part 2: Regression Trees and Model Trees -------------------\r\n\r\n## Understanding regression trees and model trees ----\r\n## Example: Calculating SDR ----\r\n# set up the data\r\ntee <- c(1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 6, 7, 7, 7, 7)\r\nat1 <- c(1, 1, 1, 2, 2, 3, 4, 5, 5)\r\nat2 <- c(6, 6, 7, 7, 7, 7)\r\nbt1 <- c(1, 1, 1, 2, 2, 3, 4)\r\nbt2 <- c(5, 5, 6, 6, 7, 7, 7, 7)\r\n\r\n# compute the SDR\r\nsdr_a <- sd(tee) - (length(at1) / length(tee) * sd(at1) + length(at2) / length(tee) * sd(at2))\r\nsdr_b <- sd(tee) - (length(bt1) / length(tee) * sd(bt1) + length(bt2) / length(tee) * sd(bt2))\r\n\r\n# compare the SDR for each split\r\nsdr_a\r\nsdr_b\r\n\r\n## Example: Estimating Wine Quality ----\r\n## Step 2: Exploring and preparing the data ----\r\nwine <- read.csv(\"whitewines.csv\")\r\n\r\n# examine the wine data\r\nstr(wine)\r\n\r\n# the distribution of quality ratings\r\nhist(wine$quality)\r\n\r\n# summary statistics of the wine data\r\nsummary(wine)\r\n\r\nwine_train <- wine[1:3750, ]\r\nwine_test <- wine[3751:4898, ]\r\n\r\n## Step 3: Training a model on the data ----\r\n# regression tree using rpart\r\nlibrary(rpart)\r\nm.rpart <- rpart(quality ~ ., data = wine_train)\r\n\r\n# get basic information about the tree\r\nm.rpart\r\n\r\n# get more detailed information about the tree\r\nsummary(m.rpart)\r\n\r\n# use the rpart.plot package to create a visualization\r\nlibrary(rpart.plot)\r\n\r\n# a basic decision tree diagram\r\nrpart.plot(m.rpart, digits = 3)\r\n\r\n# a few adjustments to the diagram\r\nrpart.plot(m.rpart, digits = 4, fallen.leaves = TRUE, type = 3, extra = 101)\r\n\r\n## Step 4: Evaluate model performance ----\r\n\r\n# generate predictions for the testing dataset\r\np.rpart <- predict(m.rpart, wine_test)\r\n\r\n# compare the distribution of predicted values vs. actual values\r\nsummary(p.rpart)\r\nsummary(wine_test$quality)\r\n\r\n# compare the correlation\r\ncor(p.rpart, wine_test$quality)\r\n\r\n# function to calculate the mean absolute error\r\nMAE <- function(actual, predicted) {\r\n mean(abs(actual - predicted)) \r\n}\r\n\r\n# mean absolute error between predicted and actual values\r\nMAE(p.rpart, wine_test$quality)\r\n\r\n# mean absolute error between actual values and mean value\r\nmean(wine_train$quality) # result = 5.87\r\nmean_abserror(5.87, wine_test$quality)\r\n\r\n## Step 5: Improving model performance ----\r\n# train a M5' Model Tree\r\nlibrary(RWeka)\r\nm.m5p <- M5P(quality ~ ., data = wine_train)\r\n\r\n# display the tree\r\nm.m5p\r\n\r\n# get a summary of the model's performance\r\nsummary(m.m5p)\r\n\r\n# generate predictions for the model\r\np.m5p <- predict(m.m5p, wine_test)\r\n\r\n# summary statistics about the predictions\r\nsummary(p.m5p)\r\n\r\n# correlation between the predicted and true values\r\ncor(p.m5p, wine_test$quality)\r\n\r\n# mean absolute error of predicted and true values\r\n# (uses a custom function defined above)\r\nMAE(wine_test$quality, p.m5p)\r\n", "meta": {"hexsha": "5b279f766924891b751efc4ff41b44559a1d19a1", "size": 5721, "ext": "r", "lang": "R", "max_stars_repo_path": "Training/MachineLearning/code/chapter 6/2148_06.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 6/2148_06.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 6/2148_06.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": 28.1822660099, "max_line_length": 95, "alphanum_fraction": 0.6762803706, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.8615382129861582, "lm_q1q2_score": 0.8283981158053269}} {"text": "#######################################################\n### Gamma distribution with Lambda = 8, Alpha = 0.5 ###\n#######################################################\n\n\n\n## Sample the samples\nnSamples <- 10000\nlambda = 8\nalpha = 0.5\nxVal <- rgamma(nSamples, shape=lambda, rate=alpha)\n\n\n## Calculate characteristics\nxA1 <- mean(xVal) # mean\nxM2 <- mean((xVal - xA1)^2) # biased sample variance\nxS2 <- nSamples * xM2 / (nSamples - 1) # unbiased sample variance\nxSigma <- sd(xVal) # standard deviation (sqrt(m2))\nxSem <- xSigma / sqrt(nSamples) # error of mean\nxMed <- median(xVal) # median\nxMax <- max(xVal) # max value\nxMin <- min(xVal) # min value\nxQuant <- quantile(xVal) # quantiles\nxIqr <- IQR(xVal) # interquartile range\nxM3 <- mean((xVal - xA1)^3) # third central moment\nxGamma1 <- xM3 / xSigma^3 # skewness\nxM4 <- mean((xVal - xA1)^4) # forth central moment\nxGamma2 <- xM4 / xSigma^4 # kurtosis\n\n\n## Parameter estimation (moment method)\nprint('################################')\n# E[x] = lambda / alpha; D[x] = lambda^2 / alpha\nalphaEstMM <- xA1 / xM2\nlambdaEstMM <- xA1^2 / xM2\nprint(paste0('Estimated alpha (MM): ', alphaEstMM))\nprint(paste0('Estimated lambda (MM): ', lambdaEstMM))\n\n\n## Pearson's chi square test\nprint('################################')\nrNum <- 15\nstepSize <- 3\nrSeq <- seq(1, rNum-1)\nxCountsVect <- vector()\nfor (i in rSeq)\n{\n\tdesiredVals <- xVal[xVal > (stepSize * (i - 1))]\n\tdesiredVals <- desiredVals[desiredVals < (stepSize * i)]\n\txCountsVect <- c(xCountsVect, length(desiredVals))\n}\ndesiredVals <- xVal[xVal > stepSize * rNum-1]\nxCountsVect <- c(xCountsVect, length(desiredVals))\nrSeq <- c(0, rSeq)\n\ngammaCDFOnBreaks <- pgamma(stepSize * rSeq, lambdaEstMM, alphaEstMM)\ngammaCDFOnBreaks <- c(gammaCDFOnBreaks, 1)\n#print(gammaCDFOnBreaks)\npVect = gammaCDFOnBreaks[2:(rNum+1)] - gammaCDFOnBreaks[1:rNum]\n#print(xCountsVect)\n#print(round(nSamples * pVect))\nnumer = (xCountsVect - nSamples * pVect)^2\ndenom = nSamples * pVect\nchiSquare = sum(numer / denom)\nprint(paste0('Chi square test: ', chiSquare))\n", "meta": {"hexsha": "7f9fef909d471be5f64c440f44aa38ab76fa7867", "size": 2032, "ext": "r", "lang": "R", "max_stars_repo_path": "TASK1/lab1/chiSquare/chiSquareTest.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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": "TASK1/lab1/chiSquare/chiSquareTest.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TASK1/lab1/chiSquare/chiSquareTest.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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.7878787879, "max_line_length": 68, "alphanum_fraction": 0.6299212598, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542875927779, "lm_q2_score": 0.8633916099737807, "lm_q1q2_score": 0.8281257645779831}} {"text": "### 多次元尺度構成法の例\n### - Distances Between European Cities\n\n## データの読み込み (\"datasets::eudodist\"を用いる)\ndata(eurodist) # データセットの読み込み\nhelp(eurodist) # データセットの詳細を表示\nclass(eurodist) # クラスの確認\n\n## 多次元尺度(2次元)の構成\nmds <- cmdscale(eurodist,k=2)\n\n## 構成された尺度によるデータの表示: 図(a)\nplot(mds,type='n',asp=1,xlab=\"\",ylab=\"\") # 点は打たずに座標軸だけ用意\ntext(mds,labels=rownames(mds),cex=.8) # 点の位置に都市名を表示\nabline(h=pretty(range(mds[,1]),10), # ガイドラインを表示\n v=pretty(range(mds[,2]),10), col=\"lightgray\")\n\n## 実際の配置に合わせて南北を逆転: 図(b)\nmds2 <- mds * rep(c(1,-1),each=nrow(mds)) \nplot(mds2,type='n',asp=1,xlab=\"\",ylab=\"\")\ntext(mds2,labels=rownames(mds2),cex=.8)\nabline(h=pretty(range(mds2[,1]),10),\n v=pretty(range(mds2[,2]),10), col=\"lightgray\")\n\n## 3次元尺度構成 (第1,2軸): 図(c)\nmds3 <- cmdscale(eurodist,k=3) # 3次元への埋め込み\nplot(mds3,type='n',asp=1,xlab=\"axis 1\",ylab=\"axis 2\")\ntext(mds3,labels=rownames(mds),cex=.8)\nabline(h=pretty(range(mds3[,1]),10),\n v=pretty(range(mds3[,2]),10), col=\"lightgray\")\n\n## 3次元尺度構成 (第2,3軸): 図(d)\nplot(mds3[,2:3],type='n',asp=1,xlab=\"axis 2\",ylab=\"axis 3\") \ntext(mds3[,2:3],labels=rownames(mds),cex=.8)\nabline(h=pretty(range(mds3[,2]),10), # 縦横比の関係で第2軸を使用\n v=pretty(range(mds3[,2]),10), col=\"lightgray\")\n\n## 不安定な高次元への埋め込みの例\nhead(cmdscale(eurodist, k=20),n=3) # 指定した次元までの座標が計算できない\n## 高次元への埋め込みの安定化\nmds4 <- cmdscale(eurodist, k=20, add=TRUE) # 対角成分に定数を付加\nhead(mds4$points,n=3) # 推定された座標を表示\n", "meta": {"hexsha": "aed9434d3d9f10408e054eec598adda2e7bdd2a1", "size": 1399, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/code/m-eurodist.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/m-eurodist.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/m-eurodist.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.5348837209, "max_line_length": 60, "alphanum_fraction": 0.6619013581, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8918110461567922, "lm_q1q2_score": 0.8279652219179929}} {"text": "#' One-dimensional diffusion, constant boundary conditions\n#'\n#' @description Function to solve diffusion equation\n#' using numerical implicit finite differences method,\n#' applied in the condition where: a) the diffusion occurs\n#' inside a slab of material unidimensionally,\n#' or only along one axis, b) the coefficient of diffusion is constant,\n#' and c) the boundary conditions are constant.\n#'\n#' @usage diff_1D(Lx, Tt, nt, nx, D, C_ini, C_lim)\n#'\n#' @param Lx Total length of slab in x direction, usually in mm.\n#' @param Tt Total diffusion time, usually in second.\n#' @param nt Number of time discretization.\n#' @param nx Number of dimension x discretization\n#' @param D Coefficient of diffusion. Must be constant value.\n#' @param C_ini Initial concentration value inside the slab.\n#' @param C_lim Boundary condition, written as a vector\n#' with one or two elements. If there is only one element,\n#' the other side of the slab will be presented as having\n#' Neumann boundary condition with flux = 0. If there are\n#' two elements, the first element is the dirichlet\n#' concentration on the left side, while the second element\n#' is the dirichlet concentration on the right side.\n#'\n#' @return A matrix with {nx+1} number of row and {nt}\n#' number of column, profiling the diffusion on slab with Lx\n#' length along the time Tt.\n#'\n#' @examples\n#' Lx <- 5 #Length of slab, in mm\n#' Tt <- 20 #Total measured diffusion time, in seconds\n#' nt <- 100 #Number of time discretization, wherein the Tt will be divided into 100 equal parts (0, 0.2, 0.4, ..., 20)\n#' nx <- 50 #Number of dimension discretization\n#' D <- 0.05 #Coefficient of diffusion in mm^2/s.\n#' C_ini <- 0.05 #Initial concentration inside the slab.\n#' C_lim <- c(0.10,0.25) #Dirichlet boundary concentration diffusing into the slab\n#' matC <- diff_1D(Lx, Tt, nt, nx, D, C_ini, C_lim)\n\ndiff_1D <- function(Lx,Tt,nt,nx,D,C_ini,C_lim){\n\n #1-Dimensional diffusion solver using implicit method, with border condition on its two extremities/sides\n\n ##Basic parameters\n if(length(C_lim) == 1){\n\n C_fin <- C_lim\n\n } else {\n\n if(length(C_lim == 2)){\n C_left <- C_lim[1]\n\n C_right <- C_lim[2]\n\n } else {\n\n stop('ERROR = Unfortunately, this function cannot take more than two condition limits coming from each side')\n\n }\n\n }\n\n dt <- Tt/nt #Size of one step in t\n\n dx <- Lx/(nx+1) #Size of one step in x\n\n ##Calculations\n s = D*dt/(dx^2)\n\n ##\n # Matrix A\n A = matrix(0, nrow = nx+1, ncol = nx+1)\n\n for (i in 2:nx) {\n\n A[i, i] <- (1+2*s) #Diagonal elements\n\n A[i, (i+1)] <- -s\n\n A[(i+1), i] <- -s\n\n }\n\n A[1,1] <- (1+2*s); A[nx+1,nx+1] <- A[1,1]\n\n A[2,1] <- -s; A[1,2] <- -s\n\n b <- matrix(0, nrow = nx+1, ncol = 1)\n\n #Conditioning\n if(length(C_lim) == 2){\n\n print(\"Boundary conditions: dirichlet in both sides\")\n\n b[1] <- s*C_right #Final, right side\n\n b[nx+1] <- s*C_left #Final, left side\n\n } else {\n\n print(\"Boundary condition: dirichlet in one side and neumann in another\")\n\n A[nx+1,nx] <- -2*s #For neumann boundary condition\n\n b[1] <- s*C_fin #Final, right side\n\n b[nx+1] <- 0 #Zero flux, neumann condition, left side\n\n }\n\n Cmat_i <- matrix(C_ini, nrow = nx+1, ncol = 1)\n\n Cmat_f <- matrix(0, nrow = nx+1, ncol = nt)\n\n t_n <- matrix(0, nrow = nt, ncol = 1)\n\n Cmat_f[,1] <- Cmat_i\n\n t_j <- 0 #Initial time\n\n t_n[1] <- t_j\n\n ######\n ##March solution in time\n\n for (j in 1:nt) {\n\n t_j <- t_j+dt\n\n if(j == 1){\n Cmat_j <- Cmat_i\n } else {\n Cmat_j <- Cmat_j_1\n }\n\n c <- Cmat_j + b\n\n Cmat_j_1 = solve(A,c)\n\n Cmat_f[,j] <- Cmat_j_1\n\n #Next time step\n t_n[j] <- t_j\n\n }\n\n return(Cmat_f)\n\n}\n\n#' Mean concentration values of one-dimensional diffusion during each time steps.\n#'\n#' @description A wrapper of \\emph{diff_1D} function,\n#' returning the mean values of concentration during each\n#' time step of the diffusion.\n#'\n#' @usage diff_1D_Ct(Lx, Tt, nt, nx, D, C_ini, C_lim)\n#'\n#' @param Lx Total length of slab in x direction, usually in mm.\n#' @param Tt Total diffusion time, usually in second.\n#' @param nt Number of time discretization.\n#' @param nx Number of dimension x discretization\n#' @param D Coefficient of diffusion. Must be constant value.\n#' @param C_ini Initial concentration value inside the slab.\n#' @param C_lim Boundary condition, written as a vector with one or two elements. If there is only one element, the other side of the slab will be presented as having Neumann boundary condition with flux = 0. If there are two elements, the first element is the dirichlet concentration on the left side, while the second element is the dirichlet concentration on the right side.\n#'\n#' @return A vector with \\strong{nt} number of elements with the values of mean concentration in the slab for each T\\emph{i}.\n#'\n#' @examples\n#' Lx <- 5 #Length of slab, in mm\n#' Tt <- 20 #Total measured diffusion time, in seconds\n#' nt <- 100 #Number of time discretization, wherein the Tt will be divided into 100 equal parts (0, 0.2, 0.4, ..., 20)\n#' nx <- 50 #Number of dimension discretization\n#' D <- 0.05 #Coefficient of diffusion in mm^2/s.\n#' C_ini <- 0.05 #Initial concentration inside the slab.\n#' C_lim <- c(0.10,0.25) #Dirichlet boundary concentration diffusing into the slab\n#' meanCt <- diff_1D_Ct(Lx, Tt, nt, nx, D, C_ini, C_lim)\n\ndiff_1D_Ct <- function(Lx,Tt,nt,nx,D,C_ini,C_lim){\n\n #Mean concentration value during each time step of 1-dimensional diffusion.\n #Will be useful for plotting\n\n Cmat <- diff_1D(Lx,Tt,nt,nx,D,C_ini,C_lim)\n\n Ct <- vector(mode=\"numeric\", length = nt)\n\n for (i in 1:nt) {\n\n Ct[i] <- mean(Cmat[,i])\n\n }\n\n return(Ct)\n\n}\n", "meta": {"hexsha": "f03eefa2dfc1a46c8eee153852611352690289d0", "size": 5786, "ext": "r", "lang": "R", "max_stars_repo_path": "R/funcs_diffs.r", "max_stars_repo_name": "ahmad-alkadri/Rdiffsolver", "max_stars_repo_head_hexsha": "5b4a37e4f7f3e92de72d146c6c457ac115e2d18c", "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/funcs_diffs.r", "max_issues_repo_name": "ahmad-alkadri/Rdiffsolver", "max_issues_repo_head_hexsha": "5b4a37e4f7f3e92de72d146c6c457ac115e2d18c", "max_issues_repo_licenses": ["MIT"], "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/funcs_diffs.r", "max_forks_repo_name": "ahmad-alkadri/Rdiffsolver", "max_forks_repo_head_hexsha": "5b4a37e4f7f3e92de72d146c6c457ac115e2d18c", "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.2222222222, "max_line_length": 377, "alphanum_fraction": 0.650362945, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.8278729276915211}} {"text": "library(repr) ; options(repr.plot.width = 5, repr.plot.height = 6) # Change plot sizes (in cm)\n\nrm(list = ls())\ngraphics.off()\n\nnll.slr <- function(par, dat, ...){\n args <- list(...)\n \n b0 <- par[1]\n b1 <- par[2]\n X <- dat$X\n Y <- dat$Y\n if(!is.na(args$sigma)){\n sigma <- args$sigma\n } else \n sigma <- par[3]\n\n mu <- b0+b1 * X\n \n return(-sum(dnorm(Y, mean=mu, sd=sigma, log=TRUE)))\n}\n\nset.seed(123)\nn <- 30\nb0 <- 10\nb1 <- 3\nsigma <- 2\nX <- rnorm(n, mean=3, sd=7)\nY <- b0 + b1 * X + rnorm(n, mean=0, sd=sigma)\ndat <- data.frame(X=X, Y=Y) # convert to a data frame\n\nplot(X, Y)\n\nN <- 50\nb0s <- seq(5, 15, length=N)\nmynll <- rep(NA, length=50)\nfor(i in 1:N){\n mynll[i] <- nll.slr(par=c(b0s[i],b1), dat=dat, sigma=sigma)\n}\n\nplot(b0s, mynll, type=\"l\")\nabline(v=b0, col=2)\nabline(v=b0s[which.min(mynll)], col=3)\n\nN0 <- 100\nN1 <- 101\nb0s <- seq(7,12, length=N0)\nb1s <- seq(1,5, length=N1)\n\nmynll <- matrix(NA, nrow=N0, ncol=N1)\nfor(i in 1:N0){\n for(j in 1:N1) mynll[i,j] <- nll.slr(par=c(b0s[i],b1s[j]), dat=dat, sigma=sigma)\n}\n\nww <- which(mynll==min(mynll), arr.ind=TRUE)\n\nb0.est <- b0s[ww[1]]\nb1.est <- b1s[ww[2]]\nrbind(c(b0, b1), c(b0.est, b1.est))\n\nfilled.contour(x = b0s, y = b1s, z= mynll, col=heat.colors(21), \n plot.axes = {axis(1); axis(2); points(b0,b1, pch=21); \n points(b0.est, b1.est, pch=8, cex=1.5); xlab=\"b0\"; ylab=\"b1\"})\n\npar(mfrow=c(1,2), bty=\"n\")\nplot(b0s, mynll[,ww[2]], type=\"l\", xlab=\"b0\", ylab=\"NLL\")\nplot(b1s, mynll[ww[1],], type=\"l\", xlab=\"b1\", ylab=\"NLL\")\n\nfit <- optim(nll.slr, par=c(2, 1), method=\"L-BFGS-B\", ## this is a n-D method\n lower=-Inf, upper=Inf, dat=dat, sigma=sigma)\n\nfit\n\nfit <- optim(nll.slr, par=c(2, 1, 5), method=\"L-BFGS-B\", ## this is a n-D method\n lower=c(-Inf, -Inf, 0.1), upper=Inf, dat=dat, sigma=NA)\nfit$par\n\nplot(X, Y)\nabline(a=fit$par[1], b=fit$par[2], col=2, lwd=2)\n\nfit <- optim(nll.slr, par=c(2, 1), method=\"L-BFGS-B\", hessian=TRUE, lower=-Inf, upper=Inf, dat=dat, sigma=sigma)\n\nfisher_info <- solve(fit$hessian)\nest_sigma <- sqrt(diag(fisher_info))\nupper <- fit$par+1.96 * est_sigma\nlower <- fit$par-1.96 * est_sigma\ninterval <- data.frame(value=fit$par, upper=upper, lower=lower)\ninterval\n\nlmfit <- lm(Y~X)\n\nsummary(lmfit)$coeff\n", "meta": {"hexsha": "fd7ca103a578be1f6e44d2cba2398fcacd64af94", "size": 2197, "ext": "r", "lang": "R", "max_stars_repo_path": "content/_build/jupyter_execute/notebooks/21-ModelFitting-MLE.r", "max_stars_repo_name": "nesbitm/VBiTE_2021", "max_stars_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-10-03T08:48:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T21:26:35.000Z", "max_issues_repo_path": "content/_build/jupyter_execute/notebooks/21-ModelFitting-MLE.r", "max_issues_repo_name": "nesbitm/VBiTE_2021", "max_issues_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2020-10-02T05:33:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T11:44:01.000Z", "max_forks_repo_path": "content/_build/jupyter_execute/notebooks/21-ModelFitting-MLE.r", "max_forks_repo_name": "nesbitm/VBiTE_2021", "max_forks_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63, "max_forks_repo_forks_event_min_datetime": "2017-12-04T14:08:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T11:37:36.000Z", "avg_line_length": 23.623655914, "max_line_length": 112, "alphanum_fraction": 0.6017296313, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.9019206692796966, "lm_q1q2_score": 0.8273342327436494}} {"text": "#!/usr/bin/env Rscript\n\n# dpois, ppois, qpois, rposi\n# d-密度函数后分布律\n# p-分布函数\n# q-分布函数的反函数,即给定概率p下,求其下分为点\n# r-仿真(产生相同分布随机数)\n\n# eg.1\n# Binom distribution\npar(mfrow=c(3,3))\nfor (i in seq(.1, .9, .1)) {\n barplot(dbinom(0:5, 5, i))\n # p == that 使用list里面的变量值变换替换\n title(main=(substitute(p == that, list(that = i))))\n}\n\n# eg.2\n# Possion distribution\n# type = \"b\": both - 点线\n# pch = n: 控制连接点的symbol\nplot(dpois(0:20, 3), type=\"b\", pch=15, xlab=\"k\", ylab=\"p(k)\")\npoints(dpois(0:20, 6), type=\"b\", pch=17)\npoints(dpois(0:20, 10), type=\"b\", pch=19)\n# text 在指定坐标输入txt\ntext(c(3.5, 6.5, 11.5), c(.18, .14, .09), \n c(expression(lambda==3), \n expression(lambda==6),\n expression(lambda==10)))\ntitle(main=\"Possion Distribution\")\n\n# eg.3 理解概率密度, 当连续型变量, 在某个值上的频数, 实际上非常小(因为连续分母很大)\nx = rnorm(100000)\npar(mfrow=c(2,2))\n# hist: 按n分成相等的份, 在该区间的频数和\nhist(x, 14, col=\"blue\", xlab=\"\", ylab=\"\", main=\"Histogram 1\")\nhist(x, 50, col=\"blue\", axes=FALSE, xlab=\"\", ylab=\"\", main=\"Histogram 2\")\nhist(x, 100, col=\"blue\", xlab=\"\", ylab=\"\", main=\"Histogram 2\")\n\n# 正态分布x>4, y接近0 (因为sigma=1, mu=0, 3*sigma --> 99%)\n# dnorm 是密度函数, 给定xs, 返回ys\nxs = seq(-4, 4, l=1000)\nys = dnorm(xs)\nplot(xs, ys, type=\"l\", axes=FALSE, xlab=\"\", ylab=\"\", main=\"Density\")\n# 多边形填充\npolygon(c(xs[xs>-4]), c(dnorm(c(xs[xs>-4]))), col=\"blue\")\n\n# eg.4 正态分布 不同值, 形状\nxs = seq(-5, 5, .001)\npar(mfrow=c(1,1))\nys1 = dnorm(xs, mean=-2, sd = .5)\nys2 = dnorm(xs, mean=0, sd = 1)\n# lty: line type\nplot(xs, ys1, type=\"l\", lty=2, xlab=\"\", ylab=\"\")\nlines(xs, ys2)\ntext(c(-2, 0), c(.3, .2), c(\"N(-2, 0.5)\", \"N(0,1)\"))\n\n# eg.5 pdf 密度函数积分(r1 --> r2)\nxs = c(seq(-4, 4, length=1000))\nys = dnorm(xs)\n\nr1 = 0.51\nr2 = 1.57\n\nxs2 = c(r1, r1, xs[xs>r1&xsr1&xs 0.8,arr.ind=T)\r\n\r\n\r\n\r\n#Correlated predictors\r\n\r\nnames(spam)[c(34,32)]\r\nplot(spam[,34],spam[,32])\r\n\r\n#Basic PCA idea\r\n\r\n#We might not need every predictor\r\n#A weighted combination of predictors might be better\r\n#We should pick this combination to capture the \"most information\" possible\r\n#Benefits\r\n#Reduced number of predictors\r\n#Reduced noise (due to averaging)\r\n\r\n\r\n\r\n#We could rotate the plot\r\n\r\n#$$ X = 0.71 \\times {\\rm num 415} + 0.71 \\times {\\rm num857}$$\r\n \r\n#$$ Y = 0.71 \\times {\\rm num 415} - 0.71 \\times {\\rm num857}$$\r\n \r\nX <- 0.71*training$num415 + 0.71*training$num857\r\nY <- 0.71*training$num415 - 0.71*training$num857\r\nplot(X,Y)\r\n\r\n#Related problems\r\n\r\n#You have multivariate variables $X_1,\\ldots,X_n$ so $X_1 = (X_{11},\\ldots,X_{1m})$\r\n \r\n#Find a new set of multivariate variables that are uncorrelated and explain as much variance as possible.\r\n#If you put all the variables together in one matrix, find the best matrix created with fewer variables (lower rank) that explains the original data.\r\n#The first goal is statistical and the second goal is data compression.\r\n\r\n\r\n#Related solutions - PCA/SVD\r\n\r\n#SVD\r\n\r\n#If $X$ is a matrix with each variable in a column and each observation in a row then the SVD is a \"matrix decomposition\"\r\n\r\n#$$ X = UDV^T$$\r\n \r\n#where the columns of $U$ are orthogonal (left singular vectors), the columns of $V$ are orthogonal (right singluar vectors) \r\n#and $D$ is a diagonal matrix (singular values).\r\n\r\n#PCA\r\n\r\n#The principal components are equal to the right singular values if you first scale (subtract the mean, divide by the standard deviation) the variables.\r\n\r\n\r\n#Principal components in R - prcomp\r\n\r\nsmallSpam <- spam[,c(34,32)]\r\nprComp <- prcomp(smallSpam)\r\nplot(prComp$x[,1],prComp$x[,2])\r\n\r\n\r\n#Principal components in R - prcomp\r\n\r\nprComp$rotation\r\n\r\n#PCA on SPAM data\r\n\r\ntypeColor <- ((spam$type==\"spam\")*1 + 1)\r\nprComp <- prcomp(log10(spam[,-58]+1))\r\nplot(prComp$x[,1],prComp$x[,2],col=typeColor,xlab=\"PC1\",ylab=\"PC2\")\r\n\r\n\r\n#PCA with caret\r\n\r\npreProc <- preProcess(log10(spam[,-58]+1),method=\"pca\",pcaComp=2)\r\nspamPC <- predict(preProc,log10(spam[,-58]+1))\r\nplot(spamPC[,1],spamPC[,2],col=typeColor)\r\n\r\n\r\n#Preprocessing with PCA\r\n\r\npreProc <- preProcess(log10(training[,-58]+1),method=\"pca\",pcaComp=2)\r\ntrainPC <- predict(preProc,log10(training[,-58]+1))\r\nmodelFit <- train(training$type ~ .,method=\"glm\",data=trainPC)\r\n\r\n#Preprocessing with PCA\r\n\r\ntestPC <- predict(preProc,log10(testing[,-58]+1))\r\nconfusionMatrix(testing$type,predict(modelFit,testPC))\r\n\r\n#Alternative (sets # of PCs)\r\n\r\nmodelFit <- train(training$type ~ .,method=\"glm\",preProcess=\"pca\",data=training)\r\nconfusionMatrix(testing$type,predict(modelFit,testing))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "01ac7da8fa236cc403432fd1bf168997d0a9286e", "size": 3043, "ext": "r", "lang": "R", "max_stars_repo_path": "PCA_Preprocessing.r", "max_stars_repo_name": "DamjanStefanovski/MachineLearningcoursera", "max_stars_repo_head_hexsha": "ae5a2be5f03ddb9e0b3ae5c7aa6a975245d03e4f", "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": "PCA_Preprocessing.r", "max_issues_repo_name": "DamjanStefanovski/MachineLearningcoursera", "max_issues_repo_head_hexsha": "ae5a2be5f03ddb9e0b3ae5c7aa6a975245d03e4f", "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": "PCA_Preprocessing.r", "max_forks_repo_name": "DamjanStefanovski/MachineLearningcoursera", "max_forks_repo_head_hexsha": "ae5a2be5f03ddb9e0b3ae5c7aa6a975245d03e4f", "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.6929824561, "max_line_length": 153, "alphanum_fraction": 0.6799211305, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.8254925339269342}} {"text": "newton.raphson <- function(f, ..., xguess=0, tol = 1e-5, n = 1000) {\r\n ## use newton raphson to find x where f(x, ...) = 0\r\n ## where \"...\" is a list of additional arguments needed by f, if any\r\n ## starts search from xguess\r\n \r\n ## following modified from https://rpubs.com/aaronsc32/newton-raphson-method\r\n library(numDeriv) # Package for computing f'(x)\r\n\r\n x0 <- xguess # Set start value to supplied guess\r\n k <- n # Initialize for iteration results\r\n\r\n ## Check to see if xguess result in 0\r\n if (f(x0, ...) == 0.0) return(x0)\r\n \r\n ## iterate to find where f(x, ...) = 0\r\n for (i in 1:n) {\r\n dx <- genD(func = f, ..., x = x0)$D[1] # First-order derivative f'(x0)\r\n x1 <- x0 - (f(x0, ...) / dx) # Calculate next guess x1\r\n k[i] <- x1 # Store x1\r\n ## Once the difference between x0 and x1 becomes sufficiently small, output the results.\r\n if (abs(x1 - x0) < tol) {\r\n root.approx <- tail(k, n=1)\r\n res <- list('root approximation' = root.approx, 'iterations' = k)\r\n return(res)\r\n }\r\n ## If Newton-Raphson has not yet reached convergence set x1 as x0 and continue\r\n x0 <- x1\r\n }\r\n print('Too many iterations in method')\r\n}\r\n\r\n## xtol_upper <- newton.raphson(function(x, parms=jparms, z=ztol_upper) john_z(x, parms) - z,\r\n## xguess = xmax, tol=1E-10)\r\n", "meta": {"hexsha": "6bf5252ad06edf980d94679c392894a0f64707d2", "size": 1456, "ext": "r", "lang": "R", "max_stars_repo_path": "modules/newton.raphson.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/newton.raphson.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/newton.raphson.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": 42.8235294118, "max_line_length": 97, "alphanum_fraction": 0.5418956044, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.825283489714627}} {"text": "library(rstudioapi)\nlibrary(ellipse)\nlibrary(ggplot2)\nthis.dir <- dirname(rstudioapi::getActiveDocumentContext()$path)\nsetwd(this.dir)\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])*eigen$vectors[,1]\nax2=c*sqrt(eigen$values[2])*eigen$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 #####\nlibrary(readr)\ne8_18 <- read_delim(\"e8_18.txt\", \" \", escape_double = FALSE, trim_ws = TRUE)\nnation = e8_18[,1]\nX = as.matrix(e8_18[,2:8])\nr = cor(X)\neigen = eigen(r)\nfirstpc = -1*eigen$vectors[,1]\nstdX <- scale(X)\nnew = stdX%*%firstpc\nnation[(sort.int(new,index.return = TRUE))$ix,]\n\n##### 8.27 #####\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}\ne8_27 <- read_delim(\"e8_27.txt\",\n \" \", escape_double = FALSE, trim_ws = TRUE)\nX = scale(as.matrix(e8_27))\npca <- prcomp(x = X, retx = TRUE, center = TRUE, scale. = TRUE)\nsummary(pca)\npc_correlations(pca)\nscreeplot(pca, type = \"lines\", pch = 19,\n main = \"Screeplot of pulp and paper properties Data\")\ne8_27$y1 = X%*%pca$rotation[,1]\ne8_27$y2 = X%*%pca$rotation[,2]\nggplot(data = e8_27, aes(x = y2, y = y1)) + geom_point()+ggtitle(\"Scatterplot of Y1hat and Y2hat\")\n", "meta": {"hexsha": "5fa513fb449f9dc9ea33bda05472a9ffa4a8d1d1", "size": 2059, "ext": "r", "lang": "R", "max_stars_repo_path": "Statistics/STA 135/hw5/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/hw5/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/hw5/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": 31.196969697, "max_line_length": 128, "alphanum_fraction": 0.629431763, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.8246038000068553}} {"text": "### 6.2-2\n\nexperData <- c(28, 32, 15, 14, 38, 43, 19)\nnSamples <- length(experData)\nexperMean <- mean(experData)\n\nchiSquare <- sum((experData - experMean)^2 / experMean)\nprint(chiSquare)\n\n### df = r - k - 1 = 7 - 1 = 6 \nchiSquareCritical <- qchisq(0.95, nSamples-1, ncp=0, lower.tail=TRUE, log.p=FALSE) \nprint(chiSquareCritical)\n\n### chiSquare = 28.88889 -> H0 is rejected (the dataset is not uniformly distributed)\n", "meta": {"hexsha": "2e6bf349ad174f6e3fe26976eca5b901f99a79e4", "size": 418, "ext": "r", "lang": "R", "max_stars_repo_path": "TASK3/sem3/chiSq1.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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": "TASK3/sem3/chiSq1.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TASK3/sem3/chiSq1.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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.8666666667, "max_line_length": 87, "alphanum_fraction": 0.6698564593, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8596637451167995, "lm_q1q2_score": 0.8245501670168434}} {"text": "# 2.2 a)\n'''\nInstall the R-package astsa, load the package and the dataset varve. You may use\nthe following code:\n\tinstall.packages(\"astsa\")\n\tlibrary(astsa)\n\tdata(varve)\nPlot the glacial varve data.\nThe time series exhibits some nonstationarity that can be improved by transforming to \nlogarithms and some additional nonstationarity that can be corrected by\ndifferencing the logarithms.\n'''\n\ninstall.packages(\"astsa\")\nlibrary(astsa)\ndata(varve)\n\nplot(varve)\n\n#b)\n'''\nArgue that the glacial varves series, say Xt, \nexhibits heteroscedasticity by computing the sample variance over the first half and the second half of the data. \nArgue that the transformation Yt = log Xt stabilizes the variance over the series. \nPlot the histograms of Xt and Yt to see whether the approximation to normality \nis improved by transforming the data.\n'''\n\nhist(varve, breaks = 10)\n#Not so different\nfor (i in c(0:9)){\n\tsample = sample.int(n=length(varve), size=0.5*length(varve))\n\tprint(var(varve[sample]))\n\tprint(var(varve[-sample]))\n\tprint(\"********\")\n}\n\n#different variance\nsubset = seq(from = 1,to = length(varve)/2, by = 1)\nvar(varve[subset])\nvar(varve[-subset])\n\n#log-transformation\ny = log(varve)\npar(mfrow=c(1,2))\nhist(y, breaks = 20, prob=TRUE)\nlines(dt <- seq(0,150,0.1), dnorm(dt, mean(y), sd(y)), col=2, lty=2)\nhist(varve, breaks=10, prob=TRUE)\nlines(dt <- seq(0,150,0.1), dnorm(dt, mean(varve),sd(varve)), col=2, lty=2)\n\n'''\nheteroscedasticity is the variability of a variable is unequal across the range of values of a second variable that predicts it\nAfter log transform - the variable is symmetic about its mean - so more normal.\n'''\n\n#c) Plot the series Yt\nplot(log(varve),lty=1)\n\n#d) Examine the sample ACF of Yt and comment.\nacf(log(varve), lag.max= 40))\nacf(log(varve), lag.max= 150))\nacf(varve, lag.max= 150))\n\n#looking at plot in c) Y_t oscilates, acf(y) oscilates and acf is declining \n#So there is trend and seasonality\n\n#e)\n'''\nCompute the difference Ut = Yt - Yt−1 , examine its time plot and sample ACF,\nand argue that differencing the logged varve data produces a reasonably stationary\nseries. Can you think of a practical interpretation for Ut ?\n'''\n\n#U_t is the differenced (differenciated) time-series of Y_t - so without trend\nU_t_x= diff(varve, lag = 1)\nplot(U_t_x)\nU_t= diff(y, lag = 1)\nplot(U_t)\n\nacf(U_t, lag.max=150)\n\n#U_t is the definition of derivative when h=1. Since time discrete this is smallest h.\n\n#f)\n'''\nBased on the sample ACF of the differenced transformed series computed in (d),\nargue that the model in (1) below might be reasonable. \n\nAssume U_t = mu + Z_t + theta*Z_t-1\n\nis stationary when the inputs Zt are assumed independent with mean 0 and variance sigma_z**2\nThen, show ACVF: (1+theta**2) , h=0, theta*sima_z**2, h=1, 0 else\n'''\n\n#see paper solution - its a MA(1) processs\n\n# g)\n'''\nBased on part (f), use ρbU (1) and the estimate of the variance of Ut\n, γ_U (1) ), to\nderive estimates of θ and σ\n2\nZ\n. This is an application of the method of moments\nfrom classical statistics, where estimators of the parameters are derived by equating\nsample moments to theoretical moments. You can calculate the empirical autocorrelation and autocovariance functions \nusing the acf function, by using the following syntax\n\tacf(u, type = \"correlation\")\n\tacf(u, type = \"covariance\")\n'''\n\nacf(U_t, type = \"correlation\")\nacf(U_t, type = \"covariance\")\n\n(a<-acf(U_t, plot=FALSE)$acf[2])\n(b<-acf(U_t, type=\"covariance\", plot=FALSE)$acf[1])\n(theta <- (1 + c(-1,1) * sqrt(1 - 4 * a^2))/(2 * a))\n(sigma2<- b / (1 + theta^2))\narima(U_t, order=c(0,0,1), include.mean=FALSE)\n\n########\np <- as.vector(acf(Ut, type = \"correlation\", lag.max = 1, plot=FALSE)$acf[2]) #rho\ng <- as.vector(acf(Ut, type = \"covariance\", lag.max = 0, plot=FALSE)$acf) #g=gamma\n\ntheta <- c((1+sqrt(1-4*p^2))/(2*p),(1-sqrt(1-4*p^2))/(2*p))\nsigmasq <- g/(1+theta^2)\n\ntheta\nsigmasq\n#Need |theta| < 1 to be invertible, thus the solution is\n#theta hat = -0.494 and sigmasq hat = 0.266\n\n\n\n", "meta": {"hexsha": "9c0677eb79f5535f46bfdf3fbe1fcd715495101e", "size": 3967, "ext": "r", "lang": "R", "max_stars_repo_path": "hw2/hw2.r", "max_stars_repo_name": "emoen/Time_Series_stat211", "max_stars_repo_head_hexsha": "f30eb0c6a34c1eab8d347670c3b7a54f2c4c89c0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-06T19:14:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:14:00.000Z", "max_issues_repo_path": "hw2/hw2.r", "max_issues_repo_name": "emoen/Time_Series_stat211", "max_issues_repo_head_hexsha": "f30eb0c6a34c1eab8d347670c3b7a54f2c4c89c0", "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": "hw2/hw2.r", "max_forks_repo_name": "emoen/Time_Series_stat211", "max_forks_repo_head_hexsha": "f30eb0c6a34c1eab8d347670c3b7a54f2c4c89c0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-22T07:40:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T07:40:48.000Z", "avg_line_length": 29.3851851852, "max_line_length": 127, "alphanum_fraction": 0.7085959163, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8840392817460332, "lm_q1q2_score": 0.8243253534266344}} {"text": "\r\n\r\n# Goal: Simulation to study size and power in a simple problem.\r\n\r\nset.seed(101)\r\n\r\n# The data generating process: a simple uniform distribution with stated mean\r\ndgp <- function(N,mu) {runif(N)-0.5+mu}\r\n\r\n# Simulate one FIXED hypothesis test for H0:mu=0, given a true mu for a sample size N\r\none.test <- function(N, truemu) {\r\n x <- dgp(N,truemu)\r\n muhat <- mean(x)\r\n s <- sd(x)/sqrt(N)\r\n # Under the null, the distribution of the mean has standard error s\r\n threshold <- 1.96*s\r\n (muhat < -threshold) || (muhat > threshold)\r\n} # Return of TRUE means reject the null\r\n\r\n# Do one experiment, where the fixed H0:mu=0 is run Nexperiments times with a sample size N.\r\n# We return only one number: the fraction of the time that H0 is rejected.\r\nexperiment <- function(Nexperiments, N, truemu) {\r\n sum(replicate(Nexperiments, one.test(N, truemu)))/Nexperiments\r\n}\r\n\r\n# Measure the size of a test, i.e. rejections when H0 is true\r\nexperiment(10000, 50, 0)\r\n# Measurement with sample size of 50, and true mu of 0.\r\n\r\n# Power study: I.e. Pr(rejection) when H0 is false\r\n# (one special case in here is when the H0 is actually true)\r\n\r\nmuvalues <- seq(-.15,.15,.01)\r\n # When true mu < -0.15 and when true mu > 0.15,\r\n # the Pr(rejection) veers to 1 (full power) and it's not interesting.\r\n\r\n# First do this with sample size of 50\r\nresults <- NULL\r\nfor (truth in muvalues) {\r\n results <- c(results, experiment(10000, 50, truth))\r\n}\r\npar(mai=c(.8,.8,.2,.2))\r\nplot(muvalues, results, type=\"l\", lwd=2, ylim=c(0,1),\r\n xlab=\"True mu\", ylab=\"Pr(Rejection of H0:mu=0)\")\r\nabline(h=0.05, lty=2)\r\n\r\n# Now repeat this with sample size of 100 (should yield a higher power)\r\nresults <- NULL\r\nfor (truth in muvalues) {\r\n results <- c(results, experiment(10000, 100, truth))\r\n}\r\nlines(muvalues, results, lwd=2, col=\"blue\")\r\nlegend(x=-0.15, y=.2, lwd=c(2,1,2), lty=c(1,2,1), cex=.8,\r\n col=c(\"black\",\"black\",\"blue\"), bty=\"n\",\r\n legend=c(\"N=50\", \"Size, 0.05\", \"N=100\"))\r\n\r\n", "meta": {"hexsha": "db8f2b1c31a7be30ab1ad7ce3d607fc1bf7a6e2d", "size": 1975, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p11.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)/p11.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)/p11.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.649122807, "max_line_length": 93, "alphanum_fraction": 0.6572151899, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.8840392741081575, "lm_q1q2_score": 0.8243253446452652}} {"text": "# Introduction to Computational Finance and Financial Econometrics\n# Assignment 2\n# Paul-Gabriel Müller\n# Topic: Probability\n\n# question 1:\n# Suppose X is a normally distributed random variable with mean 0.05 and variance (0.10)2. Compute the following.\n# a) Pr(X>.10)\n1- pnorm(0.1, mean=0.05, sd=0.1)\n\n# question 2:\n# Suppose X is a normally distributed random variable with mean 0.05 and variance (0.10)2. Compute the following.\n# Pr(X<−.10)\npnorm(-0.1, mean=0.05, sd=0.1)\n\n# question 3:\n# Suppose X is a normally distributed random variable with mean 0.05 and variance (0.10)2. Compute the following.\n# c) Pr(−0.05 r = ln(1+R)\nr.01 = qnorm(0.01, mean=0.04, sd=0.09)\nr.05 = qnorm(0.05, mean=0.04, sd=0.09)\n\nR.01 = exp(r.01) -1\nR.05 = exp(r.05) -1\n\nR.01*w0\nR.05*w0\n\n#Question 11\n# For the following questions:\n \n# Consider a one month investment in two Northwest stocks: Amazon and Costco. \n# Suppose you buy Amazon and Costco at the end of September at P(A,t−1)=$38.23, P(C,t−1)=$41.11 and then sell \n# at the end of October for P(A,t)=$41.29, P(C,t)=$41.74. (Note: these are actual closing prices for 2004 taken \n# from Yahoo!)\n# What are the simple monthly returns for the two stocks?\n\nR.A = (41.29 - 38.23) / 38.23\nR.C = (41.74 - 41.11) / 41.11\n# Question 12\n# What are the continuously compounded returns for the two stocks?\nr.A = log(1 + R.A)\nr.C = log(1 + R.C)\nr.A\nr.C\n\n# Question 13\n# Suppose Amazon paid a $0.10 per share cash dividend at the end of October. \n# What is the monthly simple total return on Amazon? What is the monthly dividend yield?\n\nRsimple = (41.29 + 0.1 - 38.23) / 38.23 \ndivYield = 0.01 / 38.23\nRsimple * 100\ndivYield * 100\n\n#question 14\n# Suppose the monthly returns on Amazon from question 12 above are the same every month for 1 year.\n# Compute the simple annual returns, as well as the continuously compounded annual returns. \n# r is always smaller than R\nR.month = (41.29 - 38.23) / 38.23\nR.year = ((1+R.month)^12) -1\nR.year*100\n\nr.year = log(1+R.year)\nr.year*100\n# Question 15\nQuestion 15\n# At the end of September 2004, supposed you have $10,000 to invest in Amazon and Costco over the next month.\n# If you invest $8,000 in Amazon and $2,000 in Costco, what are your portfolio shares, xA and xC.\n\n# Question 16\n# Continuing with the previous question, compute the monthly simple return on the portfolio.\n# Assume than no dividends are paid. \n\nR.total = 0.8 * R.A + 0.2*R.C\nR.total*100\n", "meta": {"hexsha": "dc137534d41e012e4debbdee44173ba8af132c11", "size": 4492, "ext": "r", "lang": "R", "max_stars_repo_path": "test_files/R.r", "max_stars_repo_name": "pheonixo/file_info", "max_stars_repo_head_hexsha": "1585f9938e591ea92312f49d9d2d7481951d9e18", "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_files/R.r", "max_issues_repo_name": "pheonixo/file_info", "max_issues_repo_head_hexsha": "1585f9938e591ea92312f49d9d2d7481951d9e18", "max_issues_repo_licenses": ["MIT"], "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_files/R.r", "max_forks_repo_name": "pheonixo/file_info", "max_forks_repo_head_hexsha": "1585f9938e591ea92312f49d9d2d7481951d9e18", "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.7744360902, "max_line_length": 113, "alphanum_fraction": 0.7005788068, "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642557, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.8239458453300226}} {"text": "library(repr) ; options(repr.plot.width = 5, repr.plot.height = 6) # Change plot sizes (in cm)\n\nrm(list = ls())\ngraphics.off()\n\nrequire(\"minpack.lm\") # for Levenberg-Marquardt nlls fitting\n\npowMod <- function(x, a, b) {\n return(a * x^b)\n}\n\nMyData <- read.csv(\"../data/GenomeSize.csv\")\n\nhead(MyData)\n\nData2Fit <- subset(MyData,Suborder == \"Anisoptera\")\n\nData2Fit <- Data2Fit[!is.na(Data2Fit$TotalLength),] # remove NA's\n\nplot(Data2Fit$TotalLength, Data2Fit$BodyWeight)\n\nlibrary(\"ggplot2\")\n\nggplot(Data2Fit, aes(x = TotalLength, y = BodyWeight)) + \ngeom_point(size = (3),color=\"red\") + theme_bw() + \nlabs(y=\"Body mass (mg)\", x = \"Wing length (mm)\")\n\nPowFit <- nlsLM(BodyWeight ~ powMod(TotalLength, a, b), data = Data2Fit, start = list(a = .1, b = .1))\n\nsummary(PowFit)\n\nLengths <- seq(min(Data2Fit$TotalLength),max(Data2Fit$TotalLength),len=200)\n\ncoef(PowFit)[\"a\"]\ncoef(PowFit)[\"b\"]\n\nPredic2PlotPow <- powMod(Lengths,coef(PowFit)[\"a\"],coef(PowFit)[\"b\"])\n\nExercisesplot(Data2Fit$TotalLength, Data2Fit$BodyWeight)\nlines(Lengths, Predic2PlotPow, col = 'blue', lwd = 2.5)\n\nconfint(PowFit)\n\nQuaFit <- lm(BodyWeight ~ poly(TotalLength,2), data = Data2Fit)\n\nPredic2PlotQua <- predict.lm(QuaFit, data.frame(TotalLength = Lengths))\n\nplot(Data2Fit$TotalLength, Data2Fit$BodyWeight)\nlines(Lengths, Predic2PlotPow, col = 'blue', lwd = 2.5)\nlines(Lengths, Predic2PlotQua, col = 'red', lwd = 2.5)\n\nRSS_Pow <- sum(residuals(PowFit)^2) # Residual sum of squares\nTSS_Pow <- sum((Data2Fit$BodyWeight - mean(Data2Fit$BodyWeight))^2) # Total sum of squares\nRSq_Pow <- 1 - (RSS_Pow/TSS_Pow) # R-squared value\n\nRSS_Qua <- sum(residuals(QuaFit)^2) # Residual sum of squares\nTSS_Qua <- sum((Data2Fit$BodyWeight - mean(Data2Fit$BodyWeight))^2) # Total sum of squares\nRSq_Qua <- 1 - (RSS_Qua/TSS_Qua) # R-squared value\n\nRSq_Pow \nRSq_Qua\n\nn <- nrow(Data2Fit) #set sample size\npPow <- length(coef(PowFit)) # get number of parameters in power law model\npQua <- length(coef(QuaFit)) # get number of parameters in quadratic model\n\nAIC_Pow <- n + 2 + n * log((2 * pi) / n) + n * log(RSS_Pow) + 2 * pPow\nAIC_Qua <- n + 2 + n * log((2 * pi) / n) + n * log(RSS_Qua) + 2 * pQua\nAIC_Pow - AIC_Qua\n\nAIC(PowFit) - AIC(QuaFit)\n\nalb <- read.csv(file=\"../data/albatross_grow.csv\")\nalb <- subset(x=alb, !is.na(alb$wt))\nplot(alb$age, alb$wt, xlab=\"age (days)\", ylab=\"weight (g)\", xlim=c(0, 100))\n\nlogistic1 <- function(t, r, K, N0){\n N0 * K * exp(r * t)/(K+N0 * (exp(r * t)-1))\n}\n\nvonbert.w <- function(t, Winf, c, K){\n Winf * (1 - exp(-K * t) + c * exp(-K * t))^3\n}\n\nscale <- 4000\n\nalb.lin <- lm(wt/scale ~ age, data = alb)\n\nalb.log <- nlsLM(wt/scale~logistic1(age, r, K, N0), start=list(K=1, r=0.1, N0=0.1), data=alb)\n\nalb.vb <- nlsLM(wt/scale~vonbert.w(age, Winf, c, K), start=list(Winf=0.75, c=0.01, K=0.01), data=alb)\n\nages <- seq(0, 100, length=1000)\n\npred.lin <- predict(alb.lin, newdata = list(age=ages)) * scale\n\npred.log <- predict(alb.log, newdata = list(age=ages)) * scale\n\npred.vb <- predict(alb.vb, newdata = list(age=ages)) * scale\n\nplot(alb$age, alb$wt, xlab=\"age (days)\", ylab=\"weight (g)\", xlim=c(0,100))\nlines(ages, pred.lin, col=2, lwd=2)\nlines(ages, pred.log, col=3, lwd=2)\nlines(ages, pred.vb, col=4, lwd=2)\n\nlegend(\"topleft\", legend = c(\"linear\", \"logistic\", \"Von Bert\"), lwd=2, lty=1, col=2:4)\n\npar(mfrow=c(3,1), bty=\"n\")\nplot(alb$age, resid(alb.lin), main=\"LM resids\", xlim=c(0,100))\nplot(alb$age, resid(alb.log), main=\"Logisitic resids\", xlim=c(0,100))\nplot(alb$age, resid(alb.vb), main=\"VB resids\", xlim=c(0,100))\n\nn <- length(alb$wt)\nlist(lin=signif(sum(resid(alb.lin)^2)/(n-2 * 2), 3), \n log= signif(sum(resid(alb.log)^2)/(n-2 * 3), 3), \n vb= signif(sum(resid(alb.vb)^2)/(n-2 * 3), 3)) \n\naedes <- read.csv(file=\"../data/aedes_fecund.csv\")\n\nplot(aedes$T, aedes$EFD, xlab=\"temperature (C)\", ylab=\"Eggs/day\")\n\nquad1 <- function(T, T0, Tm, c){\n c * (T-T0) * (T-Tm) * as.numeric(TT0)\n}\n\nbriere <- function(T, T0, Tm, c){\n c * T * (T-T0) * (abs(Tm-T)^(1/2)) * as.numeric(TT0)\n}\n\nscale <- 20\n\naed.lin <- lm(EFD/scale ~ T, data=aedes)\n\naed.quad <- nlsLM(EFD/scale~quad1(T, T0, Tm, c), start=list(T0=10, Tm=40, c=0.01), data=aedes)\n\naed.br <- nlsLM(EFD/scale~briere(T, T0, Tm, c), start=list(T0=10, Tm=40, c=0.1), data=aedes)\n\nt <- seq(0, 22, 2)\nN <- c(32500, 33000, 38000, 105000, 445000, 1430000, 3020000, 4720000, 5670000, 5870000, 5930000, 5940000)\n\nset.seed(1234) # set seed to ensure you always get the same random sequence \n\ndata <- data.frame(t, N * (1 + rnorm(length(t), sd = 0.1))) # add some random error\n\nnames(data) <- c(\"Time\", \"N\")\n\nhead(data)\n\nggplot(data, aes(x = Time, y = N)) + \n geom_point(size = 3) +\n labs(x = \"Time (Hours)\", y = \"Population size (cells)\")\n\ndata$LogN <- log(data$N)\n\n# visualise\nggplot(data, aes(x = t, y = LogN)) + \n geom_point(size = 3) +\n labs(x = \"Time (Hours)\", y = \"log(cell number)\")\n\n(data[data$Time == 10,]$LogN - data[data$Time == 6,]$LogN)/(10-6)\n\ndiff(data$LogN)\n\nmax(diff(data$LogN))/2 # 2 is the difference in any successive pair of timepoints\n\nlm_growth <- lm(LogN ~ Time, data = data[data$Time > 2 & data$Time < 12,])\nsummary(lm_growth)\n\nlogistic_model <- function(t, r_max, K, N_0){ # The classic logistic equation\n return(N_0 * K * exp(r_max * t)/(K + N_0 * (exp(r_max * t) - 1)))\n}\n\n# first we need some starting parameters for the model\nN_0_start <- min(data$N) # lowest population size\nK_start <- max(data$N) # highest population size\nr_max_start <- 0.62 # use our estimate from the OLS fitting from above\n\nfit_logistic <- nlsLM(N ~ logistic_model(t = Time, r_max, K, N_0), data,\n list(r_max=r_max_start, N_0 = N_0_start, K = K_start))\n\nsummary(fit_logistic)\n\ntimepoints <- seq(0, 22, 0.1)\n\nlogistic_points <- logistic_model(t = timepoints, \n r_max = coef(fit_logistic)[\"r_max\"], \n K = coef(fit_logistic)[\"K\"], \n N_0 = coef(fit_logistic)[\"N_0\"])\ndf1 <- data.frame(timepoints, logistic_points)\ndf1$model <- \"Logistic equation\"\nnames(df1) <- c(\"Time\", \"N\", \"model\")\n\nggplot(data, aes(x = Time, y = N)) +\n geom_point(size = 3) +\n geom_line(data = df1, aes(x = Time, y = N, col = model), size = 1) +\n theme(aspect.ratio=1)+ # make the plot square \n labs(x = \"Time\", y = \"Cell number\")\n\nggplot(data, aes(x = Time, y = LogN)) +\n geom_point(size = 3) +\n geom_line(data = df1, aes(x = Time, y = log(N), col = model), size = 1) +\n theme(aspect.ratio=1)+ \n labs(x = \"Time\", y = \"log(Cell number)\")\n\nggplot(data, aes(x = N, y = LogN)) +\n geom_point(size = 3) +\n theme(aspect.ratio = 1)+ \n labs(x = \"N\", y = \"log(N)\")\n\ngompertz_model <- function(t, r_max, K, N_0, t_lag){ # Modified gompertz growth model (Zwietering 1990)\n return(N_0 + (K - N_0) * exp(-exp(r_max * exp(1) * (t_lag - t)/((K - N_0) * log(10)) + 1)))\n} \n\nN_0_start <- min(data$LogN) # lowest population size, note log scale\nK_start <- max(data$LogN) # highest population size, note log scale\nr_max_start <- 0.62 # use our previous estimate from the OLS fitting from above\nt_lag_start <- data$Time[which.max(diff(diff(data$LogN)))] # find last timepoint of lag phase\n\ndiff(data$LogN) # same as what we did above - get differentials\n\ndiff(diff(data$LogN)) # get the differentials of the differentials (approx 2nd order derivatives)\n\nwhich.max(diff(diff(data$LogN))) # find the timepoint where this 2nd order derivative really takes off \n\ndata$Time[which.max(diff(diff(data$LogN)))] # This then is a good guess for the last timepoint of the lag phase\n\nfit_gompertz <- nlsLM(LogN ~ gompertz_model(t = Time, r_max, K, N_0, t_lag), data,\n list(t_lag=t_lag_start, r_max=r_max_start, N_0 = N_0_start, K = K_start))\n\nsummary(fit_gompertz)\n\ntimepoints <- seq(0, 24, 0.1)\n\nlogistic_points <- log(logistic_model(t = timepoints, \n r_max = coef(fit_logistic)[\"r_max\"], \n K = coef(fit_logistic)[\"K\"], \n N_0 = coef(fit_logistic)[\"N_0\"]))\n\ngompertz_points <- gompertz_model(t = timepoints, \n r_max = coef(fit_gompertz)[\"r_max\"], \n K = coef(fit_gompertz)[\"K\"], \n N_0 = coef(fit_gompertz)[\"N_0\"], \n t_lag = coef(fit_gompertz)[\"t_lag\"])\n\ndf1 <- data.frame(timepoints, logistic_points)\ndf1$model <- \"Logistic model\"\nnames(df1) <- c(\"Time\", \"LogN\", \"model\")\n\ndf2 <- data.frame(timepoints, gompertz_points)\ndf2$model <- \"Gompertz model\"\nnames(df2) <- c(\"Time\", \"LogN\", \"model\")\n\nmodel_frame <- rbind(df1, df2)\n\nggplot(data, aes(x = Time, y = LogN)) +\n geom_point(size = 3) +\n geom_line(data = model_frame, aes(x = Time, y = LogN, col = model), size = 1) +\n theme_bw() + # make the background white\n theme(aspect.ratio=1)+ # make the plot square \n labs(x = \"Time\", y = \"log(Abundance)\")\n\nnll.slr <- function(par, dat, ...){\n args <- list(...)\n \n b0 <- par[1]\n b1 <- par[2]\n X <- dat$X\n Y <- dat$Y\n if(!is.na(args$sigma)){\n sigma <- args$sigma\n } else \n sigma <- par[3]\n\n mu <- b0+b1 * X\n \n return(-sum(dnorm(Y, mean=mu, sd=sigma, log=TRUE)))\n}\n\nset.seed(123)\nn <- 30\nb0 <- 10\nb1 <- 3\nsigma <- 2\nX <- rnorm(n, mean=3, sd=7)\nY <- b0 + b1 * X + rnorm(n, mean=0, sd=sigma)\ndat <- data.frame(X=X, Y=Y) # convert to a data frame\n\nplot(X, Y)\n\nN <- 50\nb0s <- seq(5, 15, length=N)\nmynll <- rep(NA, length=50)\nfor(i in 1:N){\n mynll[i] <- nll.slr(par=c(b0s[i],b1), dat=dat, sigma=sigma)\n}\n\nplot(b0s, mynll, type=\"l\")\nabline(v=b0, col=2)\nabline(v=b0s[which.min(mynll)], col=3)\n\nN0 <- 100\nN1 <- 101\nb0s <- seq(7,12, length=N0)\nb1s <- seq(1,5, length=N1)\n\nmynll <- matrix(NA, nrow=N0, ncol=N1)\nfor(i in 1:N0){\n for(j in 1:N1) mynll[i,j] <- nll.slr(par=c(b0s[i],b1s[j]), dat=dat, sigma=sigma)\n}\n\nww <- which(mynll==min(mynll), arr.ind=TRUE)\n\nb0.est <- b0s[ww[1]]\nb1.est <- b1s[ww[2]]\nrbind(c(b0, b1), c(b0.est, b1.est))\n\nfilled.contour(x = b0s, y = b1s, z= mynll, col=heat.colors(21), \n plot.axes = {axis(1); axis(2); points(b0,b1, pch=21); \n points(b0.est, b1.est, pch=8, cex=1.5); xlab=\"b0\"; ylab=\"b1\"})\n\npar(mfrow=c(1,2), bty=\"n\")\nplot(b0s, mynll[,ww[2]], type=\"l\", xlab=\"b0\", ylab=\"NLL\")\nplot(b1s, mynll[ww[1],], type=\"l\", xlab=\"b1\", ylab=\"NLL\")\n\nfit <- optim(nll.slr, par=c(2, 1), method=\"L-BFGS-B\", ## this is a n-D method\n lower=-Inf, upper=Inf, dat=dat, sigma=sigma)\n\nfit\n\nfit <- optim(nll.slr, par=c(2, 1, 5), method=\"L-BFGS-B\", ## this is a n-D method\n lower=c(-Inf, -Inf, 0.1), upper=Inf, dat=dat, sigma=NA)\nfit$par\n\nplot(X, Y)\nabline(a=fit$par[1], b=fit$par[2], col=2, lwd=2)\n\nfit <- optim(nll.slr, par=c(2, 1), method=\"L-BFGS-B\", hessian=TRUE, lower=-Inf, upper=Inf, dat=dat, sigma=sigma)\n\nfisher_info <- solve(fit$hessian)\nest_sigma <- sqrt(diag(fisher_info))\nupper <- fit$par+1.96 * est_sigma\nlower <- fit$par-1.96 * est_sigma\ninterval <- data.frame(value=fit$par, upper=upper, lower=lower)\ninterval\n\nlmfit <- lm(Y~X)\n\nsummary(lmfit)$coeff\n\nset.seed(54321)\n\n## 50 draws with each p \npp <- c(0.1, 0.5, 0.8)\nN <- 20\nreps <- 50 \n\n## histograms + density here\nx <- seq(0, 50, by=1)\npar(mfrow=c(1,3), bty=\"n\")\n\n# Write more code here\n\n## MOM estimators for 3 simulated sets\n\n\n## MoM estimates, histogram \n\npp <- .25\nN <- 10\nreps <- 10\n## Make one set of data\n\n## the likelihood is always exactly zero\n## at p=0,1, so I skip those values\nps <- seq(0.01, 0.99, by=0.01) \n\n## Likelihood\n\n\n## MLE/MoM estimators \n\n## now plot the negative log likelihood profile\n\n\nWL.data <- read.csv(\"../data/MidgeWingLength.csv\")\nY <- WL.data$WingLength\nn <- length(Y)\n\nhist(Y,breaks=10,xlab=\"Wing Length (mm)\") \n\nm <- sum(Y)/n\ns2 <- sum((Y-m)^2)/(n-1)\nround(c(m, s2), 3)\n\nx <- seq(1.4,2.2, length=50)\nhist(Y,breaks=10,xlab=\"Wing Length (mm)\", xlim=c(1.4, 2.2), freq=FALSE) \nlines(x, dnorm(x, mean=m, sd=sqrt(s2)), col=2)\n\ntau.post <- function(tau, tau0, n){n * tau + tau0}\nmu.post <- function(Ybar, mu0, sig20, sig2, n){\n weight <- sig2+n * sig20\n \n return(n * sig20 * Ybar/weight + sig2 * mu0/weight)\n}\n\nmu0 <- 1.9\ns20 <- 0.8\ns2 <- 0.025 ## \"true\" variance\n\nmp <- mu.post(Ybar=m, mu0=mu0, sig20=s20, sig2=s2, n=n)\ntp <- tau.post(tau=1/s2, tau0=1/s20, n=n)\n\nx <- seq(1.3,2.3, length=1000)\nhist(Y,breaks=10,xlab=\"Wing Length (mm)\", xlim=c(1.3, 2.3),\n freq=FALSE, ylim=c(0,8)) \nlines(x, dnorm(x, mean=mu0, sd=sqrt(s20)), col=2, lty=2, lwd=2) ## prior\nlines(x, dnorm(x, mean=mp, sd=sqrt(1/tp)), col=4, lwd=2) ## posterior\nlegend(\"topleft\", legend=c(\"prior\", \"posterior\"), col=c(2,4), lty=c(2,1), lwd=2)\n\n# Load libraries\nrequire(rjags) # does the fitting\nrequire(coda) # makes diagnostic plots\n##require(mcmcplots) # another option for diagnostic plots\n\nmodel1 <- \"model{\n\n ## Likelihood\n for(i in 1:n){\n Y[i] ~ dnorm(mu,tau)\n }\n\n ## Prior for mu\n mu ~ dnorm(mu0,tau0)\n\n} ## close model \n\"\n\nmodel <- jags.model(textConnection(model1), \n n.chains = 1, ## usually do more\n data = list(Y=Y,n=n, ## data\n mu0=mu0, tau0=1/s20, ## hyperparams\n tau = 1/s2 ## known precision\n ),\n inits=list(mu=3) ## setting an starting val\n )\n\nsamp <- coda.samples(model, \n variable.names=c(\"mu\"), \n n.iter=1000, progress.bar=\"none\")\n\nplot(samp)\n\nupdate(model, 10000, progress.bar=\"none\") # Burnin for 10000 samples\n\nsamp <- coda.samples(model, \n variable.names=c(\"mu\"), \n n.iter=20000, progress.bar=\"none\")\n\nplot(samp)\n\nsummary(samp)\n\nx <- seq(1.3,2.3, length=1000)\nhist(samp[[1]], xlab=\"mu\", xlim=c(1.3, 2.3),\n freq=FALSE, ylim=c(0,8), main =\"posterior samples\") \nlines(x, dnorm(x, mean=mu0, sd=sqrt(s20)), col=2, lty=2, lwd=2) ## prior\nlines(x, dnorm(x, mean=mp, sd=sqrt(1/tp)), col=4, lwd=2) ## posterior\nlegend(\"topleft\", legend=c(\"prior\", \"analytic posterior\"), col=c(2,4), lty=c(2,1), lwd=2)\n\nmodel2 <- \"model{\n\n # Likelihood\n for(i in 1:n){\n Y[i] ~ dnorm(mu,tau) T(0,) ## truncates at 0\n }\n\n # Prior for mu\n mu ~ dnorm(mu0,tau0)\n\n # Prior for the precision\n tau ~ dgamma(a, b)\n\n # Compute the variance\n s2 <- 1/tau\n}\"\n\n## hyperparams for tau\na <- 0.01\nb <- 0.01\n\nm2 <- jags.model(textConnection(model2), \n n.chains = 1,\n data = list(Y=Y, n=n,\n mu0=mu0, tau0=1/s20, ## mu hyperparams\n a=a, b=b ## tau hyperparams\n ),\n inits=list(mu=3, tau=10) ## starting vals\n )\n\nsamp <- coda.samples(m2, \n variable.names=c(\"mu\",\"s2\"), \n n.iter=1000, progress.bar=\"none\")\n\nplot(samp)\n\nsummary(samp)\n\npar(mfrow=c(1,2), bty=\"n\")\n\nhist(samp[[1]][,1], xlab=\"samples of mu\", main=\"mu\")\nlines(x, dnorm(x, mean=mu0, sd=sqrt(s20)), \n col=2, lty=2, lwd=2) ## prior\n\nx2 <- seq(0, 200, length=1000)\nhist(1/samp[[1]][,2], xlab=\"samples of tau\", main=\"tau\")\nlines(x2, dgamma(x2, shape = a, rate = b), \n col=2, lty=2, lwd=2) ## prior\n\nplot(as.numeric(samp[[1]][,1]), samp[[1]][,2], xlab=\"mu\", ylab=\"s2\")\n\nrequire(R2jags) # fitting\nrequire(coda) # diagnostic plots\nset.seed(1234)\n\nAaeg.data <- read.csv(\"../data/AeaegyptiTraitData.csv\")\n\nhead(Aaeg.data)\n\nmu.data <- subset(Aaeg.data, trait.name == \"mu\")\nlf.data <- subset(Aaeg.data, trait.name == \"1/mu\")\npar(mfrow=c(1,2), bty=\"l\") \nplot(trait ~ T, data = mu.data, ylab=\"mu\")\nplot(trait ~ T, data = lf.data, ylab=\"1/mu\")\n\nmu.data.inv <- mu.data # make a copy of the mu data\nmu.data.inv$trait <- 1/mu.data$trait # take the inverse of the trait values to convert mu to lifespan\nlf.data.comb <- rbind(mu.data.inv, lf.data) # combine both lifespan data sets together \n \nplot(trait ~ T, data = lf.data.comb, ylab=\"1/mu\")\n\nsink(\"quad.txt\") # create a file\ncat(\"\n model{\n \n ## Priors\n cf.q ~ dunif(0, 1)\n cf.T0 ~ dunif(0, 24)\n cf.Tm ~ dunif(25, 45)\n cf.sigma ~ dunif(0, 1000)\n cf.tau <- 1 / (cf.sigma * cf.sigma)\n \n ## Likelihood\n for(i in 1:N.obs){\n trait.mu[i] <- -1 * cf.q * (temp[i] - cf.T0) * (temp[i] - cf.Tm) * (cf.Tm > temp[i]) * (cf.T0 < temp[i])\n trait[i] ~ dnorm(trait.mu[i], cf.tau)\n }\n \n ## Derived Quantities and Predictions\n for(i in 1:N.Temp.xs){\n z.trait.mu.pred[i] <- -1 * cf.q * (Temp.xs[i] - cf.T0) * (Temp.xs[i] - cf.Tm) * (cf.Tm > Temp.xs[i]) * (cf.T0 < Temp.xs[i])\n }\n } # close model\n\",fill=T)\nsink()\n\n# Parameters to Estimate\nparameters <- c(\"cf.q\", \"cf.T0\", \"cf.Tm\",\"cf.sigma\", \"z.trait.mu.pred\")\n\n# Initial values for the parameters\ninits <- function(){list(\n cf.q = 0.01,\n cf.Tm = 35,\n cf.T0 = 5,\n cf.sigma = rlnorm(1))}\n\n# MCMC Settings: number of posterior dist elements = [(ni - nb) / nt ] * nc\nni <- 25000 # number of iterations in each chain\nnb <- 5000 # number of 'burn in' iterations to discard\nnt <- 8 # thinning rate - jags saves every nt iterations in each chain\nnc <- 3 # number of chains\n\n# Temperature sequence for derived quantity calculations\nTemp.xs <- seq(0, 45, 0.2)\nN.Temp.xs <- length(Temp.xs)\n\n### Fitting the trait thermal response; Pull out data columns as vectors\ndata <- lf.data.comb # this lets us reuse the same generic code: we only change this first line\ntrait <- data$trait\nN.obs <- length(trait)\ntemp <- data$T\n\n# Bundle all data in a list for JAGS\njag.data <- list(trait = trait, N.obs = N.obs, temp = temp, Temp.xs = Temp.xs, N.Temp.xs = N.Temp.xs)\n\nlf.fit <- jags(data=jag.data, inits=inits, parameters.to.save=parameters, \n model.file=\"quad.txt\", n.thin=nt, n.chains=nc, n.burnin=nb, \n n.iter=ni, DIC=T, working.directory=getwd())\n\nlf.fit.mcmc <- as.mcmc(lf.fit)\n\nlf.fit$BUGSoutput$summary[1:5,]\n\nplot(lf.fit.mcmc[,c(1,3,4)])\n\nplot(trait ~ T, xlim = c(0, 45), ylim = c(0,42), data = lf.data.comb, ylab = \"Lifespan for Ae. aegypti\", xlab = \"Temperature\")\nlines(lf.fit$BUGSoutput$summary[6:(6 + N.Temp.xs - 1), \"2.5%\"] ~ Temp.xs, lty = 2)\nlines(lf.fit$BUGSoutput$summary[6:(6 + N.Temp.xs - 1), \"97.5%\"] ~ Temp.xs, lty = 2)\nlines(lf.fit$BUGSoutput$summary[6:(6 + N.Temp.xs - 1), \"mean\"] ~ Temp.xs)\n\nTemp.xs[which.max(as.vector(lf.fit$BUGSoutput$summary[6:(6 + N.Temp.xs - 1), \"mean\"]))]\n\nlf.grad <- lf.fit$BUGSoutput$sims.list$z.trait.mu.pred\ndim(lf.grad) # A matrix with 7500 iterations of the MCMC chains at 226 temperatures\n\nrequire(R2jags) # does the fitting\nrequire(coda) # makes diagnostic plots\nlibrary(IDPmisc) # makes nice colored pairs plots to look at joint posteriors\n\ndat <- read.csv(\"../data/lb_ab_temps.csv\")\nhead(dat)\n\nd2 <- dat[which(dat$EXP==2),2:8]\nd2 <- d2[which(d2$TEMP==12),]\nsummary(d2)\n\nTemps <- seq(0,max(d2$DAY)-1, by=0.05)\nmycol <- 1 \nmy.ylim <- c(0, 0.5)\nmy.title <- \"LB-AB isolate, T=12C\"\n\nplot(d2$DAY-1, d2$OD, xlim=c(0,max(Temps)), ylim=my.ylim,\n pch=(mycol+20),\n xlab=\"time (days)\", ylab=\"\",\n main=my.title,\n col=mycol+1, cex=1.5)\n\nsink(\"jags-logistic.bug\")\ncat(\"\n model {\n \n ## Likelihood\n for (i in 1:N) {\n Y[i] ~ dlnorm(log(mu[i]), tau)\n mu[i] <- K * Y0/(Y0+(K-Y0) * exp(-r * t[i]))\n }\n\n ## Priors\n r~dexp(1000)\n K ~ dunif(0.01, 0.6)\n Y0 ~ dunif(0.09, 0.15)\n tau <- 1/sigma^2\n sigma ~ dexp(0.1)\n\n } # close model\n \",fill=T)\nsink()\n\n# Parameters to Estimate\nparameters <- c('Y0', 'K', 'r', 'sigma')\n\n# Initial values for the parameters\ninits <- function(){list(\n Y0 = 0.1,\n K = 0.4,\n r = 0.1,\n sigma = rlnorm(1))}\n\n# MCMC Settings: number of posterior dist elements = [(ni - nb) / nt ] * nc\nni <- 6000 # number of iterations in each chain\nnb <- 1000 # number of 'burn in' iterations to discard\nnt <- 1 # thinning rate - jags saves every nt iterations in each chain\nnc <- 5 # number of chains\n\n# Pull out data columns as vectors\ndata <- d2 # this lets us reuse the same generic code: we only change this first line\nY <- data$OD\nN <- length(Y)\nt <- data$DAY\n\n# Bundle all data in a list for JAGS\njag.data <- list(Y = Y, N = N, t = t)\n\n# Run JAGS\nOD.12C <- jags(data=jag.data, inits=inits, parameters.to.save=parameters, \n model.file=\"jags-logistic.bug\", n.thin=nt, n.chains=nc, n.burnin=nb, \n n.iter=ni, DIC=T, working.directory=getwd())\n\nOD.12C.mcmc <- as.mcmc(OD.12C)\n\nOD.12C$BUGSoutput$summary\n\nplot(OD.12C.mcmc[,c(1,2,4)])\n\ns1 <- as.data.frame(OD.12C.mcmc[[1]])\npar(mfrow=c(2,2))\nfor(i in 2:5) acf(s1[,i], lag.max=20)\n\nsource(\"../code/mcmc_utils.R\")\n\nsamps <- NULL\nfor(i in 1:nc){\n samps <- rbind(samps, as.data.frame(OD.12C.mcmc[[i]]))\n}\n\nsamps <- samps[,c(5,2,3,4)]\n\npriors <- list()\npriors$names <- c(\"Y0\", \"K\", \"r\",\"sigma\")\npriors$fun <- c(\"uniform\", \"uniform\", \"exp\",\"exp\")\npriors$hyper <- matrix(NA, ncol=4, nrow=3)\npriors$hyper[,1] <- c(0.09, 0.15, NA)\npriors$hyper[,2] <- c(0.01, 0.6, NA)\npriors$hyper[,3] <- c(1000, NA, NA) \npriors$hyper[,4] <- c(0.1, NA, NA)\n\nplot.hists(samps, my.par=c(2,2), n.hists=4, priors=priors, mai=c(0.5, 0.5, 0.25, 0.2))\n\nipairs(s1[,2:5], ztransf = function(x){x[x<1] <- 1; log2(x)})\n\nmy.logistic <- function(t, Y0, K, r){\n return(K * Y0/(Y0+(K-Y0) * exp(-r * t)))\n}\n\nts <- seq(0, 40, length=100)\nss <- seq(1, dim(samps)[1], by=10)\nmy.curves <- matrix(NA, nrow=length(ss), ncol=length(ts))\n\nfor(i in 1:length(ss)){\n my.curves[i,] <- my.logistic(t=ts, Y0=samps$Y0[i], K=samps$K[i], r=samps$r[i])\n}\n\nplot(ts, my.curves[1,], col=1, type=\"l\", ylim=c(0.09, 0.36), \n ylab=\"predicted OD\", xlab=\"time (days)\")\nfor(i in 2:length(ss)) lines(ts, my.curves[i,], col=i)\n\nm.log <- apply(my.curves, 2, mean)\nl.log <- apply(my.curves, 2, quantile, probs=0.025)\nu.log <- apply(my.curves, 2, quantile, probs=0.975)\n\nhpd.log <- NULL\nfor(i in 1:length(ts)){\n hpd.log <- cbind(hpd.log, as.numeric(HPDinterval(mcmc(my.curves[,i]))))\n}\n\nmy.ylim <- c(0.09, 0.45)\nmy.title <- \"LB-AB isolate, T=12C\"\n\nplot(d2$DAY-1, d2$OD, xlim=c(0,max(Temps)), ylim=my.ylim,\n pch=(mycol+20),\n xlab=\"time (days)\", ylab=\"\",\n main=my.title,\n col=\"grey\", cex=1.5)\nlines(ts, m.log, col=1, lwd=2)\nlines(ts, l.log, col=2, lwd=2, lty=2)\nlines(ts, u.log, col=2, lwd=2, lty=2)\n\nlines(ts, hpd.log[1,], col=3, lwd=2, lty=3)\nlines(ts, hpd.log[2,], col=3, lwd=2, lty=3)\n", "meta": {"hexsha": "23448e10f0d3348adf6a9d1e6187cfdcb3596a50", "size": 21234, "ext": "r", "lang": "R", "max_stars_repo_path": "content/_build/jupyter_execute/notebooks/20-ModelFitting.r", "max_stars_repo_name": "nesbitm/VBiTE_2021", "max_stars_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "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": "content/_build/jupyter_execute/notebooks/20-ModelFitting.r", "max_issues_repo_name": "nesbitm/VBiTE_2021", "max_issues_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/_build/jupyter_execute/notebooks/20-ModelFitting.r", "max_forks_repo_name": "nesbitm/VBiTE_2021", "max_forks_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "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.976284585, "max_line_length": 126, "alphanum_fraction": 0.6313930489, "num_tokens": 8025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.8239314165802494}} {"text": "#' @title e\r\n#'\r\n#' @description Calculates the Nash-Sutcliffe modelling efficiency (E)\r\n#' from observed and predicted values.\r\n#'\r\n#' @param observed Numeric vector of observed values\r\n#'\r\n#' @param predicted Numeric vector of predicted values. The length shall be\r\n#' the same as for observed.\r\n#'\r\n#' @return The Nash-Sutcliffe modelling efficiency (E) calculated from observed and\r\n#' predicted values.\r\n#'\r\n#' @details E = 1 - sum(observed - predicted)/sum(observed - mean (observed))\r\n#'\r\n#' @references Nash, J. E., & Sutcliffe, J. V. (1970). River flow forecasting\r\n#' through conceptual models part I—A discussion of principles. Journal of\r\n#' hydrology, 10(3), 282-290.\r\n#'\r\n#' @examples\r\n#' o<-1:5\r\n#' p<-c(2,2,4,3,5)\r\n#' e(observed=o, predicted=p)\r\n#'\r\n#' @export\r\ne<-function(observed, predicted){\r\n return(1-(sum((observed-predicted)^2)/sum((observed-mean(observed))^2)))\r\n}\r\n", "meta": {"hexsha": "4181fed4d3167e3a5514d1593aa136489fb0c72b", "size": 892, "ext": "r", "lang": "R", "max_stars_repo_path": "R/e.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/e.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/e.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": 30.7586206897, "max_line_length": 84, "alphanum_fraction": 0.6726457399, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8237651055273509}} {"text": "## Multivariate Regression \r\n\r\n## Section 1: Loading Libraries ---------------------------------------------------------\r\n\r\n## Load the \"data.table\", \"ggplot2\", and \"reshape2\" libraries. \r\nlibrary(data.table)\r\nlibrary(ggplot2)\r\nlibrary(reshape2)\r\n\r\n## Section 2: Regressing Years of Service on Salary ---------------------------------------------------------\r\n\r\n## Load the \"Salaries\" dataset, and convert it to a data.table. \r\ndata(\"Salaries\")\r\nSalaries <- data.table(Salaries)\r\n\r\n## Run a regression where the outcome variable is \"salary\" and the predictor variable is \"yrs.service\". \r\nregression_output <- lm(salary ~ yrs.service, data = Salaries)\r\nprint(regression_output)\r\n## Run the \"summary\" command on your regression, and answer the following questions:\r\n\r\n## 1. What are the coefficients for intercept and \"yrs.service\"?\r\n## Coefficients: Intercept 99974.7, yrs.service 779.6 \r\n\r\n## 2. Put those intercepts into a sentence describing the linear relationship, like we did for the two regressions in lecture.\r\n# A professor with zero years of service is expected to make $99,974 and every additional year of service will add $779.\r\n\r\n## 3. What is the standard error and p-value of the \"yrs.service\" coefficient? Is that p-value statistically significant?\r\nsummary(regression_output)\r\n# Std error 110.4, p value 7.53e-12, yes\r\n\r\n## 4. What is the adjusted R-squared value for this regression? What does that mean?\r\n#Adjusted R-squared: 0.1098. R-squared, along with p-value, is another common statistic for assessing the goodness-of-fit of your model. the R-squared value will tell you how much variation in your outcome variable can be predicted by your predictor variable.\r\n# about 10% of the variance in salary is explained by yrs.service\r\n#If the data were a straight line, the R-squared value would be 1. If the data were random noise, R-squared would be close to zero (or could, in some cases, even be negative). Here we have an adjusted R-squared of 0.1098, meaning that only about 10% of the variance in salary can be explained by yrs.since.phd.\r\n\r\n## Make a new column in your dataset with predicted salary values.\r\nSalaries[, salary.predict:=predict(regression_output)]\r\nprint(Salaries)\r\n\r\n## Make a scatter plot of yrs.service vs. salary, and add a line plot showing the regression predictions.\r\n## NOTE: I want you to plot your predicted values (from the last question). Do *not* use geom_smooth().\r\n## Fully label both axes, and add a title.\r\nsalary_plot <- ggplot(data=Salaries, aes(x=yrs.service)) + geom_point(aes(y=salary)) + geom_line(aes(y=salary.predict), color=\"green\") + labs(title=\"Professor's Actual and Predicted Salary Over Years of Service\", x=\"Years of Service\", y=\"Salary\")\r\nprint(salary_plot)\r\n\r\nggplot(Salaries, aes(x=yrs.service))+\r\n geom_point(aes(y=salary), color=\"orange\", alpha=0.7)+\r\n geom_line(aes(y=predictedSalary), color=\"blue\") +\r\n labs(title=\"Data and Regression Line for Years of Service and Salary among Professors\",\r\n x=\"Years of Service\",\r\n y=\"Salary (USD)\")\r\n## ---------------------------------------------------------------------------------\r\n## Section 3: Regressing with the \"tips\" Dataset ---------------------------------------------------------\r\n\r\n## Load the \"tips\" dataset from the \"reshape2\" library, and convert it to a data.table. \r\ndata(tips)\r\ntips <- data.table(tips)\r\n\r\n## What does one row of this dataset represent?\r\n# One row represents a restaurant bill transaction and has bill amount, day of week, time (categorical bfast, lunch and dinner) and details about the customer such as number in the party, sex and smoking status.\r\n\r\n## Run a regression where the outcome variable is \"tip\" and the predictor variable is \"total_bill\". \r\nregression_tip <- lm(tip ~ total_bill, data = tips)\r\nprint(regression_tip)\r\n## Run the \"summary\" command on your regression, and answer the following questions:\r\nsummary(regression_tip)\r\n\r\n## 1. What are the coefficients for intercept and \"total_bill\"?\r\n#Intercept : 0.920270\r\n# Total bill: 0.105025\r\n\r\n## 2. Put those intercepts into a sentence describing the linear relationship, like we did for the two regressions in lecture.\r\n# A total bill of zero dollars is expected to make 0$.92 in tips and every additional dollar of total bill will add $0.105025\r\n\r\n## 3. What is the standard error and p-value of the \"total_bill\" coefficient? Is that p-value statistically significant?\r\n#Standard error: 0.007365, p-value: <2e-16. Yes, P value is significant.\r\n\r\n## 4. What is the adjusted R-squared value for this regression? What does that mean?\r\n# Adjusted R-squared: 0.4544. R-squared, along with p-value, is another common statistic for assessing the goodness-of-fit of your model. the R-squared value will tell you how much variation in your outcome variable can be predicted by your predictor variable.\r\n#If the data were a straight line, the R-squared value would be 1. If the data were random noise, R-squared would be close to zero (or could, in some cases, even be negative). Here we have an adjusted R-squared of 0.1098, meaning that only about 10% of the variance in salary can be explained by yrs.since.phd.\r\n\r\n## 5. What are the units of the coefficients in the \"Estimate\" column?\r\n#Dollars\r\n## Make a new column in your dataset with predicted tip values.\r\ntips[, tips.predict:=predict(regression_tip)]\r\nprint(tips)\r\n## Make a scatter plot of total_bill vs. tips, and add a line plot showing the regression predictions.\r\n## See note above about how to plot predicted values. Again, make sure both axes are labeled and the plot \r\n## has a title. \r\ntips_plot <- ggplot(data=tips, aes(x=total_bill)) + geom_point(aes(y=tip)) + geom_line(aes(y=tips.predict), color=\"red\") + labs(title=\"Tips of Prediction\", x=\"Total Bill\", y=\"Tips\")\r\nprint(tips_plot)\r\n\r\n## Think about the expected relationship between \"total_bill\" and \"tip\", according to cultural norms in the US.\r\n## How does the coefficient on \"total_bill\" relate to those cultural norms?\r\n\r\n\r\n## Section 2: Exploring variables in the \"tips\" dataset ---------------------------------------------------------\r\n\r\n## Load the \"tips\" dataset and convert it to a data.table.\r\ndata(tips)\r\ntips <- data.table(tips)\r\n\r\n## Let's say that we're interested in the relationship between total bill (predictor variable) and tip (outcome variable).\r\n\r\n## For each of the other five variables in the dataset, indicate what class that variable falls into (confounder, effect modifier,\r\n## mediator, or none of the above). Explain why you think that. Is this variable categorical or continuous?\r\n## Should this variable be included in the regression?\r\n\r\n#sex: confounder (since it's associated with both predictor and outcome)\r\n#smoker: effect modifier, but would also accept confounder or irrelevant (definitely associated with outcome, more tenuously associated with predictor, if they make a good argument for why it should theoretically be irrelevant I'll accept it)\r\n#day: confounder (associated with both predictor and outcome)\r\n#time: irrelevant, or confounder (not strongly associated with either predictor or outcome, but you could make the case for why it might be a confounder)\r\n#size: mediator (associated with tip and total bill, but on the causal pathway)\r\nggplot(tips, aes(x=total_bill, y=tip)) +\r\n geom_point() +\r\n geom_smooth(method=\"lm\", color=\"black\")+\r\n facet_grid(.~sex)+\r\n labs(title=\"Total Bill size and Tips by Sex\",\r\n x=\"Total Bill ($)\",\r\n y=\"Tips($)\")\r\ntips_bi <- lm(tip ~ sex, data=tips)\r\nsummary(tips_bi)\r\n## Section 3: Designing a regression ---------------------------------------------------------\r\n\r\n## In section 2, you decided what variables should and should not be included in your regression on the relationship \r\n## between total bill and tip.Write out what your regression equation should be, including all the variables\r\n## you deemed necessary in Section 2.\r\n## You can use \"b\" instead of \"beta\", for example: \"tip = b0 + b1*total_bill + b2*sex\". \r\n## You should have at least three predictor variables. \r\n\r\n\r\n## Section 4: Running that regression ---------------------------------------------------------\r\n\r\n## Run the regression specified in Section 3. Print the output using summary().\r\nregression_multi_tips <- lm(formula = tip ~ total_bill + size + day, data = multi_tips)\r\nsummary(regression_multi_tips)\r\n## What category/categories is your Intercept value capturing? For example, in our \"full regression\" video from \r\n## lecture, our Intercept value captured both the category \"sex=Female\" and the category \"discipline=A\".\r\n# The intercept is capturing the category value of \"day=Friday\".\r\n\r\n## For each row of the regression output, tell me:\r\n## --If the coefficient in question refers to a continuous or categorical variable (and if categorical, what category)\r\n## --How to interpret that value in a sentence. \r\n## For continuous variables, this should be in the format of \"an [x] increase in [predictor variable] \r\n## leads to a [y] increase/decrease in my outcome variable. \r\n## For categorical variables, tell me how the Intercept changes for each categorical variable. \r\n\r\n# Coefficients:\r\n# Estimate Std. Error t value Pr(>|t|) \r\n# (Intercept) 0.745787 0.281343 2.651 0.00857 ** - a bill of $0 is expected to generate $0.75 in tips.\r\n# total_bill 0.092994 0.009239 10.065 < 2e-16 *** - continuous - an increase of $1.00 in total_bill is expected to generate\r\n# an increase of $0.09 in tips.\r\n# size 0.187132 0.087199 2.146 0.03288 * - continuous - an increase of 1 person in party size is expected to generate\r\n# an increase of $0.19 in tips.\r\n# daySat -0.124658 0.259746 -0.480 0.63172 - categorical - if the bill is on a Saturday, it's expected to generate $0.13\r\n# less in tips than if it were on Friday.\r\n# daySun -0.013498 0.266391 -0.051 0.95963 - categorical - if the bill is on a Sunday, it's expected to generate $0.14\r\n# less in tips than if it were on Friday.\r\n# dayThur -0.077493 0.268534 -0.289 0.77316 - categorical - if the bill is on a Thursday, it's expected to generate $0.08\r\n# less in tips than if it were on Friday.\r\n\r\n## NOTE: You **do not** have to work through every possible combiations of categories and give me their intercept values--\r\n## depending on which variables you choose, that could wind up being a lot of combinations. Just tell me how each categorical\r\n## coefficient changes the intercept. \r\n\r\n#1) The coefficient for total_bill refers to a continuous variable. A $1 increase in the total_bill \r\n## leads to an increase in the tip amount by $0.093205\r\n## 2) The coefficient for sex refers to a categorical variable and indicates the Male category.\r\n## If the sex of the bill payer is Male, the tip amount reduces by $0.032595\r\n## 3) The coefficents for day refer to a categorical variable and indicate the Sat, Sun and Thur categories. \r\n## The 'Fri' category is represented by absence i.e. if the bill is paid on a Friday, then none of the coefficients will apply.\r\n## If the bill is for Sat, the tip amount reduces by $0.120244 (~12 cents), if the bill is for Sun, the tip amount\r\n## reduces by $0.006392 and if the bill is for Thur, then the tip amount reduces by $0.078854 (~7cents)\r\n## 4) The coefficnets for size refer to a continuous variable. An increase in size of party by 1, leads to \r\n## an increase in the tip amount by $0.186741 (~18 cents)\r\n\r\n## Section 5: Visualization ---------------------------------------------------------\r\n\r\n## Make a plot of your regression outputs. If you included continuous variables, make one plot where the x-axis is \r\n## \"total_bill\" and another where it is your continuous variable. The results won't be straight lines, but that's ok.\r\n## If you only have one categorical variable, distinguish its values by color. If you have multiple categorical variables,\r\n## Use some combination of color and faceting to come up with the appropriate number of regression lines. \r\ntips[,predicted_tip := predict(tip.regression, data=tips)]\r\n\r\nvisualization <- ggplot(tips, aes(x=total_bill)) +\r\n geom_point(aes(y=tip, color=sex), alpha=0.7) +\r\n geom_line(aes(y=predicted_tip, color=sex), size=1) +\r\n facet_grid(.~smoker, scales=\"free\") +\r\n labs(title=\"Multivariate Regression with Categorical Variables: Sex and Smoking\", x=\"Total Bill\", y=\"Tip Amount\")\r\n\r\nprint(visualization)\r\n\r\nInteresting vizualizations\r\ntips[, predicted_tips_total_bill:= predict(combined_regression, data=tips)]\r\nprint(tips)\r\n\r\n\r\n## Plot predicted values - sex\r\nggplot(tips, aes(x=total_bill)) +\r\n geom_point(aes(y=tip, color=sex), alpha=0.7) +\r\n geom_line(aes(y=predicted_tips_total_bill, color=sex), size=1) +\r\n labs(title=\"Multivariate Regression with Categorical Variables: Day, Sex & Time\",\r\n x=\"Total Bill (USD)\",\r\n y=\"Tip Amount (USD)\")\r\n\r\n## Plot predicted values - sex, Factetted by sex\r\nggplot(tips, aes(x=total_bill)) +\r\n geom_point(aes(y=tip, color=sex), alpha=0.7) +\r\n geom_line(aes(y=predicted_tips_total_bill), size=1) +\r\n facet_grid(.~sex, scales=\"free\") + \r\n labs(title=\"Multivariate Regression with Categorical Variables: Day, Sex & Time\",\r\n x=\"Total Bill (USD)\",\r\n y=\"Tip Amount (USD)\")\r\n\r\n#Plot Tip v Bill, Faceting by Day and Time, Sex by color of plot, Best fit line \r\nfaceting <- ggplot(data=tips, aes(x=total_bill, y=tip)) +\r\n geom_point(aes(color=sex)) +\r\n geom_smooth(method=\"lm\", color=\"black\") +\r\n # adding a facet_wrap component\r\n facet_grid(time~day) +\r\n labs(title=\"Multivariate Regression with Categorical Variables: Day, Sex & Time\",\r\n x=\"Total Bill (USD)\",\r\n y=\"Tip Amount (USD)\")\r\nprint(faceting)\r\n\r\n#Plots Tip v Bill, Faceting Sex by Time and Day, Best fit Line\r\nfaceting <- ggplot(data=tips, aes(x=total_bill, y=tip)) +\r\n geom_point(aes(color=sex)) +\r\n geom_smooth(method=\"lm\", color=\"black\") +\r\n # adding a facet_wrap component\r\n facet_grid(time~day~sex) +\r\n labs(title=\"Multivariate Regression with Categorical Variables: Day, Sex & Time\",\r\n x=\"Total Bill (USD)\",\r\n y=\"Tip Amount (USD)\")\r\nprint(faceting)\r\n\r\n#Plots Tip v Bill, Faceting Sex by Time and Day, Geomteric Line\r\nfaceting <- ggplot(data=tips, aes(x=total_bill, y=tip)) +\r\n geom_point(aes(color=sex)) +\r\n geom_line(color=\"black\") +\r\n # adding a facet_wrap component\r\n facet_grid(time~day~sex) +\r\n labs(title=\"Multivariate Regression with Categorical Variables: Sex - Time and Day\",\r\n x=\"Total Bill (USD)\",\r\n y=\"Tip Amount (USD)\")\r\nprint(faceting)\r\n# Note there is only one Thursday Dinner\r\n\r\n#Plots Tip v Bill, Faceting Sex by Time and Day, Geomteric Line & Best fit line\r\nfaceting <- ggplot(data=tips, aes(x=total_bill, y=tip)) +\r\n geom_point(aes(color=sex)) +\r\n geom_line(color=\"black\") +\r\n geom_smooth(method=\"lm\", color=\"green\") +\r\n # adding a facet_wrap component\r\n facet_grid(time~day~sex) +\r\n labs(title=\"Multivariate Regression with Categorical Variables: Day, Sex & Time\",\r\n x=\"Total Bill (USD)\",\r\n y=\"Tip Amount (USD)\")\r\nprint(faceting)\r\n# Note there is only one Thursday Dinner\r\n\r\n#Plots Tip v Bill, Faceting by Day and Time, Sex by color of plot, Geomteric Line & Best fit line\r\nfaceting <- ggplot(data=tips, aes(x=total_bill, y=tip)) +\r\n geom_point(aes(color=sex)) +\r\n geom_line(color=\"black\") +\r\n geom_smooth(method=\"lm\", color=\"green\") +\r\n # adding a facet_wrap component\r\n facet_grid(time~day) +\r\n labs(title=\"Multivariate Regression with Categorical Variables: Day, Sex & Time\",\r\n x=\"Total Bill (USD)\",\r\n y=\"Tip Amount (USD)\")\r\nprint(faceting)\r\n# Note there is only one Thursday Dinner\r\n\r\n#Plots Tip v Bill, Faceting by Day and Sex, Time by color of plot, Best fit line\r\nfaceting <- ggplot(data=tips, aes(x=total_bill, y=tip)) +\r\n geom_point(aes(color=time)) +\r\n geom_smooth(method=\"lm\", color=\"black\") +\r\n # adding a facet_wrap component\r\n facet_grid(sex~day) +\r\n labs(title=\"Multivariate Regression with Categorical Variables: Day, Sex & Time\",\r\n x=\"Total Bill (USD)\",\r\n y=\"Tip Amount (USD)\")\r\nprint(faceting)\r\n\r\n#Plots Tip v Bill, Faceting by Day and Sex, Time by color of plot, Geomteric Line & Best fit line\r\nfaceting <- ggplot(data=tips, aes(x=total_bill, y=tip)) +\r\n geom_point(aes(color=time)) +\r\n geom_line(color=\"black\") +\r\n geom_smooth(method=\"lm\", color=\"green\") +\r\n # adding a facet_wrap component\r\n facet_grid(sex~day) +\r\n labs(title=\"Multivariate Regression with Categorical Variables: Day, Sex & Time\",\r\n x=\"Total Bill (USD)\",\r\n y=\"Tip Amount (USD)\")\r\nprint(faceting)\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "96f6da9064ed30fe030824267cc8138d4e833fae", "size": 16907, "ext": "r", "lang": "R", "max_stars_repo_path": "Tips_Dataset_Regression.r", "max_stars_repo_name": "fpDNA/Machine-Learning-examples-R", "max_stars_repo_head_hexsha": "c6dc8bd654ebb1ec18c65d85d5852d1a1e5596c7", "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": "Tips_Dataset_Regression.r", "max_issues_repo_name": "fpDNA/Machine-Learning-examples-R", "max_issues_repo_head_hexsha": "c6dc8bd654ebb1ec18c65d85d5852d1a1e5596c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tips_Dataset_Regression.r", "max_forks_repo_name": "fpDNA/Machine-Learning-examples-R", "max_forks_repo_head_hexsha": "c6dc8bd654ebb1ec18c65d85d5852d1a1e5596c7", "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": 56.1694352159, "max_line_length": 311, "alphanum_fraction": 0.681611167, "num_tokens": 4123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.82364632373795}} {"text": "#' Entropy of a bit-string\n#'\n#' The entropy of a bitstring (ex: 1010111000) is calculated.\n#' @param x - A vector of 0's and 1's.\n#' @return e - a floating point percentage, between 0 and 1.\n#' @export stats.entropyFunction\n#' @examples\n#' stats.entropyFunction(c(1,0,0,0,1,0,0,0,0,0,0,0,0))\n#' > 0.6193822\n#' stats.entropyFunction(c(1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0))\n#' > 1\n#' stats.entropyFunction(c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))\n#' > 0\nstats.entropyFunction = function(bitString) {\n pT = sum(bitString)/length(bitString)\n pF = 1-pT\n if (pT==1 || pT==0) {\n e = 0\n } else {\n e = -pT*log2(pT)-pF*log2(pF)\n }\n return(e)\n}\n", "meta": {"hexsha": "65f13909a3ed2f6caf767aab3b6ed6265df67bf4", "size": 638, "ext": "r", "lang": "R", "max_stars_repo_path": "R/stats.entropyFunction.r", "max_stars_repo_name": "Xiqi-Li/CTD", "max_stars_repo_head_hexsha": "3002736b9cc43e5435b8a0bf07535b0146a1e32c", "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/stats.entropyFunction.r", "max_issues_repo_name": "Xiqi-Li/CTD", "max_issues_repo_head_hexsha": "3002736b9cc43e5435b8a0bf07535b0146a1e32c", "max_issues_repo_licenses": ["MIT"], "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/stats.entropyFunction.r", "max_forks_repo_name": "Xiqi-Li/CTD", "max_forks_repo_head_hexsha": "3002736b9cc43e5435b8a0bf07535b0146a1e32c", "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.5833333333, "max_line_length": 61, "alphanum_fraction": 0.6128526646, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.8596637523076224, "lm_q1q2_score": 0.8234824540699632}} {"text": "# Author: Nikos Kougianos\n# Date: 13/12/2020\n\ncustom_median <- function(x, na.rm = FALSE) {\n # Check if vector has any NA values\n if (anyNA(x)) {\n # Check na.rm if TRUE or FALSE\n if (na.rm == TRUE) {\n # If true, remove NA values from x\n x <- x[!is.na(x)]\n \n } else {\n # If false, then return NA as result like median function\n return(NA)\n \n }\n \n }\n \n # Sort x\n x = sort(x)\n \n # Check if length of x is even or odd\n # If even, then we want to return the mean of the 2 middle elements\n # If odd, then we want to return only the middle element\n if (length(x) %% 2 == 0) {\n middle1 <- x[length(x) %/% 2]\n middle2 <- x[length(x) %/% 2 + 1]\n return(mean(c(middle1, middle2)))\n } else {\n return(x[length(x) %/% 2 + 1])\n }\n \n}\n\n# Sample executions of custom_median function, using integer vectors,\n# double vectors, vectors with NA values and vectors without NA values\ncustom_median(runif(10, 0, 100), FALSE)\ncustom_median(runif(150, 0, 100), FALSE)\ncustom_median(sample.int(100, 9), FALSE)\ncustom_median(sample.int(100, 200, replace=TRUE), FALSE)\ncustom_median(c(NA,1,5,15.6,NA,6,7,8,9), FALSE)\ncustom_median(c(NA,1,5,15.6,NA,6,7,8,9), TRUE)\ncustom_median(c(1,5,15.6,6,7,8,9), FALSE)\n", "meta": {"hexsha": "5d2c9f292f72d9f365046ec4b4967ee90dfc1f17", "size": 1348, "ext": "r", "lang": "R", "max_stars_repo_path": "exercise4/custom_median.r", "max_stars_repo_name": "kougianos/R-code", "max_stars_repo_head_hexsha": "9e582d7f44e151242bb02f8dbf386eac0e703c9a", "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": "exercise4/custom_median.r", "max_issues_repo_name": "kougianos/R-code", "max_issues_repo_head_hexsha": "9e582d7f44e151242bb02f8dbf386eac0e703c9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise4/custom_median.r", "max_forks_repo_name": "kougianos/R-code", "max_forks_repo_head_hexsha": "9e582d7f44e151242bb02f8dbf386eac0e703c9a", "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.9555555556, "max_line_length": 71, "alphanum_fraction": 0.5786350148, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.909907010924213, "lm_q1q2_score": 0.823147864324641}} {"text": "#' Geometric mean\n#'\n#' @description Calculates geometric mean\n#'\n#' @param x numeric vector\n#'\n#' @return Geometric mean\n#' @export\n#'\n#' @examples\n#'\n#' x <- rexp(100,.5)\n#'\n#' geometric_mean(x)\n#'\n\ngeometric_mean <- function(x){\n\n if(sum(x == 0, na.rm = T) > 0 ){\n warning(\"There is at least one value = 0 and that cause the geometric mean to be 0\")\n }\n\n if(sum(x < 0, na.rm = T) > 0 ){\n warning(\"There is at least one value < 0 and that cause NaN's when computing the geometric mean\")\n }\n\n exp(mean(log(x), na.rm = T))\n\n}\n", "meta": {"hexsha": "e296bbf8f9b03325009d47a1ed1cad9a4bac0ba8", "size": 537, "ext": "r", "lang": "R", "max_stars_repo_path": "R/geometric_mean.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/geometric_mean.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/geometric_mean.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": 17.9, "max_line_length": 101, "alphanum_fraction": 0.6070763501, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485602, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.8230125382030307}} {"text": "quaddiscrroots <- function(a,b,c, tol=1e-5) {\n d <- b*b - 4*a*c + 0i\n root1 <- (-b + sqrt(d))/(2*a)\n root2 <- (-b - sqrt(d))/(2*a)\n if ( abs(Re(d)) < tol ) {\n list(\"real and equal\", abs(root1), abs(root1))\n } else if ( Re(d) > 0 ) {\n list(\"real\", Re(root1), Re(root2))\n } else {\n list(\"complex\", root1, root2)\n }\n}\n\nfor(coeffs in list(c(3,4,4/3), c(3,2,-1), c(3,2,1), c(1, -1e6, 1)) ) {\n cat(sprintf(\"roots of %gx^2 %+gx^1 %+g are\\n\", coeffs[1], coeffs[2], coeffs[3]))\n r <- quaddiscrroots(coeffs[1], coeffs[2], coeffs[3])\n cat(sprintf(\" %s: %s, %s\\n\", r[[1]], r[[2]], r[[3]]))\n}\n", "meta": {"hexsha": "84cf6d604a4a7088f187ee95fe5940a2fa3007fe", "size": 600, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Roots-of-a-quadratic-function/R/roots-of-a-quadratic-function.r", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "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-quadratic-function/R/roots-of-a-quadratic-function.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/Roots-of-a-quadratic-function/R/roots-of-a-quadratic-function.r", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "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.5789473684, "max_line_length": 82, "alphanum_fraction": 0.5066666667, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799410139922, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.8229839755047739}} {"text": "# Suppose we have two students taking a 40-question \n# multiple-choice exam.\n# We think they will do better than chance.\n\n# 1. What are our parameters of interest? \n\n# Ad 1: Theta 1 and thata 2 - probailities that a given student gets a question right\n\n\n# 2. what is our likelihood?\n\n# It's Binom(40, theta), assuming that questions are independent and \n# probabilities of answers are the same for each question\n\n\n# 3. What prior should we use? \n# Beta, as it's a conjucate prior for binom.\ntheta = seq(0, 1, .1)\nplot(theta, dbeta(theta, 8, 4), type = 'l')\n# beta(8, 4) gives a reasonable model of doing better than chance (P > .25)\nprior_alpha = 8\nprior_beta = 4\n\n# 4. What's the prior probability that theta > .25, > .5, > .8?\n1 - pbeta(.25, prior_alpha, prior_beta)\n1 - pbeta( .5, prior_alpha, prior_beta)\n1 - pbeta( .8, prior_alpha, prior_beta)\n\n# 5. Suppose the first student takes the test and gets 33 of the 40 questions right.\n# What's the postrior distribution for their parameter? \n# What's P(theta > .25), > .5, > .8?\n# What's a 95% credible interval for it? \npost_alpha_1 = prior_alpha + 33\npost_beta_1 = prior_beta + 7\n\npost_mean_1 = post_alpha_1 / (post_alpha_1 + post_beta_1)\ncat('Posterior mean:', post_mean_1)\ncat('MLE:', 33/40)\n\n1 - pbeta(.25, post_alpha_1, post_beta_1)\n1 - pbeta( .5, post_alpha_1, post_beta_1)\n1 - pbeta( .8, post_alpha_1, post_beta_1)\n\ncat('95% CI:', qbeta(.025, post_alpha_1, post_beta_1), \n qbeta(.975, post_alpha_1, post_beta_1))\n\n# 6. Suppose the 2nd student gets 24 questions right.\n# What's the distribution for their parameter?\n# What's P(theta > .25), > .5, > .8?\n# What's a 95% credible interval for it? \npost_alpha_2 = prior_alpha + 24\npost_beta_2 = prior_beta + 40 - 24\n\npost_mean_2 = post_alpha_2 / (post_alpha_2 + post_beta_2)\ncat('Posterior mean:', post_mean_2)\ncat('MLE:', 24/40)\n\n1 - pbeta(.25, post_alpha_2, post_beta_2)\n1 - pbeta( .5, post_alpha_2, post_beta_2)\n1 - pbeta( .8, post_alpha_2, post_beta_2)\n\ncat('95% CI:', qbeta(.025, post_alpha_2, post_beta_2), \n qbeta(.975, post_alpha_2, post_beta_2))\n\n\n# 7) Estimate by simulation: draw 1,000 samples from each and see how often \n# we observe theta1 > theta2\n\ntheta_1 = rbeta(1000,41,11)\ntheta_2 = rbeta(1000,32,20)\nmean(theta_1 > theta_2)\n\n", "meta": {"hexsha": "ee344abe573646c908d2588a296a858717254015", "size": 2305, "ext": "r", "lang": "R", "max_stars_repo_path": "bayesian-notes-santa-cruz/ex_1.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_1.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_1.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": 31.5753424658, "max_line_length": 85, "alphanum_fraction": 0.6911062907, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542864252023, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.8227319494289361}} {"text": "pie1=94/125\r\npie2=113/175\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))/125)+((pie2*(1-pie2))/175))\r\n \r\n#test statistic\r\nz=(pie1-pie2)/sigma\r\nprint(z)\r\nalpha=0.05\r\nz.alpha=qnorm(1-alpha)\r\nzstar=qnorm(1-alpha/2)\r\n# Since z is greater than z.alpha, we reject H0 and conclude that the observations\r\n#support the hypothesis\r\nerror=zstar*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": "d3d490558552354053f7eb26fa076c015ed9dc63", "size": 563, "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.7/Ex10_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/CH10/EX10.7/Ex10_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/CH10/EX10.7/Ex10_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": 25.5909090909, "max_line_length": 88, "alphanum_fraction": 0.7193605684, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854111860906, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.8223467575050049}} {"text": "##########################################\n#\n# Introduction to Correspondence Analysis\n#\n# Author: Maximilian Stoehr\n# Email: maximilian.stoehr@protonmail.com\n# License: MIT\n##########################################\n\n# Uncomment to install packages\n# install.packages(\"FactoMineR\")\n# install.packages(\"factoextra\")\n\n# Load packages and dataset\nlibrary(FactoMineR)\nlibrary(factoextra)\ndata(housetasks)\n\n##########################################\n#\n# We are going to work with the housetasks\n# dataset.\n# Data contents: housetasks repartition in the couple.\n#\n# rows are the different tasks\n#\n# values are the frequencies of the tasks done by:\n# the i) wife only, \n# ii) alternatively,\n# iii) husband only,\n# iv) jointly.\n###########################################\n\n# Task 1\n# Explore the housetasks dataset and create the correspondence matrix P\n\n# Task 2\n# Compute the chi^2 test statistic X^2\n\n# Task 3\n# Compare the test statistic with the 95th percentile of\n# a chi^2 distribution with (I-1)(J-1) degrees of freedom\n\n# Task 4\n# Build the distance matrix D which elements are the chi^2 distances\n# Tipp: The diagional should be 0 (reference to the row itself)\n\n# Task 5\n# Compute the total row inertia\n\n# Task 6\n# Fit a CA to the dataset and visualize it with a biplot\n# Tipp: Use the command CA and plot\n\n# Task 7\n# Display a scree plot of the dataset\n# Tipp: The structure of the CA object will give you a hint\n# on how to access the eigenvalues\n\n## **Results of the Correspondence Analysis (CA)**\n## The row variable has 13 categories; the column variable has 4 categories\n## The chi square of independence between the two variables is equal to 1944 (p-value = 0 ).\n## *The results are available in the following objects:\n## \n## name description \n## 1 \"$eig\" \"eigenvalues\" \n## 2 \"$col\" \"results for the columns\" \n## 3 \"$col$coord\" \"coord. for the columns\" \n## 4 \"$col$cos2\" \"cos2 for the columns\" \n## 5 \"$col$contrib\" \"contributions of the columns\"\n## 6 \"$row\" \"results for the rows\" \n## 7 \"$row$coord\" \"coord. for the rows\" \n## 8 \"$row$cos2\" \"cos2 for the rows\" \n## 9 \"$row$contrib\" \"contributions of the rows\" \n## 10 \"$call\" \"summary called parameters\" \n## 11 \"$call$marge.col\" \"weights of the columns\" \n## 12 \"$call$marge.row\" \"weights of the rows\"\n", "meta": {"hexsha": "8801cf5542ebc8fc05fd43218c23b1191f5f6e0a", "size": 2456, "ext": "r", "lang": "R", "max_stars_repo_path": "intro_correspondence_analysis.r", "max_stars_repo_name": "stoehrmax/intro_correspondence_analysis", "max_stars_repo_head_hexsha": "be89c37a9a757ee7fd7baf11a8527478e71df880", "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": "intro_correspondence_analysis.r", "max_issues_repo_name": "stoehrmax/intro_correspondence_analysis", "max_issues_repo_head_hexsha": "be89c37a9a757ee7fd7baf11a8527478e71df880", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intro_correspondence_analysis.r", "max_forks_repo_name": "stoehrmax/intro_correspondence_analysis", "max_forks_repo_head_hexsha": "be89c37a9a757ee7fd7baf11a8527478e71df880", "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.4871794872, "max_line_length": 93, "alphanum_fraction": 0.608713355, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.8223184710504209}} {"text": "#####################################################################\n# CS638: Applied Machine Learning\n# Copyright 2016 Pejman Ghorbanzade \n# More info: https://github.com/ghorbanzade/beacon\n#####################################################################\n\n# clear workspace\nrm(list = ls())\n\n# enable traceback on error messages\noptions(error=traceback)\n\n# remove all plots if there are any\nif (!is.null(dev.list())) trash <- dev.off()\n\nargs = commandArgs(trailingOnly=TRUE)\nif (0 == length(args)) {\n stop(\"expected path to root directory of course\", call.=FALSE)\n}\npngdir <- args[1]\ncourseNameFull <- \"umb-cs638-2016s\"\n\n# loading database\ndata = read.table(\"dat/hw02/data.txt\", sep=\",\")\ncolnames(data) <- c('population', 'profit')\n\n##\n# visualize dataset\n##\npng(filename=file.path(pngdir, paste(courseNameFull, \"-hw02-01\", \".png\", sep=\"\")),\n\theight=768, width=1024, res=150, units=\"px\", bg=\"white\")\n\nxrange <- seq(floor(min(data$population)/5)*5,\n\tceiling(max(data$population)/5)*5,\n\tlength.out=5\n\t)\nyrange <- seq(floor(min(data$profit)/5)*5,\n\tceiling(max(data$profit)/5)*5,\n\tlength.out=7\n\t)\nplot(0, 0, type=\"n\", axes=F, ann=F,\n\txlim=range(xrange), ylim=range(yrange))\npoints(data$population, data$profit, type=\"p\", col=\"blue\")\naxis(1, at=xrange, labels=round(xrange, 3))\naxis(2, at=yrange, labels=round(yrange, 3))\n\ngrid(10, 10)\nbox()\ntitle(main=\"Profit of Coffee Shop Based on City's Population\", font.main=1)\ntitle(xlab=\"Population in 10,000\", col.lab='black')\ntitle(ylab=\"Profit in $10,000\", col.lab='black')\ntrash <- dev.off()\n\n##\n# Check feature correlation\n##\nwith(data, cor.test(data$population, data$profit, alternative=\"greater\", conf.level=.8))\n\n##\n# data variables in pairs to check for correlation easily\n##\npng(filename=file.path(pngdir, paste(courseNameFull, \"-hw02-02\", \".png\", sep=\"\")),\n\theight=768, width=1024, res=150, units=\"px\", bg=\"white\")\npairs(data)\ntrash <- dev.off()\n\n##\n# fit linear model and print summary regression\n##\nlm.out <- lm(data$profit ~ data$population)\nsummary(lm.out)\n\n##\n# Plot regression line on the dataset\n##\npng(filename=file.path(pngdir, paste(courseNameFull, \"-hw02-03\", \".png\", sep=\"\")),\n\theight=768, width=1024, res=150, units=\"px\", bg=\"white\")\n\nxrange <- seq(floor(min(data$population)/5)*5,\n\tceiling(max(data$population)/5)*5,\n\tlength.out=5\n\t)\nyrange <- seq(floor(min(data$profit)/5)*5,\n\tceiling(max(data$profit)/5)*5,\n\tlength.out=7\n\t)\nplot(0, 0, type=\"n\", axes=F, ann=F,\n\txlim=range(xrange), ylim=range(yrange))\npoints(data$population, data$profit, type=\"p\", col=\"blue\")\nabline(lm.out, col=\"red\")\naxis(1, at=xrange, labels=round(xrange, 3))\naxis(2, at=yrange, labels=round(yrange, 3))\n\ngrid(10, 10)\nbox()\ntitle(main=\"Profit of Coffee Shop Based on City's Population\", font.main=1)\ntitle(xlab=\"Population in 10,000\", col.lab='black')\ntitle(ylab=\"Profit in $10,000\", col.lab='black')\ntrash <- dev.off()\n\n##\n# plot linear regression model summary\n##\npng(filename=file.path(pngdir, paste(courseNameFull, \"-hw02-04\", \".png\", sep=\"\")),\n height=768, width=1024, res=150, units=\"px\", bg=\"white\")\npar(mfrow=c(2,2))\nplot(lm.out)\ntrash <- dev.off()\n\n##\n# compute value of the cost function for a given theta\n##\nlm.out <- lm(data$profit ~ data$population)\ntheta <- coef(lm.out)\nx <- cbind(1,data$population)\ny <- data$profit\nm <- nrow(data)\ncost <- sum(((x%*%theta)- y)^2)/(2*m)\n\n##\n# Function to find theta values obtained via gradient descent method\n# for a given learning rate\n##\ngradient_descent <- function(x, y, alpha) {\n\tx <- cbind(1, x)\n\tm <- nrow(x)\n\titerations <- 500\n\ttheta <- c(0, 0)\n\tfor (i in 1:iterations)\n\t{\n\t\ttheta[1] <- theta[1] - alpha * (1/m) * sum(((x%*%theta)- y))\n\t\ttheta[2] <- theta[2] - alpha * (1/m) * sum(((x%*%theta)- y)*x[,2])\n\t}\n\treturn(theta)\n}\n\n##\n# Find an report regression coefficient\n##\ntheta <- gradient_descent(data$population, data$profit, 0.02)\ntheta <- gradient_descent(data$population, data$profit, 0.005)\n\n##\n# Compute theta values for different learning rates\n##\nrealtheta <- coef(lm(data$profit ~ data$population))\nmin <- 0.001\nmax <- 0.024\nnum <- 20\nalpha <- seq(min, max, length.out=num)\ntheta <- mat.or.vec(num, 2)\nnrmtheta <- mat.or.vec(num, 2)\nfor (i in 1:length(alpha)) {\n\ttheta[i,] <- gradient_descent(data$population, data$profit, alpha[i])\n\tnrmtheta[i,] <- (realtheta - theta[i,]) / realtheta * 100\n}\n\n##\n# Plot theta_0 and theta_1 for different learning rates\n##\npng(filename=file.path(pngdir, paste(courseNameFull, \"-hw02-05\", \".png\", sep=\"\")),\n\theight=768, width=1024, res=150, units=\"px\", bg=\"white\")\n\nxrange <- seq(min(alpha),\n\tmax(alpha),\n\tlength.out=5\n\t)\nyrange <- seq(floor(min(theta, realtheta)),\n\tceiling(max(theta, realtheta)),\n\tlength.out=7\n\t)\nplot(0, 0, type=\"n\", axes=F, ann=F,\n\txlim=range(xrange), ylim=range(yrange))\nlines(alpha, theta[,1], type=\"o\", pch=21, col=\"blue\")\nlines(alpha, theta[,2], type=\"o\", pch=22, col=\"red\")\nabline(h=realtheta[1], col=\"blue\", lty=3)\nabline(h=realtheta[2], col=\"red\", lty=3)\naxis(1, at=xrange, labels=round(xrange, 3))\naxis(2, at=yrange, labels=round(yrange, 3))\nlegend(0.015, 0.5,\n\tcex=1,\n\tc(expression(paste(theta[0], \" gradient descent\")),\n\t\texpression(paste(theta[1], \" gradient descent\")),\n\t\texpression(paste(theta[0], \" regression line\")),\n\t\texpression(paste(theta[1], \" regression line\"))\n\t),\n\tcol=c(\"blue\",\"red\",\"blue\",\"red\"),\n\tpch=c(21, 22, 21, 22),\n\tlty=c(1, 2, 3, 3));\n\ngrid(10, 10)\nbox()\ntitle(main=\"Impact of different learning rate on hypothesis function coefficients\", font.main=1)\ntitle(xlab=expression(paste(\"Learning Rate (\", alpha, \")\")), col.lab='black')\ntitle(ylab=expression(paste(\"Hypothesis Function Coefficients (\", theta, \")\")), col.lab='black')\ntrash <- dev.off()\n\n##\n# Plot normalized gradient descent error for different learning rates\n##\npng(filename=file.path(pngdir, paste(courseNameFull, \"-hw02-06\", \".png\", sep=\"\")),\n\theight=768, width=1024, res=150, units=\"px\", bg=\"white\")\n\nxrange <- seq(min(alpha), max(alpha), length.out=5)\nyrange <- seq(0, 100, length.out=6)\nplot(0, 0, type=\"n\", axes=F, ann=F,\n\txlim=range(xrange), ylim=range(yrange))\nlines(alpha, nrmtheta[,1], type=\"o\", col=\"blue\")\nlines(alpha, nrmtheta[,2], type=\"o\", pch=22, lty=2, col=\"red\")\naxis(1, at=xrange, labels=round(xrange, 3))\naxis(2, at=yrange, labels=paste(round(yrange, 3), \"%\", sep=\"\"))\nlegend(\"topright\", inset=0.05,\n\tlegend = c(expression(theta[0]), expression(theta[1])),\n\tcol=c(\"blue\",\"red\"),\n\tpch=c(21, 22),\n\tlty=c(1, 2));\n\ngrid(10, 10)\nbox()\ntitle(main=\"Impact of different learning rate on values of\\n hypothesis function coefficients after 500 iterations\", font.main=1)\ntitle(xlab=expression(paste(\"Learning Rate (\", alpha, \")\")), col.lab='black')\ntitle(ylab=expression(paste(\"Normalized Error\")), col.lab='black')\ntrash <- dev.off()\n\n##\n#\n##\nget_iterations <- function(x, y, alpha, realtheta) {\n\tx <- cbind(1, x)\n\tm <- nrow(x)\n\ttheta <- c(0, 0)\n\tcounter <- 0\n\tsatisfy <- FALSE\n\twhile (!all(abs(realtheta - theta)/realtheta*100 < c(1, 1))) {\n\t\ttheta[1] <- theta[1] - alpha * (1/m) * sum(((x%*%theta)- y))\n\t\ttheta[2] <- theta[2] - alpha * (1/m) * sum(((x%*%theta)- y)*x[,2])\n\t\tcounter <- counter + 1\n\t}\n\treturn(counter)\n}\n\n##\n# compute required number of iterations to acheive less than 1 percent error\n# for different learning rates\n##\nmin <- 0.001\nmax <- 0.024\nnum <- 20\nalpha <- seq(min, max, length.out=num)\niterations <- vector(mode=\"numeric\", num)\nfor (i in 1:length(alpha)) {\n\titerations[i] <- get_iterations(data$population, data$profit, alpha[i], realtheta)\n}\n\n##\n# plot required number of iterations for different learning rates\n##\npng(filename=file.path(pngdir, paste(courseNameFull, \"-hw02-07\", \".png\", sep=\"\")),\n\theight=768, width=1024, res=150, units=\"px\", bg=\"white\")\n\nxrange <- seq(min(alpha), max(alpha), length.out=5)\nyrange <- seq(floor(min(iterations)/5000)*5000,\n\tceiling(max(iterations)/5000)*5000,\n\tlength.out=5\n\t)\nplot(0, 0, type=\"n\", axes=F, ann=F,\n\txlim=range(xrange), ylim=range(yrange))\nlines(alpha, iterations, type=\"o\", col=\"blue\")\naxis(1, at=xrange, labels=round(xrange, 3))\naxis(2, at=yrange, labels=round(yrange, 3))\n\ngrid(10, 10)\nbox()\ntitle(main=\"Required number of iterations for different learning rates\\n to achieve less than one percent error\", font.main=1)\ntitle(xlab=expression(paste(\"Learning Rate (\", alpha, \")\")), col.lab='black')\ntitle(ylab=\"Required Number of Iterations\", col.lab='black')\ntrash <- dev.off()\n\n##\n# predict profit of store, given population of the city\n##\ngiven_population <- 645966 * 1e-4\npredicted_profit <- c(1, given_population) %*% realtheta\npredicted_profit\n\nnew_row <- cbind(given_population, predicted_profit)\ncolnames(new_row) <- c('population', 'profit')\nnew_data <- rbind(data, new_row)\n\n##\n# visualize dataset and include the estimated profit for Boston\n##\npng(filename=file.path(pngdir, paste(courseNameFull, \"-hw02-08\", \".png\", sep=\"\")),\n\theight=768, width=1024, res=150, units=\"px\", bg=\"white\")\n\nxrange <- seq(floor(min(new_data$population)/5)*5,\n\tceiling(max(new_data$population)/5)*5,\n\tlength.out=5\n\t)\nyrange <- seq(floor(min(new_data$profit)/5)*5,\n\tceiling(max(new_data$profit)/5)*5,\n\tlength.out=7\n\t)\nplot(0, 0, type=\"n\", axes=F, ann=F,\n\txlim=range(xrange), ylim=range(yrange))\npoints(data$population, data$profit, type=\"p\", col=\"blue\")\nabline(lm(data$profit ~ data$population), col=\"red\")\npoints(new_row[1], new_row[2], type=\"p\", col=\"green\")\naxis(1, at=xrange, labels=round(xrange, 3))\naxis(2, at=yrange, labels=round(yrange, 3))\n\ngrid(10, 10)\nbox()\ntitle(main=\"Profit of Coffee Shop Based on City's Population\", font.main=1)\ntitle(xlab=\"Population in 10,000\", col.lab='black')\ntitle(ylab=\"Profit in $10,000\", col.lab='black')\ntrash <- dev.off()\n", "meta": {"hexsha": "f4b792cd2a4e10e186838280eb3db12955f2abe2", "size": 9620, "ext": "r", "lang": "R", "max_stars_repo_path": "umb-cs638-2016s/src/r/hw02.r", "max_stars_repo_name": "ghorbanzade/beacon", "max_stars_repo_head_hexsha": "c36e3d1909b9e1e47b1ad3cda81f7f33b713adc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-13T20:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T11:16:51.000Z", "max_issues_repo_path": "umb-cs638-2016s/src/r/hw02.r", "max_issues_repo_name": "ghorbanzade/beacon", "max_issues_repo_head_hexsha": "c36e3d1909b9e1e47b1ad3cda81f7f33b713adc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "umb-cs638-2016s/src/r/hw02.r", "max_forks_repo_name": "ghorbanzade/beacon", "max_forks_repo_head_hexsha": "c36e3d1909b9e1e47b1ad3cda81f7f33b713adc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-09-20T05:58:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T17:18:05.000Z", "avg_line_length": 30.251572327, "max_line_length": 129, "alphanum_fraction": 0.6669438669, "num_tokens": 2983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.9032942158155877, "lm_q1q2_score": 0.8219137310706032}} {"text": "# Finding shortest path\n# Ko Byeongmin\n# Jan 26 2021\n\n# functions\n\ngreedy <- function(costdata) { # calculates optimal path with greedy algorithm\n \n num.row <- dim(costdata)[1]\n num.col <- dim(costdata)[2]\n \n path = rbind(c(1,1))\n \n i <- 1\n j <- 1\n \n while (i < num.row & j < num.col) {\n if (costdata[i+1, j] > costdata[i, j+1]) {\n j <- j+1\n path = rbind(path, c(i, j))\n } else {\n i <- i+1\n path = rbind(path, c(i, j))\n }\n }\n \n if (i == num.row) {\n while (j < num.col) {\n j <- j+1\n path = rbind(path, c(i, j))\n }\n }\n \n if (j == num.col) {\n while (i < num.row) {\n i <- i+1\n path = rbind(path, c(i, j))\n }\n }\n \n totalexpense = 0\n \n for (i in 1:dim(path)[1]) {\n totalexpense = totalexpense + costdata[path[i, 1], path[i, 2]]\n }\n \n return(list(\"grid\" = costdata, \"path\" = path, \"totalexpense\" = totalexpense))\n \n}\n\nexpensecalc <- function (costdata) { # calculates optimal path recursively\n \n num.row <- dim(costdata)[1]\n num.col <- dim(costdata)[2]\n expense <- matrix(\n nrow = num.row,\n ncol = num.col,\n data = 0\n )\n\n for (i in 1:(num.col-1)) {\n expense[num.row, (num.col-i)] =\n costdata[num.row, (num.col-i)] +\n expense[num.row, (num.col-i+1)]\n }\n \n for (i in 1:(num.row-1)) {\n expense[(num.row-i), num.col] =\n costdata[(num.row-i), num.col] +\n expense[(num.row-i+1), num.col]\n }\n \n for (j in 1:(num.col-1)) {\n for (i in 1:(num.row-1)) {\n if (expense[(num.row-i), (num.col-j+1)] >= expense[(num.row-i+1), (num.col-j)]) {\n expense[(num.row-i), (num.col-j)] = expense[(num.row-i+1), (num.col-j)] +\n costdata[(num.row-i), (num.col-j)]\n } else {\n expense[(num.row-i), (num.col-j)] = expense[(num.row-i), (num.col-j+1)] +\n costdata[(num.row-i), (num.col-j)]\n }\n }\n }\n\n path = rbind(c(1,1))\n \n i <- 1\n j <- 1\n \n while (i < num.row & j < num.col) {\n if (expense[i+1, j] > expense[i, j+1]) {\n j <- j+1\n path = rbind(path, c(i, j))\n } else {\n i <- i+1\n path = rbind(path, c(i, j))\n }\n }\n \n if (i == num.row) {\n while (j < num.col) {\n j <- j+1\n path = rbind(path, c(i, j))\n }\n }\n \n if (j == num.col) {\n while (i < num.row) {\n i <- i+1\n path = rbind(path, c(i, j))\n }\n }\n \n totalexpense = 0\n \n for (i in 1:dim(path)[1]) {\n totalexpense = totalexpense + costdata[path[i, 1], path[i, 2]]\n }\n \n return(list(\"grid\" = costdata, \"path\" = path, \"totalexpense\" = totalexpense))\n \n}\n\n## showcase\n\ncostdata <- matrix(\n data = c(2, 5 ,3, 8, 6,\n 4, 2, 9, 4, 1,\n 5, 3, 2, 6, 9,\n 0, 3, 8, 5, 0),\n nrow = 4,\n ncol = 5,\n byrow = T\n)\n\nprint(costdata)\n\nmyway = expensecalc(costdata)\nmyway$path\nmyway$totalexpense\nmyanotherway = greedy(costdata)\nmyanotherway$path\nmyanotherway$totalexpense\n\n## performance review\n\ntestcost <- function(nrow, ncol, times) {\n \n diff = 0\n \n for (trial in 1:times) {\n \n costdata <- matrix(\n data = sample(x = 0:15, size = nrow*ncol, replace = TRUE),\n nrow = nrow,\n ncol = ncol\n )\n \n diff = c(diff, (greedy(costdata)$totalexpense - expensecalc(costdata)$totalexpense))\n }\n\n return(diff[-1])\n}\n\nmytest = testcost(10, 12, 1000)\nplot(mytest, type = \"l\",\n main = \"Differnce of costs: how bad is the greedy algorithm?\",\n sub = \"Done on 10 by 12 Grid. Costs sampled from 0 to 15\",\n xlab = \"Trial\", \n ylab = \"Difference in costs\")\nabline(h = mean(mytest), col = \"red\")\nmean(mytest)", "meta": {"hexsha": "6bf19aaa206f94cd34069cb7836e6956b9fa3e49", "size": 3956, "ext": "r", "lang": "R", "max_stars_repo_path": "shortest-path.r", "max_stars_repo_name": "kobyeongmin/shortest-path", "max_stars_repo_head_hexsha": "db5589c7ae8202fe8a42781806ffb2ce7b00ec39", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shortest-path.r", "max_issues_repo_name": "kobyeongmin/shortest-path", "max_issues_repo_head_hexsha": "db5589c7ae8202fe8a42781806ffb2ce7b00ec39", "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": "shortest-path.r", "max_forks_repo_name": "kobyeongmin/shortest-path", "max_forks_repo_head_hexsha": "db5589c7ae8202fe8a42781806ffb2ce7b00ec39", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0, "max_line_length": 93, "alphanum_fraction": 0.4651162791, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.9111797154386841, "lm_q1q2_score": 0.8218118253884518}} {"text": "library(tidyverse)\r\nlibrary(stringr)\r\nlibrary(purrr)\r\nlibrary(lubridate)\r\nlibrary(readr)\r\nlibrary(forecast)\r\n\r\nsetwd(\"C:/Users/Ghozy Haqqoni/Documents/!Kuliah/Semester 5 - DS/Time Series/datas/\")\r\n\r\n#########\r\n#CHAPTER 4\r\n#########\r\n\r\n####Simulate the autoregressive model####\r\n# Simulate an AR model with 0.5 slope\r\nx <- arima.sim(model = list(ar = 0.5), n = 100)\r\n# Simulate an AR model with 0.9 slope\r\ny <- arima.sim(model = list(ar = 0.9), 100)\r\n# Simulate an AR model with -0.75 slope\r\nz <- arima.sim(model = list(ar = -0.75), 100)\r\n# Plot your simulated data\r\nplot.ts(cbind(x, y, z))\r\n####\r\n\r\n####Estimate the autocorrelation function (ACF) for an autoregression####\r\n# Calculate the ACF for x\r\nacf(x)\r\n# Calculate the ACF for y\r\nacf(y)\r\n# Calculate the ACF for z\r\nacf(z)\r\n####\r\n\r\n####Compare the random walk (RW) and autoregressive (AR) models####\r\n# Simulate and plot AR model with slope 0.9 \r\nx <- arima.sim(model = list(ar =.9), n = 200)\r\nts.plot(x)\r\nacf(x)\r\n# Simulate and plot AR model with slope 0.98\r\ny <- arima.sim(model = list(ar =.98), n = 200)\r\nts.plot(y)\r\nacf(y)\r\n# Simulate and plot RW model (diff = 1)\r\nz <- arima.sim(model = list(order = c(0,1,0)), n = 200)\r\nts.plot(z)\r\nacf(z)\r\n####\r\n\r\n####################################################\r\n####AR Model Estimation and Forecasting#### <- video\r\n#load data\r\ndata(Mishkin, package = \"Ecdat\")\r\nclass(Mishkin)\r\nView(Mishkin)\r\n#make inflation -> ts\r\ninflation <- as.ts(Mishkin[,1])\r\nclass(inflation)\r\n#AR Processes: Inflation Rate\r\nts.plot(inflation); acf(inflation)\r\n#AR Model: Inflation Rate\r\nlibrary(forecast)\r\nAR_inflation2 <- arima(inflation, order = c(1,0,0))\r\nAR_inflation2\r\n#AR Processes: Fitted Values \r\nts.plot(inflation)\r\nAR_inflation_fitted2 <- inflation - residuals(AR_inflation2)\r\npoints(AR_inflation_fitted2, type = \"l\", col = \"red\",\r\n lty = 2)\r\n#forecasting\r\npredict(AR_inflation2) #1-step ahead forecasts\r\npredict(AR_inflation2, n.ahead = 5) #n-step ahead forecasts\r\n####\r\n####################################################\r\n\r\n####Estimate the autoregressive (AR) model####\r\n# Fit the AR model to x\r\narima(x, order = c(1,0,0))\r\n# Copy and paste the slope (ar1) estimate\r\n0.8575\r\n# Copy and paste the slope mean (intercept) estimate\r\n-0.0948\r\n# Copy and paste the innovation variance (sigma^2) estimate\r\n1.022\r\n# Fit the AR model to AirPassengers\r\nAR <- arima(AirPassengers, order = c(1,0,0))\r\nprint(AR)\r\n# Run the following commands to plot the series and fitted values\r\nts.plot(AirPassengers)\r\nAR_fitted <- AirPassengers - residuals(AR)\r\nprint(AR_fitted)\r\npoints(AR_fitted, type = \"l\", col = 2, lty = 2)\r\n####\r\n\r\n####Simple forecasts from an estimated AR model####\r\ndata(\"Nile\")\r\n# Fit an AR model to Nile\r\nAR_fit <-arima(Nile, order = c(1,0,0))\r\nprint(AR_fit)\r\n# Use predict() to make a 1-step forecast\r\npredict_AR <- predict(AR_fit)\r\n# Obtain the 1-step forecast using $pred[1]\r\npredict_AR$pred[1]\r\n# Use predict to make 1-step through 10-step forecasts\r\npredict(AR_fit, n.ahead = 10)\r\n# Run to plot the Nile series plus the forecast and 95% prediction intervals\r\nts.plot(Nile, xlim = c(1871, 1980))\r\nAR_forecast <- predict(AR_fit, n.ahead = 10)$pred\r\nAR_forecast_se <- predict(AR_fit, n.ahead = 10)$se\r\npoints(AR_forecast, type = \"l\", col = 2)\r\npoints(AR_forecast - 2*AR_forecast_se, type = \"l\", col = 2, lty = 2)\r\npoints(AR_forecast + 2*AR_forecast_se, type = \"l\", col = 2, lty = 2)\r\n####\r\n\r\n#########\r\n#CHAPTER 5\r\n#########\r\n\r\n#The Simple Moving Average Model\r\n\r\n####Simulate the simple moving average model####\r\n# Generate MA model with slope 0.5\r\nx <- arima.sim(model = list(ma = 0.5), n = 100)\r\n# Generate MA model with slope 0.9\r\ny <- arima.sim(model = list(ma = 0.9), n = 100)\r\n# Generate MA model with slope -0.5\r\nz <- arima.sim(model = list(ma = -0.5), n = 100) \r\n# Plot all three models together\r\nplot.ts(cbind(x, y, z))\r\n####\r\n\r\n####Estimate the autocorrelation function (ACF) for a moving average####\r\n# Calculate ACF for x\r\nacf(x)\r\n# Calculate ACF for y\r\nacf(y)\r\n# Calculate ACF for z\r\nacf(z)\r\n####\r\n\r\n####################################################\r\n####MA Model Estimation and Forecasting\r\n#load data\r\ndata(Mishkin, package = \"Ecdat\")\r\nclass(Mishkin)\r\nView(Mishkin)\r\n#make inflation -> ts\r\ninflation <- as.ts(Mishkin[,1])\r\nclass(inflation)\r\n#MA Processes: Changes (diff) in Inflation Rate\r\ninflation_diff <- diff(inflation)\r\nts.plot(inflation); ts.plot(inflation_diff)\r\nacf(inflation_diff, lag.max=24)\r\n#MA Model\r\nMA_inflation_diff <- arima(inflation_diff, order=c(0,0,1))\r\nMA_inflation_diff\r\n#MA Processes: Fitted Value\r\nts.plot(inflation_diff)\r\nMA_inflation_diff_fitted <- inflation_diff - residuals(MA_inflation_diff)\r\npoints(MA_inflation_diff_fitted, type=\"l\",\r\n col = \"red\", lty = 2)\r\n#forecast\r\npredict(MA_inflation_diff, n.ahead = 5)\r\n####################################################\r\n\r\n####Estimate the simple moving average model####\r\n# Fit the MA model to x\r\narima(x, order = c(0,0,1))\r\n# Paste the slope (ma1) estimate below\r\n.7928\r\n# Paste the slope mean (intercept) estimate below\r\n.1589\r\n# Paste the innovation variance (sigma^2) estimate below\r\n.9576\r\n# Fit the MA model to Nile\r\ndata(\"Nile\")\r\nMA <- arima(Nile, order = c(0,0,1))\r\nprint(MA)\r\nAIC(MA); BIC(MA)\r\n# Plot Nile and MA_fit \r\nts.plot(Nile)\r\nMA_fit <- Nile - resid(MA)\r\npoints(MA_fit, type = \"l\", col = 2, lty = 2)\r\n####\r\n\r\n####Simple forecasts from an estimated MA model####\r\n# Make a 1-step forecast based on MA\r\npredict_MA <- predict(MA)\r\npredict_MA\r\n# Obtain the 1-step forecast using $pred[1]\r\npredict_MA$pred[1]\r\n# Make a 1-step through 10-step forecast based on MA\r\npredict(MA, 10)\r\n# Plot the Nile series plus the forecast and 95% prediction intervals\r\nts.plot(Nile, xlim = c(1871, 1980))\r\nMA_forecasts <- predict(MA, n.ahead = 10)$pred\r\nMA_forecast_se <- predict(MA, n.ahead = 10)$se\r\npoints(MA_forecasts, type = \"l\", col = 2)\r\npoints(MA_forecasts - 2*MA_forecast_se, type = \"l\", col = 2, lty = 2)\r\npoints(MA_forecasts + 2*MA_forecast_se, type = \"l\", col = 2, lty = 2)\r\n####\r\n\r\n#Compare the AR and MA Models\r\n\r\n####AR vs MA models####\r\n# Find correlation between AR_fit and MA_fit\r\ncor(AR_fit, MA_fit)\r\n# Find AIC of AR\r\nAIC(AR)\r\n# Find AIC of MA\r\nAIC(MA)\r\n# Find BIC of AR\r\nBIC(AR)\r\n# Find BIC of MA\r\nBIC(MA)\r\n####\r\n", "meta": {"hexsha": "d8a2ac3d840e2d486ba6cb8bff71f074a090b5e7", "size": 6226, "ext": "r", "lang": "R", "max_stars_repo_path": "Time_Series_with_R_Track/2_Introduction_to_TimeSeries_Analysis/Introduction_to_TimeSeries_Analysis_04-05.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": "Time_Series_with_R_Track/2_Introduction_to_TimeSeries_Analysis/Introduction_to_TimeSeries_Analysis_04-05.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": "Time_Series_with_R_Track/2_Introduction_to_TimeSeries_Analysis/Introduction_to_TimeSeries_Analysis_04-05.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": 28.8240740741, "max_line_length": 85, "alphanum_fraction": 0.6482492772, "num_tokens": 1916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641186, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.8212828693604914}} {"text": "#' Compute the squared error\n#'\n#' This function computes the elementwise squared error for a\n#' number or a vector\n#'\n#' @param actual ground truth number or vector\n#' @param predicted predicted number or vector\n#' @export\nse <- function (actual, predicted) (actual-predicted)^2\n\n#' Compute the mean squared error#'\n#' This function computes the mean squared error between\n#' two vectors\n#'\n#' @param actual ground truth vector\n#' @param predicted predicted vector\n#' @export\nmse <- function (actual, predicted) mean(se(actual, predicted))\n\n#' Compute the root mean squared error#'\n#' This function computes the root mean squared error\n#' between two vectors\n#'\n#' @param actual ground truth vector\n#' @param predicted predicted vector\n#' @export\nrmse <- function (actual, predicted) sqrt(mse(actual, predicted))\n\n#' Compute the absolute error#'\n#' This function computes the elementwise absolute error for a\n#' number or a vector\n#'\n#' @param actual ground truth number or vector\n#' @param predicted predicted number or vector\n#' @export\nae <- function (actual, predicted) abs(actual-predicted)\n\n#' Compute the mean absolute error#'\n#' This function computes the mean absolte error between\n#' two vectors\n#'\n#' @param actual ground truth vector\n#' @param predicted vector\n#' @export\nmae <- function (actual, predicted) mean(ae(actual, predicted))\n\n#' Compute the squared log error\n#'\n#' This function computes the elementwise squared log error for a\n#' number or a vector\n#'\n#' @param actual ground truth number or vector\n#' @param predicted predicted number or vector\n#' @export\nsle <- function (actual, predicted) (log(1+actual)-log(1+predicted))^2\n\n#' Compute the mean squared log error\n#'\n#' This function computes the mean squared log error between\n#' two vectors\n#'\n#' @param actual ground truth vector\n#' @param predicted predicted vector\n#' @export\nmsle <- function (actual, predicted) mean(sle(actual, predicted))\n\n#' Compute the root mean squared log error\n#'\n#' This function computes the root mean squared log error between\n#' two vectors\n#'\n#' @param actual ground truth vector\n#' @param predicted predicted vector\n#' @export\nrmsle <- function (actual, predicted) sqrt(msle(actual, predicted))\n\n#' Compute the area under the ROC (AUC)\n#'\n#' This function computes the area under the receiver-operator\n#' characteristic (AUC)\n#'\n#' @param actual binary vector\n#' @param predicted real-valued vector that defines the ranking\n#' @export\nauc <- function(actual, predicted)\n{\n r <- rank(predicted)\n n_pos <- sum(actual==1)\n n_neg <- length(actual) - n_pos\n auc <- (sum(r[actual==1]) - n_pos*(n_pos+1)/2) / (n_pos*n_neg)\n auc\n}\n\n#' Compute the log loss\n#'\n#' This function computes the elementwise log loss for a\n#' number or a vector\n#'\n#' @param actual binary ground truth number or vector\n#' @param predicted predicted number or vector\n#' @export\nll <- function(actual, predicted)\n{\n score <- -(actual*log(predicted) + (1-actual)*log(1-predicted))\n score[actual==predicted] <- 0\n score[is.nan(score)] <- Inf\n score\n}\n\n#' Compute the mean log loss\n#'\n#' This function computes the mean log loss between\n#' two vectors\n#'\n#' @param actual binary ground truth vector\n#' @param predicted predicted vector\n#' @export\nlogLoss <- function(actual, predicted) mean(ll(actual, predicted))\n\n#' Compute the average precision at k\n#'\n#' This function computes the average precision at k\n#' between two sequences\n#'\n#' @param k max length of predicted sequence\n#' @param actual ground truth set (vector)\n#' @param predicted predicted sequence (vector)\n#' @export\napk <- function(k, actual, predicted)\n{\n score <- 0.0\n cnt <- 0.0\n for (i in 1:min(k,length(predicted)))\n {\n if (predicted[i] %in% actual && !(predicted[i] %in% predicted[0:(i-1)]))\n {\n cnt <- cnt + 1\n score <- score + cnt/i \n }\n }\n score <- score / min(length(actual), k)\n score\n}\n\n#' Compute the mean average precision at k\n#'\n#' This function computes the mean average precision at k\n#' of two lists of sequences.\n#'\n#' @param k max length of predicted sequence\n#' @param actual list of ground truth sets (vectors)\n#' @param predicted list of predicted sequences (vectors)\n#' @export\nmapk <- function (k, actual, predicted)\n{\n scores <- rep(0, length(actual))\n for (i in 1:length(scores))\n {\n scores[i] <- apk(k, actual[[i]], predicted[[i]])\n }\n score <- mean(scores)\n score\n}\n\n#' Compute the classification error\n#'\n#' This function computes the classification error\n#' between two vectors\n#'\n#' @param actual ground truth vector\n#' @param predicted predicted vector\n#' @export\nce <- function (actual, predicted)\n{\n cntError <- 0.0\n for (i in 1:length(actual))\n {\n if (actual[i] != predicted[i])\n {\n cntError <- cntError + 1\n }\n }\n\n score = cntError / length(actual)\n score\n}\n\n#' Compute the quadratic weighted kappa\n#'\n#' This function computes the quadratic weighted kappa\n#' between two vectors of integers\n#'\n#' @param rater.a is the first rater's ratings\n#' @param rater.b is the second rater's ratings\n#' @param min.rating is the minimum possible rating\n#' @param max.rating is the maximum possible rating\n#' @export\nScoreQuadraticWeightedKappa <- function (rater.a , rater.b, \n min.rating,\n max.rating) {\n\n if (missing(min.rating)) {\n min.rating <- min(min(rater.a),min(rater.b))\n }\n if (missing(max.rating)) {\n max.rating <- max(max(rater.a),max(rater.b))\n }\n \n rater.a <- factor(rater.a, levels<-min.rating:max.rating)\n rater.b <- factor(rater.b, levels<-min.rating:max.rating)\n\n #pairwise frequencies\n confusion.mat <- table(data.frame(rater.a, rater.b))\n confusion.mat <- confusion.mat / sum(confusion.mat)\n \n #get expected pairwise frequencies under independence\n histogram.a <- table(rater.a) / length(table(rater.a))\n histogram.b <- table(rater.b) / length(table(rater.b))\n expected.mat <- histogram.a %*% t(histogram.b)\n expected.mat <- expected.mat / sum(expected.mat)\n\n #get weights\n labels <- as.numeric( as.vector (names(table(rater.a))))\n weights <- outer(labels, labels, FUN <- function(x,y) (x-y)^2 )\n\n #calculate kappa\n kappa <- 1 - sum(weights*confusion.mat)/sum(weights*expected.mat)\n kappa\n}\n\n#' Compute the mean quadratic weighted kappa\n#'\n#' This function computes the mean quadratic weighted\n#' kappa, which can optionally be weighted\n#'\n#' @param kappas is a vector of possible kappas\n#' @param weights is an optional vector of ratings\n#' @export\nMeanQuadraticWeightedKappa <- function (kappas, weights) {\n\n if (missing(weights)) {\n weights <- rep(1, length(kappas))\n } else {\n weights <- weights / mean(weights)\n }\n\n max999 <- function(x) sign(x)*min(0.999,abs(x))\n min001 <- function(x) sign(x)*max(0.001,abs(x))\n kappas <- sapply(kappas, max999)\n kappas <- sapply(kappas, min001)\n \n r2z <- function(x) 0.5*log((1+x)/(1-x))\n z2r <- function(x) (exp(2*x)-1) / (exp(2*x)+1)\n kappas <- sapply(kappas, r2z)\n kappas <- kappas * weights\n kappas <- mean(kappas)\n kappas <- z2r(kappas)\n kappas\n}\n", "meta": {"hexsha": "e1819341ebbdea42fc8fa12fe0a7b35935d67290", "size": 7268, "ext": "r", "lang": "R", "max_stars_repo_path": "R/R/metrics.r", "max_stars_repo_name": "fayimora/Metrics", "max_stars_repo_head_hexsha": "2f5171d326a5e05f73430bb0444e11ef923805d8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-03-20T13:34:20.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-20T13:34:20.000Z", "max_issues_repo_path": "R/R/metrics.r", "max_issues_repo_name": "zzz123xyz/Metrics", "max_issues_repo_head_hexsha": "5ae41fc3763f4fd4a25a7863ab139ef2709e9565", "max_issues_repo_licenses": ["BSD-2-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": "R/R/metrics.r", "max_forks_repo_name": "zzz123xyz/Metrics", "max_forks_repo_head_hexsha": "5ae41fc3763f4fd4a25a7863ab139ef2709e9565", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-23T23:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-23T23:22:13.000Z", "avg_line_length": 27.9538461538, "max_line_length": 80, "alphanum_fraction": 0.666758393, "num_tokens": 1848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142221377825, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.8212082104860966}} {"text": "# Example : 2 Chapter : 6.2 Page No: 300\r\n# The diagonal matrix of any matrix contains the eigen values in its main diagonal\r\nA<-matrix(c(0.8,0.2,0.3,0.7),ncol=2)\r\nlambda<-eigen(A)$values\r\nprint(lambda)\r\nS<-eigen(A)$vectors #Normlised eigen vectors, Answer can also be validated with normalised eigen vectors\r\n#to get eigen vector matrix in text book\r\nS[,1]<-S[,1]*(0.6/S[1,1])\r\nS[,2]<-S[,2]*(1/S[1,2])\r\nS1<-solve(S)\r\nDiag_matrix<-diag(2)*lambda\r\nprint(\"S*diag_matrix(A)*S-1 is A\")\r\nprint(S%*%Diag_matrix%*%S1)\r\n#The answer may slightly vary due to rounding off values\r\n#The answers provided in the text book may vary because of the computation process\r\n#Both answers are correct , here it is taken -Ax+b=0 , In the text book it is considered as Ax-b=0", "meta": {"hexsha": "09d7f4c4fa79b278e25398a56db87d40df5dea40", "size": 760, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.2.2/Ex6.2_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.2.2/Ex6.2_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.2.2/Ex6.2_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": 47.5, "max_line_length": 105, "alphanum_fraction": 0.7026315789, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8740772466456688, "lm_q1q2_score": 0.8207802314245456}} {"text": "#!/usr/bin/env Rscript\n\n# eg.1 假设检验\nw = scan(\"res/sugar.txt\")\n\npar(mfrow=c(1,1))\nhist(x=w, main=\"Histogram of sugar weight\")\n\nsummary(object = w)\n\n# QQ正态图\npar(mfrow=c(1,1))\nqqnorm(w)\nqqline(w)\n\n# H0: u = 500 <=> H1: u < 500\n# 检验统计量的分布从H0导出, 如果有矛盾, 就对H0不利\n# p值: 检验统计量取实现值以及更极端值的概率\n# p值很小: 在H0下, 小概率的事件发生了\n# 显著性水平alpha, PV < alpha 拒绝H0\n# R软件给出PValue值, 一般不给alpha, PValue又叫观测的显著性水平(sig)\n# alpha不是越小越好, 越小越不好拒绝H0, 导致犯第二类错误\n# 显著性水平和临界值是前计算机时代, 因为计算难度\n# 现在计算机直接给出P-Value和统计量的实现值\n\n# Nvim: \\rp可以直接看结果\nresult = t.test(x = w, mu = 500, alternative = \"less\")\nprint(result$p.value)\n\n\n# eg.2 \nw = scan(\"res/exh.txt\")\nresult = t.test(w, mu = 20, alternative = \"greater\")\nprint(result$p.value)\n\n\n# eg.3 (w1, w2必需相互独立)\nw = read.table(file = \"res/drug.txt\", header = T)\nw1 = w[w[,2]==1,1]\nw2 = w[w[,2]==2,1]\nt.test(w1, w2, alt=\"greater\")\n\n\n# eg.4 (w1, w2 并不相互独立, 不能是u1 = u2假设, 但是可以udiff = before - after的差后的数据)\nw = read.table(file = \"res/diet.txt\", header = T)\nw1 = w$before\nw2 = w$after\nsummary(w1)\nsummary(w2)\n# 我们是在H0的分布下做假设, 然后把实测数据扔进去, 发现这种假设下实测数据的概率很低\nt.test(w$before - w$after, alt = \"greater\")\n# or\nt.test(w$before , w$after, alt = \"greater\", pair = T)\n\n# eg.5: 总体比例的检验\n# 电视收视率调查1500人, 某电视台期望25%看, 实测23%, 是否显著 \n# 二项分布\n# 方法一: 假设分布是B(1500, 0.25), 那么1500*0.23看此台的概率 ---> P-Value\n# p-value: 0.03836\npbinom(q = 1500*0.23, size = 1500, prob = 0.25)\n\n# 方法二: R精确检验 \n# p-value: 0.03837\nbinom.test(0.23*1500, 1500, 0.25, alt=\"less\")\n\n# 方法三: 近似(样本量大), 历史计算问题, 被淘汰\n# p-value: 0.3929\nprop.test(0.23*1500, 1500, 0.25, alt=\"less\")\n\n# eg.5: 两个总体比例之差\n# A收视率: 20% B收视率: 21% A比B好吗?\nn1 = 1200\nn2 = 1300\n\n# 精确\nbinom.test(c(0.20*n1, 0.21*n2), c(n1, n2), alt=\"less\")$p.value\n# 近似\nprop.test(c(0.20*n1, 0.21*n2), c(n1, n2), alt=\"less\")$p.value\n\n\n# eg.6: 连续型变量检验\ndata = scan(\"res/life.txt\")\n# 大于2的数据\ndata[data > 2]\n# Question: 小于2的是否少于70% ?\n# 把疑问作为H0: p = 0.7 (p <= 0.7, 等于0.7, p-value已经很小了, 小于0.7更是如此)\nbinom.test(x = sum(data < 2),\n n = length(data),\n p = 0.7,\n alternative = \"greater\")$p.value\n\n# eg.7: 非参数检验(秩)\n# 如果把数据排序, 中位数100, 大于100, 小于100各0.5的概率\n# 实际上从样本上观测大于100的个数没有一半\ndata = scan(\"res/GS.TXT\")\npbinom(q = 1000, size = 2000, prob = 0.5)\npbinom(q = sum(data > 100), size = length(data), prob = 0.5)\n\n", "meta": {"hexsha": "246e0de5b53e50d10b091d0e37636590c5383d65", "size": 2206, "ext": "r", "lang": "R", "max_stars_repo_path": "R/learn/Wuxizhi/class6.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/class6.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/class6.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": 22.2828282828, "max_line_length": 70, "alphanum_fraction": 0.6323662738, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.8206954557398836}} {"text": "'''\nFor n = 5 and n = 1000, generate a random sample (e.g. using the R-command runif)\nfrom the unif(0; 1) distribution. \nPerform the two tests in c) having size alpha = 0.05 on your datasets. \nFor which of the tests do you reject H0? Discuss your fndings.\n'''\n\nmin_n=5\nmax_n=1000\nx_min = runif(min_n, min = 0, max = 1) #The Uniform Distribution\nx_max = runif(max_n, min = 0, max = 1) #runif (open) will not generate either of the extreme values\n\n#The likelihood ratio statistics rejects H0 if max(x) > 1 which it isnt from U(0,1)\n# theta_MoM = 2*X_bar\n\ntheta_MoM_min = 2* mean(x_min)\ntheta_MoM_max = 2* mean(x_max)\n\nsample.mean = 2*mean(x_min)\nprint(sample.mean)\nsample.n = min_n\nsample.sd = sd(x_min)\nsample.se = sample.sd/sqrt(sample.n)\nbound = ci_for_u(sample)\n\n#MLE\nprint(max(x_min))\n#[1] 0.7081458\n\n#MoM\n#2*sample_mean [1] 0.5812125\n#t-score [1] 2.776445\n#confidence interval [1] 0.2281778 0.9342472\n\nsample.mean = 2* mean(x_max)\nprint(sample.mean)\nsample.n = max_n\nsample.sd = sd(x_max)\nsample.se = sample.sd/sqrt(sample.n)\nbound = ci_for_u(sample)\n\n#MLE\nprint(max(x_max))\n#[1] 0.999497\n\n#MoM\n#2*sample_mean [1] 0.9991154\n#t-score [1] 1.962341\n#confidence interval [1] 0.9814277 1.0168030\n\n# discuss: likelihood ratio test is asymptotically better \n# theta_Mom contains level alpha=0.05 test with theta > 1 when we know U(0,1)\n# But for small sample size MoM is better (n approximatly 5)\n\nci_for_u <- function(sample) {\n\talpha = 0.05\n\tdegrees.freedom = sample.n - 1\n\tt.score = qt(p=alpha/2, df=degrees.freedom,lower.tail=F)\n\tprint(t.score)\n\tmargin.error = t.score * sample.se\n\tbound.lower = sample.mean - margin.error\n\tbound.upper = sample.mean + margin.error\n\tprint(c(bound.lower,bound.upper))\n\treturn (c(bound.lower,bound.upper))\n}\n\n\n'''\n here is a little simulation for the MSE of the estimators of the mean,\n showing that while the MLE if we do not know the lower bound is zero is unbiased,\n the MSEs for the two variants are identical, suggesting that the estimator which \n incorporates knowledge of the lower bound reduces variability.\n \nhttps://stats.stackexchange.com/questions/252129/is-there-an-example-where-mle-produces-a-biased-estimate-of-the-mean \n'''\n\ntheta <- 1\nmean <- theta/2\nreps <- 500000\nn <- 5\nmse <- bias <- matrix(NA, nrow = reps, ncol = 2)\n\nfor (i in 1:reps){\n x <- runif(n, min = 0, max = theta)\n mle.knownlowerbound <- max(x)/2\n mle.unknownlowerbound <- (max(x)+min(x))/2\n mse[i,1] <- (mle.knownlowerbound-mean)^2\n mse[i,2] <- (mle.unknownlowerbound-mean)^2\n bias[i,1] <- mle.knownlowerbound-mean\n bias[i,2] <- mle.unknownlowerbound-mean\n\n}\n\n> colMeans(mse)\n[1] 0.01194837 0.01194413\n\n> colMeans(bias)\n[1] -0.083464968 -0.000121968", "meta": {"hexsha": "6bed78b0c639a1bbeb847a72e8ab929a95653563", "size": 2672, "ext": "r", "lang": "R", "max_stars_repo_path": "stat210/hw2.r", "max_stars_repo_name": "emoen/Time_Series_stat211", "max_stars_repo_head_hexsha": "f30eb0c6a34c1eab8d347670c3b7a54f2c4c89c0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-06T19:14:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:14:00.000Z", "max_issues_repo_path": "stat210/hw2.r", "max_issues_repo_name": "emoen/Time_Series_stat211", "max_issues_repo_head_hexsha": "f30eb0c6a34c1eab8d347670c3b7a54f2c4c89c0", "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": "stat210/hw2.r", "max_forks_repo_name": "emoen/Time_Series_stat211", "max_forks_repo_head_hexsha": "f30eb0c6a34c1eab8d347670c3b7a54f2c4c89c0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-22T07:40:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T07:40:48.000Z", "avg_line_length": 27.2653061224, "max_line_length": 118, "alphanum_fraction": 0.7107035928, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8856314677809303, "lm_q1q2_score": 0.8203637358747456}} {"text": "\r\nGroup1 <- c(5,17,12,10,4)\r\nGroup2 <- c(19,10,9,7,5)\r\nGroup3 <- c(25,15,12,9,8)\r\n \r\nCombined_Groups <- data.frame(cbind(Group1, Group2, Group3)) # combines the data into a single data set.\r\nCombined_Groups # shows spreadsheet like results\r\n#summary(Combined_Groups) # min, median, mean, max\r\n\r\nStacked_Groups <- stack(Combined_Groups)\r\nStacked_Groups #shows the table Stacked_Groups\r\n\r\nAnova_Results <- aov(values ~ ind, data = Stacked_Groups) \r\nsummary(Anova_Results) # shows Anova_Results\r\n\r\n\r\n# answer given in book is wrong because sample varaince calcaulated for group 1 column in book is 33.7 which is wrong\r\n# correct sample varaince is 28.3", "meta": {"hexsha": "da039ef6140127d0652236a61ea1e453ff6689e6", "size": 650, "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.1/Ex8_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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH8/EX8.1/Ex8_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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH8/EX8.1/Ex8_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": 36.1111111111, "max_line_length": 118, "alphanum_fraction": 0.7384615385, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8740772400852113, "lm_q1q2_score": 0.8199928522805501}} {"text": "p = function(x)\n{\n\tdnorm(x,0,1)\n}\n\nmh = function(x,alpha)\n{\n\txt <- runif(1,x-alpha,x+alpha)\n\tif( runif(1) > p(xt) / p(x) )\n\t\txt <- x\n\n\treturn(xt)\n}\n\nsampler = function(L,alpha)\n{\n\tx <- numeric(L)\n\tfor(i in 2:L)\n\t\tx[i] <- mh(x[i-1],alpha)\n\n\treturn(x)\n}\n\npar(mfrow=c(2,2))\nfor(l in c(10,100,1000,10000))\n{\n\thist(sampler(l,1),main=paste(l,\"iterations\"),breaks=50,freq=F,xlim=c(-4,4),ylim=c(0,1))\n\tlines(x0,p(x0))\n}\n\npar(mfrow=c(2,2))\nfor(a in c(0.1,0.5,1,10))\n{\n\thist(sampler(50000,a),main=paste(\"alpha=\",a),breaks=50,freq=F,xlim=c(-4,4),ylim=c(0,1))\n\tlines(x0,p(x0))\n}\n\n#x0 <- seq(-4,4,0.1)\n#plot( x0, p(x0), lty=2 , t='l')\n", "meta": {"hexsha": "7156d4124bbea1ac00854912bc8d53d2c7f4fb88", "size": 622, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 05/mh.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 05/mh.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 05/mh.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": 15.55, "max_line_length": 88, "alphanum_fraction": 0.5707395498, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.8199365727613328}} {"text": "#####################################################################\n###### \t\t\t\t\t\t Applied Linear Model \t ###### \n#####################################################################\nlibrary(\"alr3\")\n###############\n#A data frame with 32 observations on 11 variables in mtcars\n#[, 1]\t mpg\t Miles/(US) gallon\n#[, 2]\t cyl\t Number of cylinders\n#[, 3]\t disp\t Displacement (cu.in.)\n#[, 4]\t hp\t Gross horsepower\n#[, 5]\t drat\t Rear axle ratio\n#[, 6]\t wt\t Weight (lb/1000)\n#[, 7]\t qsec\t 1/4 mile time\n#[, 8]\t vs\t V/S\n#[, 9]\t am\t Transmission (0 = automatic, 1 = manual)\n#[,10]\t gear\t Number of forward gears\n#[,11]\t carb\t Number of carburetors\n######\n###### Problem2 R code\nscatterplotMatrix(mtcars[,c(1, 2, 3, 4, 5, 6, 7)], smooth=FALSE)\ny <- mtcars$mpg\nwt <- mtcars$wt\nhp <- mtcars$hp\nqsec <- mtcars$qsec\ndisp <- mtcars$disp\ncyl <- mtcars$cyl\ndc <- disp/cyl\nm3 <- lm(y~wt+hp+qsec+dc, mtcars)\nsummary(m3)\nanova(m3)\n######\nm4 <- lm(y~wt+hp+qsec, mtcars)\nsummary(m4)\nanova(m4)\n######\nm5 <- lm(y~wt+hp, mtcars)\nsummary(m5)\nanova(m5)\n\n###### Problem 3.1 R code\nlibrary(\"alr3\")\nscatterplotMatrix(BGSgirls[, c(2, 3, 4, 5, 6, 7, 12)], smooth=FALSE)\nprint(cor(BGSgirls[, c(2, 3, 4, 5, 6, 7, 12)]), 3)\n\n######\npar(mfrow=c(2,2))\n\nwt9 <- BGSall$WT9\nlg9 <- BGSall$LG9\nsoma <-BGSall$Soma \n\nplot(wt9, soma)\nfit1 <- lm(soma~wt9)\nabline(fit1)\n\nplot(lg9, soma)\nfit2 <- lm(soma~lg9)\nabline(fit2)\n\nplot(wt9, lg9)\nfit12 <- lm(lg9~wt9)\nabline(fit12)\n\ne12 <- fit12$residuals\ne1 <- fit1$residuals\nplot(e12, e1)\nabline(h=0, lty=\"dashed\")\nabline(v=0, lty=\"dashed\")\nabline(lm(e1~e12))\n\n######\nm1 <- lm(Soma~HT2+WT2+HT9+WT9+ST9, BGSgirls)\nsummary(m1)\n\n######\nanova(m1)\n\n######\nm2 <- lm(Soma~ST9+WT9+HT9+WT2+HT2, BGSgirls)\nanova(m2)\n", "meta": {"hexsha": "3476cefb39b8eebb09f4772151700be2993adbdd", "size": 1718, "ext": "r", "lang": "R", "max_stars_repo_path": "Multiple_Regression_Model_Analysis.r", "max_stars_repo_name": "lancezlin/Applied_Linear_Model_with_R", "max_stars_repo_head_hexsha": "4948c9b2ca7794199d51a545591f7fd7135d7cf1", "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": "Multiple_Regression_Model_Analysis.r", "max_issues_repo_name": "lancezlin/Applied_Linear_Model_with_R", "max_issues_repo_head_hexsha": "4948c9b2ca7794199d51a545591f7fd7135d7cf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Multiple_Regression_Model_Analysis.r", "max_forks_repo_name": "lancezlin/Applied_Linear_Model_with_R", "max_forks_repo_head_hexsha": "4948c9b2ca7794199d51a545591f7fd7135d7cf1", "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.2098765432, "max_line_length": 69, "alphanum_fraction": 0.5518044237, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075755433748, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.8196702447791162}} {"text": "# Example : 3 Chapter : 4.2 Page No: 211\r\n# Find the best possible solution, projection vector and projection matrix\r\n\r\nsolution<-function(A,b){\r\n ATA<-t(A)%*%A\r\n b<-matrix(c(b),ncol=1)\r\n ATb<-t(A)%*%b\r\n xhat<-solve(ATA,ATb)\r\n p<-A%*%xhat\r\n e<-b-p\r\n ATA1<-solve(ATA)\r\n P<-A%*%ATA1\r\n P<-P%*%t(A)\r\n print(\"The best possible solution is \")\r\n print(xhat)\r\n print(\"The projection vector is \")\r\n print(p)\r\n print(\"The error vector e is\")\r\n print(e)\r\n print(\"The projection matrix is \")\r\n print(P)\r\n}\r\n\r\nA<-matrix(c(1,1,1,0,1,2),ncol=2)\r\nb<-c(6,0,0)\r\nsolution(A,b)\r\n#The answer may slightly vary due to rounding off values", "meta": {"hexsha": "7e621c845c5e480777dca1ef17c6cda87198fd78", "size": 640, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.2.3/Ex4.2_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.2.3/Ex4.2_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.2.3/Ex4.2_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.7037037037, "max_line_length": 75, "alphanum_fraction": 0.6078125, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.8196702438965009}} {"text": "### 6.2-4\n\nhypoPerc <- c(0.44, 0.42, 0.1, 0.04)\nexperData <- c(58, 65, 55, 22)\nnSamples <- length(experData)\nnPartic <- sum(experData)\n\nhypoData <- hypoPerc * nPartic\n\nchiSquare <- sum((experData - hypoData)^2 / hypoData)\nprint(chiSquare)\n\n### m = r - k - 1 = 4 - 1 = 3\nchiSquareCritical <- qchisq(0.9, nSamples-1, ncp=0, lower.tail=TRUE, log.p=FALSE) \nprint(chiSquareCritical)\n\n### chiSquare = 100.2749 -> H0 is accepted (the dataset does not obey the hypothetical percentage)\n", "meta": {"hexsha": "725060699321156311b0e5351c5bd1c147f57bf4", "size": 480, "ext": "r", "lang": "R", "max_stars_repo_path": "TASK3/sem3/chiSq2.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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": "TASK3/sem3/chiSq2.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TASK3/sem3/chiSq2.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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.6666666667, "max_line_length": 100, "alphanum_fraction": 0.66875, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.8192873136049853}} {"text": "# __ _____ _ __ _ \n# <(o )___ | _ |___ ___ ___| |_ ___ ___ | | ___| |_ ___ \n# ( ._> / | __| _| -_|_ -| _| -_|_ -| | |__| .'| . |_ -|\n# `---' |__| |_| |___|___|_| |___|___| |_____|__,|___|___|\n#==============================================================================\n# Local Regression NonParametric LOESS\n#==============================================================================\n# Title : Local Regression NP LOESS.r\n# Description : Local Regression - Fit a line with LOESS in R\n# Author : Isaias V. Prestes \n# Date : 20180304\n# Version : 0.0.1\n# Usage : Run in R 3.4\n# Notes : Based on \n# https://stackoverflow.com/questions/15337777/fit-a-line-with-loess-in-r\n# http://ggplot2.tidyverse.org/reference/geom_smooth.html\n# r-statistics.co by Selva Prabhakaran\n# R version : 3.4\n#==============================================================================\n# install.packages('ggplot2')\n\n#==============================================================================\n# LIBRARY DEPENDENCE\n#==============================================================================\nlibrary(ggplot2)\n\n# Loess short for Local Regression is a non-parametric approach that fits \n# multiple regressions in local neighborhood. This can be particularly \n# resourceful, if you know that your X variables are bound within a range.\n\n#------------------------------------------------------------------------------\n# Regular\n#------------------------------------------------------------------------------\nload(url('https://www.dropbox.com/s/ud32tbptyvjsnp4/data.R?dl=1'))\nlw1 <- loess(y ~ x,data=data)\nplot(y ~ x, data=data,pch=19,cex=0.1, main=\"Loess Smoothing and Prediction\")\nj <- order(data$x)\nlines(data$x[j],lw1$fitted[j],col=\"red\",lwd=3)\n\n#------------------------------------------------------------------------------\n# Scatter\n#------------------------------------------------------------------------------\nscatter.smooth(data$y ~ data$x, span = 2/3, degree = 2, main=\"Loess Smoothing and Prediction\")\n\n#------------------------------------------------------------------------------\n# ggplot2\n#------------------------------------------------------------------------------\n# http://ggplot2.tidyverse.org/reference/geom_smooth.html\nload(url(\"https://www.dropbox.com/s/ud32tbptyvjsnp4/data.R?dl=1\"))\nggplot(data, aes(x, y), main=\"Loess Smoothing and Prediction\") + \ngeom_point() +\ngeom_smooth(method = \"loess\", se = FALSE)\n\nggplot(data, aes(x, y)) + \ngeom_point() +\ngeom_smooth(method = \"loess\", se = TRUE)\n\n# Second Example\n\ndata(economics, package=\"ggplot2\") # load data\neconomics$index <- 1:nrow(economics) # create index variable\neconomics <- economics[1:80, ] # retail 80rows for better graphical understanding\nloessMod10 <- loess(uempmed ~ index, data=economics, span=0.10) # 10% smoothing span\nloessMod25 <- loess(uempmed ~ index, data=economics, span=0.25) # 25% smoothing span\nloessMod50 <- loess(uempmed ~ index, data=economics, span=0.50) # 50% smoothing span\n# get smoothed output\nsmoothed10 <- predict(loessMod10) \nsmoothed25 <- predict(loessMod25) \nsmoothed50 <- predict(loessMod50) \n\n# Plot it\nplot(economics$uempmed, x=economics$date, type=\"l\", main=\"Loess Smoothing and Prediction\", xlab=\"Date\", ylab=\"Unemployment (Median)\")\nlines(smoothed10, x=economics$date, col=\"red\")\nlines(smoothed25, x=economics$date, col=\"green\")\nlines(smoothed50, x=economics$date, col=\"blue\")\n\n#------------------------------------------------------------------------------\n# Finding the optimal smoothing span\n#------------------------------------------------------------------------------\n# As the smoothing span changes, the accuracy of the fitted curve also changes. \n# If your intent is to minimize the error, the optim() can be used to find that \n# value of span, that minimizes the Sum of Squared Errors (SSE). For this case, \n# it is graphically intuitive that lower SSE will likely be achieved at lower \n# values of span, but for more challenging cases, optimizing span could help.\n# To implement optim(), we define the function that computes the SSE. An error \n# handling mechanism is needed to address very low values of span and cases where \n# the non-numerics are produced. The simulated annealing method (SANN) is \n# implemented here to find the span that gives minimal SSE. The par argument \n# specifies the first value of the span at which optim() will begin the search.\n\n# define function that returns the SSE\ncalcSSE <- function(x){\n loessMod <- try(loess(uempmed ~ index, data=economics, span=x), silent=T)\n res <- try(loessMod$residuals, silent=T)\n if(class(res)!=\"try-error\"){\n if((sum(res, na.rm=T) > 0)){\n sse <- sum(res^2) \n }\n }else{\n sse <- 99999\n }\n return(sse)\n}\n\n# Run optim to find span that gives min SSE, starting at 0.5\noptim(par=c(0.5), calcSSE, method=\"SANN\")\n\n# EOF", "meta": {"hexsha": "8b434f6c76d7d03c1173e619195015658702f354", "size": 4963, "ext": "r", "lang": "R", "max_stars_repo_path": "Local Regression MP LOESS/Local Regression MP LOESS.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": "Local Regression MP LOESS/Local Regression MP LOESS.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": "Local Regression MP LOESS/Local Regression MP LOESS.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": 45.9537037037, "max_line_length": 133, "alphanum_fraction": 0.544831755, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.9073122232403329, "lm_q1q2_score": 0.8183236613843013}} {"text": "# confidence interval for indpendent sample\r\n\r\nn1= 12\r\nn2= 12\r\ny1bar = 26.58\r\ny2bar=39.67\r\ns1=14.36\r\ns2=13.86\r\n# solving part c\r\n# common standard deviation \r\nsp=sqrt(((n1-1)*s1*s1+(n2-1)*s2*s2)/(n1+n2-2))\r\n\r\n# the t-percentile based on df for 95% confidence interval\r\ntstar=qt( .975, df=18)\r\nmargin=tstar*sp*sqrt((1/n1)+(1/n2))\r\nleft_i=(y1bar-y2bar)-margin\r\nright_i=(y1bar-y2bar)+margin\r\nprint(\"confidence interval is\")\r\nprint(left_i)\r\nprint(right_i)\r\n\r\n# solving part a and b\r\nt=(y1bar-y2bar)/((sp)*sqrt((1/n1)+(1/n2)))\r\nprint(t)\r\n# crtitical value\r\nalpha= 0.05 \r\ndf=n1+n2-2\r\nt.alpha=qt(0.05, df=22)\r\nif(t<=t.alpha){\r\n print(\" We will reject H0\")\r\n}else{\r\n print(\"we will fail to reject H0 (no significant evidence\")\r\n}\r\n\r\n", "meta": {"hexsha": "34a8fee73208d9631afe2377af470726d5724ded", "size": 728, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH6/EX6.3/Ex6_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/CH6/EX6.3/Ex6_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/CH6/EX6.3/Ex6_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": 20.8, "max_line_length": 62, "alphanum_fraction": 0.6565934066, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.8181823801244962}} {"text": "# mean\nmean_g <- function(x, gmean = \"sqrtsin\") {\n switch(\n gmean,\n \"linear\" = 0.2 + 0.4 * x,\n \"log\" = log(x),\n \"sin\" = sin(2 * pi * x),\n \"lsin\" = 0.5 + 2 * x + sin(2 * pi * x - 0.5),\n \"sqrtsin\" = sqrt(x * (1 - x)) * sin(2 * pi * (1 + 2 ^ (-7 / 5)) / (x + 2 ^ (-7 / 5)))\n )\n}\n# error\nerr_sig <- function(x, xsig = \"quad\", derr = \"norm\") {\n v_sig <- switch(\n xsig,\n \"const\" = 0.2,\n \"linear\" = 0.2 + 0.2 * x,\n \"quad\" = 0.5 + 0.5 * (x - 1) ^ 2\n )\n switch(\n derr,\n \"norm\" = rnorm(x, 0),\n \"chisq3\" = rchisq(x, 3),\n \"t3\" = rt(x, 3),\n \"t1\" = rt(x, 1)\n #\"laplace\" = rla\n ) * v_sig\n}\n# error quantile\nerr_qt <- function(x, tau = 0.5, xsig = \"quad\", derr = \"norm\") {\n v_sig <- switch(\n xsig,\n \"const\" = 0.2,\n \"linear\" = 0.2 + 0.2 * x,\n \"quad\" = 0.5 + 0.5 * (x - 1) ^ 2\n )\n switch(\n derr,\n \"norm\" = qnorm(tau, 0),\n \"chisq3\" = qchisq(tau, 3),\n \"t3\" = qt(tau, 3),\n \"t1\" = qt(tau, 1)\n #\"laplace\" = rla\n ) * v_sig\n}\nobs_f <- function(x, gmean = \"sqrtsin\", xsig = \"quad\", derr = \"norm\") {\n mean_g(x, gmean) + err_sig(x, xsig, derr)\n}\ntruth_f <- function(x, tau, gmean = \"sqrtsin\", xsig = \"quad\", derr = \"norm\") {\n mean_g(x, gmean) + err_qt(x, tau, xsig, derr)\n}\n\n# x <- sort(x)\n# plot(x, obs_f(x, derr = \"chisq3\"))\n# for (tau in seq(0.001, 0.999, length.out = 10)) {\n# lines(comp[[3]][[1]]$x, truth_f(comp[[3]][[1]]$x, tau, gmean = \"linear\", xsig = \"linear\", derr = \"t3\"))\n# }\n", "meta": {"hexsha": "1d5348f47877e5a82eca12e34b5253c8e39464f8", "size": 1584, "ext": "r", "lang": "R", "max_stars_repo_path": "R/simulation.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/simulation.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/simulation.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": 27.3103448276, "max_line_length": 109, "alphanum_fraction": 0.4299242424, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8688267694452331, "lm_q1q2_score": 0.8181343455038376}} {"text": "##########################\n# Linear regression in R #\n##########################\n\n\n# Create some data\nx <- c(1,3,4,5,4,3,6,4,8,9,10,11,4,6,2,4,9,12,4)\nn = length(x)\ny <- 3 + 1.6 * x + + 0.5 * x^2 + rnorm(n,mean=0,sd=4)\nplot(x,y) #scatterplot\n\n# Fit a linear regression model\nfit1 <- lm(y~x) # intercept is included automatically\nsummary(fit1)\n\nplot(fit1) # Some standard diagnostics for checking model assumptions\n\n# Alternatively can do this by hand\nfitted1 <- fit1$fitted # fitted values y_hat\nrstd1 <- rstandard(fit1) # standardized residuals\n\n# Residuals against fitted. Always look at this plot. Goal: See no pattern whatsoever\nplot(fitted1,rstd1) # See the U-shaped pattern?\n # Suggests including a quadratic term\n\n# Normality\nqqnorm(rstd1)\nqqline(rstd1) # Normality looks OK\n\n\n\n\n# Try a new model\nx.sq = x^2\nfit2 <- lm(y ~ x + x.sq)\nsummary(fit2)\n\nfitted2 <- fit2$fitted # fitted values y_hat\nrstd2 <- rstandard(fit2) # standardized residuals\n\nplot(fitted2,rstd2) # Now it looks OK. => Use model fit2, not fit1.\n \nqqnorm(rstd2)\nqqline(rstd2) # OK\n\n\n\n\n?lm\n\nfit2$model # It doesn't show the first column that is constant all 1's. But it is used nevertheless (intercept).\n\nfit2$coefficients # The OLS estimate beta_hat\nvcov(fit2) # The variance/covariance matrix of beta_hat\n\n\n\n\n\n# Illustrate Near-collinearity\nx3 <- 2*x + 5*x.sq + rnorm(n,mean=0,sd=0.01)\n\nfit3 <- lm(y ~ x + x.sq + x3)\nsummary(fit3) # The standard errors became huge now. Hard to identify the beta's.\nplot(fit3)\n\nfitted3 <- fit3$fitted # fitted values y_hat\nrstd3 <- rstandard(fit3) # standardized residuals\n\nplot(fitted3,rstd3) #\n\nqqnorm(rstd3)\nqqline(rstd3) # \n\n\n\n\n# How to detect near (multi-)collinearity?\n# Check whether one of the Variance Inflation Factors (VIF) is > 10. If yes => potential problem.\n\n# install.packages(\"car\")\nlibrary(car) # need to install package 'car' first\n\nvif(fit2) # Not great, but not tooo bad either\nvif(fit3) # Catastrophic. Clearly, one of the variables has to go.\n\n\n\n\n# Check numerical stability of calculations by hand\n\n\n# Create model matrix X for model fit3\nfit3$model # Doesn't include constant column with all ones. Have to add it by hand\nconst <- rep(1,n)\nX3_ <- cbind(const,fit3$model[,2:4])\nX3_ # Can't do matrix opertions on this array. Have to convert to matrix.\nX3 <- as.matrix(X3_) \nX3 # That's it\n\n# Easier alternative: X3 <- model.matrix(fit3)\n\nbeta_hat3_naive <- solve(t(X3) %*% X3) %*% t(X3) %*% y\nt(beta_hat3_naive)\nfit3$coef # Here the naive method doesn't create problems yet.\n\nsummary(fit3)\nnames(summary(fit3))\nsigma3 <- summary(fit3)$sigma\n\nV3_naive <- sigma3^2 * solve(t(X3) %*% X3) \nV3_naive\nvcov(fit3) # Comparison shows that the naive method still works\n\n\n\n\n\n\n# Let's make it worse\nx4 <- 2*x + 5*x.sq + rnorm(n,mean=0,sd=0.00005)\n\nfit4 <- lm(y ~ x + x.sq + x4)\nsummary(fit4)\nvif(fit4) # HUGE\n\nX4 <- model.matrix(fit4)\n\nbeta_hat4_naive <- solve(t(X4) %*% X4) %*% t(X4) %*% y\nt(beta_hat4_naive)\nfit4$coef # Here the naive method gives a slightly different result. Numerical instability (rounding error).\n\nsigma4 <- summary(fit4)$sigma\nV4_naive <- sigma4^2 * solve(t(X4) %*% X4) \nV4_naive\nvcov(fit4) # Comparison shows that the naive method start's getting into trouble\n\n\n\n\n\n\n\n# Even worse\nx5 <- 2*x + 5*x.sq + rnorm(n,mean=0,sd=0.000005)\n\nfit5 <- lm(y ~ x + x.sq + x5)\nsummary(fit5) # Even R's QR decomposition can't deal with it any more.\n\n\n\n\n", "meta": {"hexsha": "f8c156ca8d452cf7feabc306a4cc363234dd9b79", "size": 3820, "ext": "r", "lang": "R", "max_stars_repo_path": "fit a linear regression model in r.r", "max_stars_repo_name": "lancezlin/Applied_Linear_Model_with_R", "max_stars_repo_head_hexsha": "4948c9b2ca7794199d51a545591f7fd7135d7cf1", "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": "fit a linear regression model in r.r", "max_issues_repo_name": "lancezlin/Applied_Linear_Model_with_R", "max_issues_repo_head_hexsha": "4948c9b2ca7794199d51a545591f7fd7135d7cf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fit a linear regression model in r.r", "max_forks_repo_name": "lancezlin/Applied_Linear_Model_with_R", "max_forks_repo_head_hexsha": "4948c9b2ca7794199d51a545591f7fd7135d7cf1", "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.9673202614, "max_line_length": 129, "alphanum_fraction": 0.6086387435, "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180243, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.8175733826303629}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Non parametric Tests - Exercise 13\n\nrm(list = ls())\n\na <- c(0.41, 0.45, 0.36, 0.49, 0.39, 0.54, 0.38, 0.43)\nb <- c(0.38, 0.40, 0.32, 0.50, 0.31, 0.52, 0.32, 0.36)\n\n(s <- (a - b)[a != b])\n# 0.03 0.05 0.04 -0.01 0.08 0.02 0.06 0.07\n\n(n <- length(s))\n# 8\n\n(V <- sum((s > 0) * rank(abs(s))))\n# 35\n\n(V.mean <- n * (n + 1) / 4)\n# 18\n\n(V.var <- n * (n + 1) * (2 * n + 1) / 24)\n# 51\n\n### H0: A(x) == B(x)\n### H1: A(x) != B(x)\n\n## Asymptotic pvalue (with continuity correction)\n2 * (1 - pnorm(abs(V + 0.5 * sign(V.mean - V) - V.mean) / sqrt(V.var)))\n# 0.0208625823327655\n\n## Exact pvalue\n2 * (1 - psignrank(V - (V.mean < V), n, lower.tail = V.mean < V))\n# 0.015625\n\nwilcox.test(a, b, paired = TRUE, alternative = \"two.sided\")\n# Wilcoxon signed rank test\n#\n# data: a and b\n# V = 35, p-value = 0.01563\n# alternative hypothesis: true location shift is not equal to 0\n", "meta": {"hexsha": "3756a09d48b594b6162cd0b8222388ada026bde7", "size": 921, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/non-parametric/exercise-13.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-13.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-13.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": 22.4634146341, "max_line_length": 71, "alphanum_fraction": 0.5537459283, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8705972700870909, "lm_q1q2_score": 0.81751243962623}} {"text": "### PART 1:\nmakeHailstone <- function(n){\n hseq <- n\n while (hseq[length(hseq)] > 1){\n current.value <- hseq[length(hseq)]\n if (current.value %% 2 == 0){\n next.value <- current.value / 2\n } else {\n next.value <- (3 * current.value) + 1\n }\n hseq <- append(hseq, next.value)\n }\n return(list(hseq=hseq, seq.length=length(hseq)))\n}\n\n### PART 2:\ntwenty.seven <- makeHailstone(27)\ntwenty.seven$hseq\ntwenty.seven$seq.length\n\n### PART 3:\nmax.length <- 0; lower.bound <- 1; upper.bound <- 100000\n\nfor (index in lower.bound:upper.bound){\n current.hseq <- makeHailstone(index)\n if (current.hseq$seq.length > max.length){\n max.length <- current.hseq$seq.length\n max.index <- index\n }\n}\n\ncat(\"Between \", lower.bound, \" and \", upper.bound, \", the input of \",\n max.index, \" gives the longest hailstone sequence, which has length \",\n max.length, \". \\n\", sep=\"\")\n", "meta": {"hexsha": "7fce19013ec662a1bb951204dcfe71db8b24db00", "size": 893, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Hailstone-sequence/R/hailstone-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/Hailstone-sequence/R/hailstone-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/Hailstone-sequence/R/hailstone-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": 25.5142857143, "max_line_length": 74, "alphanum_fraction": 0.6192609183, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.8174865560680731}} {"text": "##========================================================\n##\n## Credits:\n## Theory by Paul Bourke http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/\n## Based in part on C code by Damian Coventry Tuesday, 16 July 2002\n## Based on VBA code by Brandon Crosby 9-6-05 (2 dimensions)\n## With grateful thanks for answering our needs!\n## This is an R (http://www.r-project.org) implementation by Gregoire Thomas 7/11/08\n##\n##========================================================\n\ndistancePointLine <- function(x, y, slope, intercept) {\n ## x, y is the point to test.\n ## slope, intercept is the line to check distance.\n ##\n ## Returns distance from the line.\n ##\n ## Returns 9999 on 0 denominator conditions.\n x1 <- x-10\n x2 <- x+10\n y1 <- x1*slope+intercept\n y2 <- x2*slope+intercept\n distancePointSegment(x,y, x1,y1, x2,y2)\n}\n\ndistancePointSegment <- function(px, py, x1, y1, x2, y2) {\n ## px,py is the point to test.\n ## x1,y1,x2,y2 is the line to check distance.\n ##\n ## Returns distance from the line, or if the intersecting point on the line nearest\n ## the point tested is outside the endpoints of the line, the distance to the\n ## nearest endpoint.\n ##\n ## Returns 9999 on 0 denominator conditions.\n lineMagnitude <- function(x1, y1, x2, y2) sqrt((x2-x1)^2+(y2-y1)^2)\n ans <- NULL\n ix <- iy <- 0 # intersecting point\n lineMag <- lineMagnitude(x1, y1, x2, y2)\n if( lineMag < 0.00000001) {\n warning(\"short segment\")\n return(9999)\n }\n u <- (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)))\n u <- u / (lineMag * lineMag)\n if((u < 0.00001) || (u > 1)) {\n ## closest point does not fall within the line segment, take the shorter distance\n ## to an endpoint\n ix <- lineMagnitude(px, py, x1, y1)\n iy <- lineMagnitude(px, py, x2, y2)\n if(ix > iy) ans <- iy\n else ans <- ix\n } else {\n ## Intersecting point is on the line, use the formula\n ix <- x1 + u * (x2 - x1)\n iy <- y1 + u * (y2 - y1)\n ans <- lineMagnitude(px, py, ix, iy)\n }\n ans\n}\n\ndistancePointLineTest <- function() {\n if(abs(distancePointSegment( 5, 5, 10, 10, 20, 20) - 7.07106781186548)>.0001)\n stop(\"error 1\")\n if(abs(distancePointSegment( 15, 15, 10, 10, 20, 20) - 0)>.0001)\n stop(\"error 2\")\n if(abs(distancePointSegment( 15, 15, 20, 10, 20, 20) - 5)>.0001)\n stop(\"error 3\")\n if(abs(distancePointSegment( 0, 15, 20, 10, 20, 20) - 20)>.0001)\n stop(\"error 4\")\n if(abs(distancePointSegment( 0, 25, 20, 10, 20, 20) - 20.6155281280883)>.0001)\n stop(\"error 5\")\n if(abs(distancePointSegment(-13, -25, -50, 10, 20, 20) - 39.8808224589213)>.0001)\n stop(\"error 6\")\n if(abs(distancePointSegment( 0, 3, 0, -4, 5, 0) - 5.466082)>.0001)\n stop(\"error 7\")\n if(abs(distancePointSegment( 0, 9, 0, -4, 0, 15) - 0)>.0001)\n stop(\"error 8\")\n if(abs(distancePointSegment( 0, 0, 0, -2, 2, 0)^2 - 2)>.0001)\n stop(\"error 9\")\n return(TRUE)\n}\n\n", "meta": {"hexsha": "83c9b178faef9940ee5080dc9e557f2aae4a6969", "size": 2931, "ext": "r", "lang": "R", "max_stars_repo_path": "R/distpointline.r", "max_stars_repo_name": "jintrone/advice-reification", "max_stars_repo_head_hexsha": "2ed2ceea59dc4e8e891a7220cbd237b2d71ca569", "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/distpointline.r", "max_issues_repo_name": "jintrone/advice-reification", "max_issues_repo_head_hexsha": "2ed2ceea59dc4e8e891a7220cbd237b2d71ca569", "max_issues_repo_licenses": ["MIT"], "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/distpointline.r", "max_forks_repo_name": "jintrone/advice-reification", "max_forks_repo_head_hexsha": "2ed2ceea59dc4e8e891a7220cbd237b2d71ca569", "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.313253012, "max_line_length": 85, "alphanum_fraction": 0.5892186967, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.8933094159957173, "lm_q1q2_score": 0.8172896419442395}} {"text": "#!/usr/bin/Rscript\n\n# Bhishan Poudel\n# Jan 12, 2016\n\n# Chapter. 2 Probability\n################################################################################\n# set the working directory\nsetwd (\"~/Copy/2016Spring/RProgramming/presentation/\")\n\n\n# Start device driver to save output\npostscript(file=\"figures/chap2.eps\", height=14, width=8)\n\n# Set up 6 panel figure\npar(mfrow=c(3,2)) # par is parameter\n\n# Expand right side of clipping rect to make room for the legend\n#par(xpd=T, mar=par()$mar+c(0,0,0,4))\n\n\n# Plot upper left panel with three illustrative \n# exponential p.d.f. distributions (dexp)\nxdens <- seq(0,5,0.02)\nplot(xdens,dexp(xdens,rate=0.5), type='l', ylim=c(0,1.5), xlab='', ylab='Exponential p.d.f.',lty=1)\n\nlines(xdens,dexp(xdens,rate=1), type='l', lty=2)\nlines(xdens,dexp(xdens,rate=1.5), type='l', lty=3)\nlegend(2, 1.45, lty=1, substitute(lambda==0.5), box.lty=0)\nlegend(2, 1.30, lty=2, substitute(lambda==1.0), box.lty=0)\nlegend(2, 1.15, lty=3, substitute(lambda==1.5), box.lty=0)\n\n# Help files to learn these function\n# help(seq) ; help(plot); help(par) ; help(lines); help(legend)\n\n\n# Plot upper right panel with three illustrative exponential c.d.f. distributions\nplot(xdens, pexp(xdens,rate=0.5), type='l', ylim=c(0,1.0), xlab='', ylab='Exponential c.d.f.', lty=1)\nlines(xdens, pexp(xdens,rate=1), type='l', lty=2)\nlines(xdens, pexp(xdens,rate=1.5),type='l',lty=3)\nlegend(3, 0.50, lty=1, substitute(lambda==0.5), box.lty=0)\nlegend(3, 0.38, lty=2, substitute(lambda==1.0), box.lty=0)\nlegend(3, 0.26, lty=3, substitute(lambda==1.5), box.lty=0)\n\n\n# Plot middle panels with illustrative normal p.d.f. and c.d.f. \nxdens <- seq(-5, 5, 0.02)\nylabdnorm <- expression(phi[mu~sigma^2] (x))\nplot(xdens, dnorm(xdens, sd=sqrt(0.2)), type='l', ylim=c(0,1.0), xlab='', ylab=ylabdnorm,lty=1)\nlines(xdens,dnorm(xdens, sd=sqrt(1.0)), type='l', lty=2)\nlines(xdens,dnorm(xdens, sd=sqrt(5.0)), type='l', lty=3)\nlines(xdens,dnorm(xdens, mean=-2.0, sd=sqrt(0.5)), type='l', lty=4)\nleg1 <- expression(mu^' '==0, mu^' '==0, mu^' '==0, mu^' '==-2)\nleg2 <- expression(sigma^2==0.2, sigma^2==1.0, sigma^2==5.0, sigma^2==0.5,)\nlegend(0.5, 1.0, lty=1:4, leg1, lwd=2, box.lty=0)\nlegend(3.0, 1.01, leg2, box.lty=0)\nylabpnorm <- expression(Phi[mu~sigma^2] (x))\nplot(xdens,pnorm(xdens,sd=sqrt(0.2)), type='l', ylim=c(0,1.0), xlab='',ylab=ylabpnorm,lty=1)\nlines(xdens,pnorm(xdens, sd=sqrt(1.0)), type='l', lty=2)\nlines(xdens,pnorm(xdens, sd=sqrt(5.0)), type='l', lty=3)\nlines(xdens,pnorm(xdens, mean=-2.0, sd=sqrt(0.5)), type='l', lty=4)\nleg1 <- expression(mu^' '==0, mu^' '==0, mu^' '==0, mu^' '==-2)\nleg2 <- expression(sigma^2==0.2, sigma^2==1.0, sigma^2==5.0, sigma^2==0.5,)\nlegend(0.5, 0.6, lty=1:4, leg1, lwd=2, box.lty=0)\nlegend(3.0, 0.61, leg2, box.lty=0)\n\n\n# Plot bottom panels with illustrative lognormal p.d.f. and c.d.f. \nxdens <- seq(0,3, 0.02)\nplot(xdens, dlnorm(xdens, meanlog=0, sdlog=5), type='l', ylim=c(0,2), xlab='', ylab='Lognormal density', lty=1)\nlines(xdens, dlnorm(xdens, meanlog=0, sdlog=1), type='l', lty=2)\nlines(xdens, dlnorm(xdens, meanlog=0, sdlog=1/2), type='l', lty=3)\nlines(xdens, dlnorm(xdens, meanlog=0, sdlog=1/8), type='l', lty=4)\nleg1 <- expression(sigma==5, sigma==1, sigma==1/2, sigma==1/8)\nlegend(1.8,1.8,lty=1:4,leg1,box.lty=0)\nplot(xdens,plnorm(xdens,meanlog=0,sdlog=5),type='l',ylim=c(0,1),xlab='x', ylab='Lognormal distribution',lty=1)\nlines(xdens,plnorm(xdens,meanlog=0,sdlog=1),type='l',lty=2)\nlines(xdens,plnorm(xdens,meanlog=0,sdlog=1/2),type='l',lty=3)\nlines(xdens,plnorm(xdens,meanlog=0,sdlog=1/8),type='l',lty=4)\nleg1 <- expression(sigma==5,sigma==1,sigma==1/2,sigma==1/8)\nlegend(1.5,0.6,lty=1:4,leg1,box.lty=0)\n\n# Turn off device driver (to flush output to png)\ndev.off()\n\n# Return plot to single-panel format\npar(mfrow=c(1,1))\n\n# Restore default clipping rect\npar(mar=c(5, 4, 4, 2) + 0.1)\n\n#‘mfcol, mfrow’ A vector of the form ‘c(nr, nc)’. Subsequent\n# figures will be drawn in an ‘nr’-by-‘nc’ array on the device\n# by _columns_ (‘mfcol’), or _rows_ (‘mfrow’), respectively.\n\n# In a layout with exactly two rows and columns the base value\n# of ‘\"cex\"’ is reduced by a factor of 0.83: if there are three\n# or more of either rows or columns, the reduction factor is\n# 0.66.\n\n# Setting a layout resets the base value of ‘cex’ and that of\n# ‘mex’ to ‘1’.\n\n# If either of these is queried it will give the current\n# layout, so querying cannot tell you the order in which the\n# array will be filled.\n\n\n\n", "meta": {"hexsha": "58a0a742890d88a15363e0fc77bc4540d4ba5fa0", "size": 4538, "ext": "r", "lang": "R", "max_stars_repo_path": "AstroSeminar2019Spring/ModernStatistics_R/chap0/chap2.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/chap0/chap2.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/chap0/chap2.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": 41.2545454545, "max_line_length": 111, "alphanum_fraction": 0.6416923755, "num_tokens": 1775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.9019206699387734, "lm_q1q2_score": 0.8171309503366769}} {"text": "##### Chapter 6: Regression Methods -------------------\n\n#### Part 1: Linear Regression -------------------\n\n## Understanding regression ----\n## Example: Space Shuttle Launch Data ----\nlaunch <- read.csv(\"challenger.csv\")\n\n# estimate beta manually\nb <- cov(launch$temperature, launch$distress_ct) / var(launch$temperature)\nb\n\n# estimate alpha manually\na <- mean(launch$distress_ct) - b * mean(launch$temperature)\na\n\n# calculate the correlation of launch data\nr <- cov(launch$temperature, launch$distress_ct) /\n (sd(launch$temperature) * sd(launch$distress_ct))\nr\ncor(launch$temperature, launch$distress_ct)\n\n# computing the slope using correlation\nr * (sd(launch$distress_ct) / sd(launch$temperature))\n\n# confirming the regression line using the lm function (not in text)\nmodel <- lm(distress_ct ~ temperature, data = launch)\nmodel\nsummary(model)\n\n# creating a simple multiple regression function\nreg <- function(y, x) {\n x <- as.matrix(x)\n x <- cbind(Intercept = 1, x)\n b <- solve(t(x) %*% x) %*% t(x) %*% y\n colnames(b) <- \"estimate\"\n print(b)\n}\n\n# examine the launch data\nstr(launch)\n\n# test regression model with simple linear regression\nreg(y = launch$distress_ct, x = launch[2])\n\n# use regression model with multiple regression\nreg(y = launch$distress_ct, x = launch[2:4])\n\n# confirming the multiple regression result using the lm function (not in text)\nmodel <- lm(distress_ct ~ temperature + field_check_pressure + flight_num, data = launch)\nmodel\n\n## Example: Predicting Medical Expenses ----\n## Step 2: Exploring and preparing the data ----\ninsurance <- read.csv(\"insurance.csv\", stringsAsFactors = TRUE)\nstr(insurance)\n\n# summarize the charges variable\nsummary(insurance$expenses)\n\n# histogram of insurance charges\nhist(insurance$expenses)\n\n# table of region\ntable(insurance$region)\n\n# exploring relationships among features: correlation matrix\ncor(insurance[c(\"age\", \"bmi\", \"children\", \"expenses\")])\n\n# visualing relationships among features: scatterplot matrix\npairs(insurance[c(\"age\", \"bmi\", \"children\", \"expenses\")])\n\n# more informative scatterplot matrix\nlibrary(psych)\npairs.panels(insurance[c(\"age\", \"bmi\", \"children\", \"expenses\")])\n\n## Step 3: Training a model on the data ----\nins_model <- lm(expenses ~ age + children + bmi + sex + smoker + region,\n data = insurance)\nins_model <- lm(expenses ~ ., data = insurance) # this is equivalent to above\n\n# see the estimated beta coefficients\nins_model\n\n## Step 4: Evaluating model performance ----\n# see more detail about the estimated beta coefficients\nsummary(ins_model)\n\n## Step 5: Improving model performance ----\n\n# add a higher-order \"age\" term\ninsurance$age2 <- insurance$age^2\n\n# add an indicator for BMI >= 30\ninsurance$bmi30 <- ifelse(insurance$bmi >= 30, 1, 0)\n\n# create final model\nins_model2 <- lm(expenses ~ age + age2 + children + bmi + sex +\n bmi30*smoker + region, data = insurance)\n\nsummary(ins_model2)\n\n# making predictions with the regression model\ninsurance$pred <- predict(ins_model2, insurance)\ncor(insurance$pred, insurance$expenses)\n\nplot(insurance$pred, insurance$expenses)\nabline(a = 0, b = 1, col = \"red\", lwd = 3, lty = 2)\n\npredict(ins_model2,\n data.frame(age = 30, age2 = 30^2, children = 2,\n bmi = 30, sex = \"male\", bmi30 = 1,\n smoker = \"no\", region = \"northeast\"))\n\npredict(ins_model2,\n data.frame(age = 30, age2 = 30^2, children = 2,\n bmi = 30, sex = \"female\", bmi30 = 1,\n smoker = \"no\", region = \"northeast\"))\n\npredict(ins_model2,\n data.frame(age = 30, age2 = 30^2, children = 0,\n bmi = 30, sex = \"female\", bmi30 = 1,\n smoker = \"no\", region = \"northeast\"))\n\n#### Part 2: Regression Trees and Model Trees -------------------\n\n## Understanding regression trees and model trees ----\n## Example: Calculating SDR ----\n# set up the data\ntee <- c(1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 6, 7, 7, 7, 7)\nat1 <- c(1, 1, 1, 2, 2, 3, 4, 5, 5)\nat2 <- c(6, 6, 7, 7, 7, 7)\nbt1 <- c(1, 1, 1, 2, 2, 3, 4)\nbt2 <- c(5, 5, 6, 6, 7, 7, 7, 7)\n\n# compute the SDR\nsdr_a <- sd(tee) - (length(at1) / length(tee) * sd(at1) + length(at2) / length(tee) * sd(at2))\nsdr_b <- sd(tee) - (length(bt1) / length(tee) * sd(bt1) + length(bt2) / length(tee) * sd(bt2))\n\n# compare the SDR for each split\nsdr_a\nsdr_b\n\n## Example: Estimating Wine Quality ----\n## Step 2: Exploring and preparing the data ----\nwine <- read.csv(\"whitewines.csv\")\n\n# examine the wine data\nstr(wine)\n\n# the distribution of quality ratings\nhist(wine$quality)\n\n# summary statistics of the wine data\nsummary(wine)\n\nwine_train <- wine[1:3750, ]\nwine_test <- wine[3751:4898, ]\n\n## Step 3: Training a model on the data ----\n# regression tree using rpart\nlibrary(rpart)\nm.rpart <- rpart(quality ~ ., data = wine_train)\n\n# get basic information about the tree\nm.rpart\n\n# get more detailed information about the tree\nsummary(m.rpart)\n\n# use the rpart.plot package to create a visualization\nlibrary(rpart.plot)\n\n# a basic decision tree diagram\nrpart.plot(m.rpart, digits = 3)\n\n# a few adjustments to the diagram\nrpart.plot(m.rpart, digits = 4, fallen.leaves = TRUE, type = 3, extra = 101)\n\n## Step 4: Evaluate model performance ----\n\n# generate predictions for the testing dataset\np.rpart <- predict(m.rpart, wine_test)\n\n# compare the distribution of predicted values vs. actual values\nsummary(p.rpart)\nsummary(wine_test$quality)\n\n# compare the correlation\ncor(p.rpart, wine_test$quality)\n\n# function to calculate the mean absolute error\nMAE <- function(actual, predicted) {\n mean(abs(actual - predicted)) \n}\n\n# mean absolute error between predicted and actual values\nMAE(p.rpart, wine_test$quality)\n\n# mean absolute error between actual values and mean value\nmean(wine_train$quality) # result = 5.87\nMAE(5.87, wine_test$quality)\n\n## Step 5: Improving model performance ----\n# train a Cubist Model Tree\nlibrary(Cubist)\nm.cubist <- cubist(x = wine_train[-12], y = wine_train$quality)\n\n# display basic information about the model tree\nm.cubist\n\n# display the tree itself\nsummary(m.cubist)\n\n# generate predictions for the model\np.cubist <- predict(m.cubist, wine_test)\n\n# summary statistics about the predictions\nsummary(p.cubist)\n\n# correlation between the predicted and true values\ncor(p.cubist, wine_test$quality)\n\n# mean absolute error of predicted and true values\n# (uses a custom function defined above)\nMAE(wine_test$quality, p.cubist)\n", "meta": {"hexsha": "1fc8c6b9fc4117407b3568e14075e1f22ca3b353", "size": 6430, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter06/MLwR_3rdEd_06.r", "max_stars_repo_name": "takeuchi-kou/Machine-Learning-with-R-Third-Edition", "max_stars_repo_head_hexsha": "c4e492b4bfed3d9240d645154001616a925ef773", "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": "Chapter06/MLwR_3rdEd_06.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": "Chapter06/MLwR_3rdEd_06.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": 28.3259911894, "max_line_length": 94, "alphanum_fraction": 0.6836702955, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.8171145373987324}} {"text": "\r\nybar = 178.2 # sample mean \r\nmu0 = 190 # hypothesized value \r\nsigma = 45.3 # population standard deviation \r\nn = 100 # sample size \r\nz = (ybar- mu0)/(sigma/sqrt(n))\r\nprint(z)\r\nk=abs(z)\r\n# test statistic\r\n # formula based on level of significance\r\np_value=2*(1-pnorm(k))\r\nprint(p_value)\r\n# mentioned p value in book is wrong\r\nalpha=0.01\r\nif(p_value>alpha){\r\n print(\"we fail to reject H0\")\r\n print(\" data do not support the research hypothesis(insufficient evidence).\")\r\n}else{\r\n print(\" there is very little evidence in the data to support the research hypothesis hence we will reject H0\")\r\n}\r\n", "meta": {"hexsha": "4e5f7eb095b00cd69a9add28b1d1936ddb149bc1", "size": 640, "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.14/Ex5_14.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.14/Ex5_14.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.14/Ex5_14.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": 30.4761904762, "max_line_length": 115, "alphanum_fraction": 0.6515625, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474246069458, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.8170360950541764}} {"text": "truemu <- -.5\ntruesd <- 200\n\nn <- 10\nM <- 10000\ngama <- .90\ncc <- qt(p = (1 + gama)/2, df = n-1)\n\ncomputa_D <- function(x) {\n n <- length(x)\n Delta.sq <- sum((x - mean(x))^2)\n sigma.prime <- sqrt(Delta.sq/(n-1)) \n d <- cc * sigma.prime/sqrt(n)\n return(d)\n}\n\nta_no_intervalo <- function(intervalo){\n (intervalo[1] <= truemu) * (truemu <= intervalo[2])\n}\n#######\n\ndata.sets <- matrix(rnorm(n = n*M, mean = truemu, sd = truesd),\n ncol = n, nrow = M)\n\n\nXbars <- apply(data.sets, 1, mean)\nDs <- apply(data.sets, 1, computa_D)\nAs <- Xbars - Ds\nBs <- Xbars + Ds \n\nIntervalos <- data.frame(lwr = As, upr = Bs)\nIntervalos$contem <- apply(Intervalos, 1, ta_no_intervalo)\n\nmean(Intervalos$contem) ## cobertura dos intervalos\n\n\n########### Figura\npraplotar <- data.frame(lwr = As, media = Xbars, upr = Bs,\n inclui = as.factor(Intervalos$contem), replicata = 1:M)\nlibrary(ggplot2)\n\np0 <- ggplot(data = praplotar, aes(x = replicata, y = media, colour = inclui)) +\n geom_point() +\n geom_errorbar(aes(ymin = lwr, ymax = upr)) +\n geom_hline(yintercept = truemu, linetype = \"longdash\", size = 1.5) +\n scale_y_continuous(expression(bar(X[n]) %+-% D), expand = c(0, 0)) +\n theme_bw(base_size = 16)\n\np0\n", "meta": {"hexsha": "dae3969be1cb1a73220252c27e333f2c6286735c", "size": 1238, "ext": "r", "lang": "R", "max_stars_repo_path": "code/IC_normal.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/IC_normal.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/IC_normal.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": 24.76, "max_line_length": 80, "alphanum_fraction": 0.5961227787, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263198, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8170360875806001}} {"text": "# Intervalos de confianza, error estándar y variance-covariance matrix.\n#################################################################\ncat(\"\\014\")\nrm(list=ls())\ngraphics.off()\n\n\n# Cargar paquete para cargar bases que no son de R.\n# install.packages(\"foreign\")\nlibrary(foreign) # significa \"foraneo\"\noptions(scipen = 1000000) # apagar notacion cientifica.\ndat = read.dta(\"https://github.com/hbahamonde/OLS/raw/master/Datasets/cow.dta\")\n\n# Estimar modelo lineal: relacion entre crecimiento economico y democracia, controlando por poblacion\nmodelo.1 = lm(rgdpch ~ democracy + pop, dat)\nsummary(modelo.1)\n\n# (1) Que significa \"controlando por\"?\n\n\n# Obtener intervalos de confianza\n## Estos valores representan la incertidumbre de nuestra estimacion al promedio de cada variable, \n## manteniendo las otras variables independientes \"constantes en sus medias\".\nconfint(modelo.1, level = 0.95) # 95% de confianza\nconfint(modelo.1, level = 0.99) # 99% de confianza\n\n# DIBUJAR EN EL PIZARRON LA REPRESENTACION DE QUE _SIGNIFICA_ \n# \"EL 95%\", Y DE POR QUE VEMOS LOS NUMEROS \"2.5%\" Y \"97.5%\"\n# EN NUESTRA TABLA DE \"CONFINT\".\n\n# Fijate que el intervalo de confianza de \"democracia\" va de ~1179 a ~2097\n## \"~\" significa \"aproximadamente\". Esos valores representan, nuevamente,\n## valores de nuestra \"y\" (es decir, \"crecimiento economico\", segun lo\n## estimamos en nuestro \"modelo.1\".)\n\n# Tambien podemos ver los coeficientes y su incertidumbre \n# en forma grafica tambien.\n\n# plotear CI\n# install.packages(\"coefplot\", \"ggplot2\")\nlibrary(coefplot, ggplot2)\ncoefplot(modelo.1)\n\n\n\n\n# (1) Compara los numeros de la tabla \"confint\" y lo que ves en el grafico.\n# (2) Que es lo que vemos en este grafico?\n# (3) Que podemos decir de los distintos coeficientes?\n# (4) Que podemos decir respecto al ancho de los intervalos de confianza?\n# (5) Que es mejor? Intervalos de confianza \"angostos\" o \"anchos\"?\n\n# Sin embargo, hay algunas veces que queremos observar como esta incertidumbre\n# varia a medida que recorremos la distribucion entera (no solo el promedio).\n## Atencion: \"coefplot\" y la tabla de coeficientes (\"summary(modelo.1)\") \n## solo muestra la incertidumbre respecto al PROMEDIO (\"el centro\") de la distribucion.\n## Lo que quiero decir, es que hay veces en que queremos ver como es que \n## la incertidumbre (es decir, los intervalos de confianza) VARIAN\n## segun nos movemos a lo LARGO de la distribucion, es decir, cuando\n## vemos mas que el solo PROMEDIO.\n\n### ESTE PUNTO ES IMPORTANTE, y ASEGURATE DE ENTENDERLO BIEN.\n\n# Veamos como se ve esta incertidumbre a lo LARGO de la distribucion.\n\n\n# install.packages(\"effects\")\nlibrary(effects)\nplot(allEffects(modelo.1))\n\n# (1) Que vemos en este grafico? \n# * DIBUJAR EN LA PIZARRA: CUANDO AVANZO UNA UNIDAD EN X, AVANZO 1179.9 EN DEMOCRACIA.\n# (2) Que notan respecto al grado de incertidumbre?\n\n# OK. Ya sabemos lo que los intervalos de confianza significan, y para que estan.\n# Ahora calculemos intervalos de confianza a mano, y veamos de donde vienen\n# estos numeros.\n\n\n########################################################\n# Como estimar manualmente los intervalos de confianza\n########################################################\n\n# Todo empieza estimando la Varianza del Error (sigma^2).\n\n# Primero, obtengamos el error\ne = as.vector(modelo.1$residuals)\ne # es simplemente un vector con todos los errores (diferencia entre observado\n# y predicho)\n\n# Segundo, veamos cuantos parametros estimamos. Sera importante para la formula.\nk = 3 # numero de variables a estimar (incluyendo intercepto).\n# Tenemos \"democracy\", \"pop\", \"Intercept\". Entonces, tenemos 3 parametros.\n\n# sigma.2 (varianza del error)\n# Varianza es una medida de la variabilidad o dispersion de un vector. En este caso, del vector \"e\", que es nuestro error. Matematicamente, es la suma de los elementos diagonales que resultan de la multiplicacion entre el vector del error y el vector del error traspuesto, dividido por la cantidad de observaciones menos el numero de parametros que estaremos estimando (3 en este ejemplo).\nsigma.2 = (1/(nrow(dat)-k))*sum(diag(e %*% t(e)))\n\n\n# Tercero, obtengamos la matriz \"x\". La matriz \"x\" representa lo que observamos.\n## Recuerda que para calcular el intercepto, debemos poner una columna de 1's del mismo largo que la dimension de el resto de las variables. \nunos = rep(1, nrow(dat)) # repetir \"1\" 112 veces, que es el largo de la base de datos\n# que lo acabo de calcular con \"nrow(dat)\".\n\n## OK, ahora creemos la matrix \"x\".\nx = matrix(c(unos, dat$democracy, dat$pop), ncol=3) \nx # Ve como quedo.\n\n\n# Cuarto, estimemos los errores estandard. \n# Es importante sacar los errores estandard porque necesitamos eso para calcular los intervalos de confianza.\n\n# Los errores estandard de hecho, salen en nuestra tabla de regresion.\n\nsummary(modelo.1) # \"Std. Error\"\n\n# Para calcular los errores estandard, usaremos una vieja tecnica de matrices.\n\n# Esta matriz es famosa, y se llama Matriz de Varianza-Covarianza.\n# Las varianzas aparecen en la diagonal, y las covarianzas fuera de la diagonal.\n\nlibrary(matlib) # paquete para hacer operaciones con matrices.\n\n# Calculemos la Matriz de Varianza-Covarianza\n# Multiplicar sigma^2 por (x'x)^-1\noptions(scipen=999)\nsigma.2 * inv(t(x) %*% x)\n\n# Pero habia un camino mas corto...\nvcov(modelo.1)\n\n# Recapitulemos, esta matriz de Varianzas y Covarianzas tiene elementos importantes para calcular el error estandard, que sera necesario para calcular el intervalo de confianza.\n\n# Lo interesante es que la raiz cuadrada de la diagonal, son los errores estandard.\nsqrt(diag(sigma.2 * inv(t(x) %*% x)))\n\n# Comprobemos. Los errores std. del \"summary\" debieran ser los mismos\n# que los que estimamos nosotros manualmente.\nsummary(modelo.1)\n\n# OK. Una manera de anotar esto, es extraer elemento por elemento de lo que acabamos de calcular. \nsqrt(diag(sigma.2 * inv(t(x) %*% x)))[1] # error std. del intercepto\nsqrt(diag(sigma.2 * inv(t(x) %*% x)))[2] # error std. de democracy\nsqrt(diag(sigma.2 * inv(t(x) %*% x)))[3] # error std. de pop.\n\n\n## Hablemos del error estandar\n### La manera en la que debemos entender el error estandard (SE) asociado al \n### coeficiente (lo que vemos en \"summary(modelo.1)\") es como un ESTIMATIVO de \n### la desviacion estandard de la POBLACION.\n\n### ATENCION: Poblacion es distinto a MUESTRA. Pensemos mas en esto...\n\n### Pensemos en esto por un segundo. La razon por la que ESTIMAMOS, MODELAMOS, y \n### tenemos INCERTIDUMBRE, es precisamente porque NO PODEMOS acceder a la poblacion.\n### Es decir, dado que es imposible tener TODOS LOS DATOS, nosotros trabajamos\n### con MUESTRAS. Un ejemplo de esto, es una encuesta para conocer preferencias \n### politicas. Dado que no podemos entrevistar a todo el pais (POBLACION), entrevistamos\n### a una MUESTRA, generalmente, aleatoria. \n\n### Entonces, el error estandard del coeficiente hace referencia a algo que no conocemos\n\n### En ese sentido, es precisamente la informacion que necesitamos para calcular los Intervalos de Confianza (nuestro tema de hoy).\n\n### Antes de seguir, definamos los \"grados de libertad\"\n### Se define como el numero de observaciones - 2.\ngrados.de.libertad = nrow(dat)-2\n\ngrados.de.libertad # ...veamos.\n\n### La manera en que calculamos el intervalo de confianza,\n### es la siguiente:\n\n### Formula del intervalo de confianza\n### coeficiente +/- t * SE del coeficiente.\n\n# Es un calculo \"doble\":\n### coeficiente + t * SE del coeficiente.\n### coeficiente - t * SE del coeficiente.\n\n\n### Hasta el momento, sabemos como derivar el coeficiente ( o \"beta\"). \n### Solo recuerda nuestros ej's en matrices:\n### beta = (x'x)^-1x'y\n\n### En la clase de hoy, aprendimos tambien a sacar el error estandard \n### y entendimos lo que significa.\n### Recuerda, el SE se saca asi:\n### sqrt(diag(sigma.2 * inv(t(x) %*% x)))\n### Es decir, la raiz cuadrada del los elementos diagonales de la\n### multiplicacion entre sigma^2 y x'x (que es el \"variance-covariance matrix\").\n\n### Para completar nuestra formula de los intervalos de confianza,\n### necesitamos un ultimo elemento, \"t\". \n### T es un valor critico que sacamos de una distribicion \n### llamada \"t\". \n\n\n#### Ocupemos una funcion para conseguir estos valores criticos.\nt = qt(1-.05/2, grados.de.libertad) # valores criticos de t, a un 95% de confianza.\n\n# \"1-.05\" porque queremos el 95% de la distribucion.\n# Piensa en \"la distribucion\" como al area bajo la curva\n# que representa \"confianza\". Es por eso que decimos \n# que \"estamos 95% seguros/confiados que nuestra estimacion\n# es cierta\"\n# Y es dividido por dos (\"/2\") porque queremos repartir esa\n# confianza a ambos lados de la distribucion.\n\n# \n10631.611789 - t * sqrt(diag(sigma.2 * inv(t(x) %*% x)))[1] # (Intercept) # 9136.09240230\n10631.611789 + t * sqrt(diag(sigma.2 * inv(t(x) %*% x)))[1] # (Intercept) # 12127.13117506\n\n#\n1638.874546 - t * sqrt(diag(sigma.2 * inv(t(x) %*% x)))[2] # democracy # 1179.996\n1638.874546 + t * sqrt(diag(sigma.2 * inv(t(x) %*% x)))[2] # democracy # 2097.753\n\n#\n0.002947 - t * sqrt(diag(sigma.2 * inv(t(x) %*% x)))[3] # pop \n0.002947 + t * sqrt(diag(sigma.2 * inv(t(x) %*% x)))[3] # pop \n\n\n# Pero nuevamente, siempre hay un camino mas corto.\nconfint(modelo.1, level = 0.95) # 95% de confianza\n\n# Discutir\n## (1) Por que 95 vs. 99? \n## (2) Logica frecuentista: limites del \"supuesto asintotico\". Es posible?", "meta": {"hexsha": "2e0d89f43560d87c3a0b31e851f57b2da0a1d7cd", "size": 9340, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Clase12/Clase12.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/Clase12/Clase12.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/Clase12/Clase12.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": 40.9649122807, "max_line_length": 389, "alphanum_fraction": 0.7129550321, "num_tokens": 2796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.8169776758711522}} {"text": "\n# ------------------------------------------Questão01----------------------------------------------------\n# 01) Utilize uma Distribuição Uniforme para criar uma base de dados aleatória. \n# A base deve ser composta por 50 elementos entre os valores 6 e 18. \n# Em seguida, calcule o que se pede.\n\ndatabase <- seq(from = 6, to = 18, by = 0.244)\nlength(database)\ndatabase\n\nmean(database) # Média\nvar(database) # Variância \nsd(database) # Desvio padrão \nmedian(database) # Mediana \nquantile(database) # Quartis \n100*sd(database)/mean(database) # Coeficiente de variação\n\n# ------------------------------------------Questão02--------------------------------------------------------------\n# 02) Realize o download da base de dados localizada no link http://archive.ics.uci.edu/ml/datasets/Wine+Quality. \n# Dois arquivos devem ser baixados, o que avalia a qualidade dos vinhos tintose outro sobre a qualidade dos vinhos \n# brancos (winequality-red.csve winequality-white.csvrespectivamente). Faça o que se pedepara ambas basesde dados.\n\nwine_red <- read.csv(\"../datasets/winequality-red.csv\", sep = \";\")\nwine_white <- read.csv(\"../datasets/winequality-white.csv\", sep = \";\")\n\nhead(wine_red, n = 10)\n\nhead(wine_white)\n\n# a) Obtenha os parâmetros estatísticos com a função summary.\n\nsummary(wine_red)\n\nsummary(wine_white)\n\n# b) Plote umgráfico de pontos dos parâmetros de qualidade por pH.\n\nplot(wine_red[,12],wine_red[,9],type=\"p\", main = \"Vinho vermelho\", xlab = \"Qualidade\", ylab = \"pH\", col=\"blue\")\n\nplot(wine_white[,12],wine_white[,9],type=\"p\", main = \"Vinho branco\", xlab = \"Qualidade\", ylab = \"pH\", col=\"green\")\n\n# c) Plote gráficos de barras para os parâmetros pH, qualidade e álcool.\n\nwine_red_aux <- data.frame(pH=wine_red[,9], qualidade=wine_red[,12], alcool=wine_red[,11])\nbarplot(colSums(wine_red_aux), main = \"Vinho vermelho\")\n\nwine_white_aux <- data.frame(pH=wine_white[,9], qualidade=wine_white[,12], alcool=wine_white[,11])\nbarplot(colSums(wine_white_aux), main = \"Vinho branco\")\n\n# d) Plote histogramas para os parâmetros açúcar residual e volatilidade ácida com 10 intervalos.\n\nhist(wine_red[,2], main = \"Vinho vermelho\", xlab = \"Volatilidade acida\")\n\nhist(wine_red[,4], main = \"Vinho vermelho\", xlab = \"Açúcar residual\")\n\nhist(wine_white[,2], main = \"Vinho branco\", xlab = \"Volatilidade acida\")\n\nhist(wine_white[,4], main = \"Vinho branco\", xlab = \"Açucar residual\")\n\nlibrary(\"ISwR\")\n\n# e) Calcule a correlação entre os parâmetros qualidade e pH;densidade e álcool;\n# açúcar residual e qualidade. Interprete cada resultado com um breve comentário.\n\nprint(\"Vinho vermelho --BEGIN--\")\n# qualidade e pH\ncor(wine_red[,12], wine_red[,9])\ncor.test(wine_red[,12], wine_red[,9])\n\n# densidade e álcool\ncor(wine_red[,8], wine_red[,11])\ncor.test(wine_red[,8], wine_red[,11])\n\n# açúcar residual e qualidade\ncor(wine_red[,4], wine_red[,12])\ncor.test(wine_red[,4], wine_red[,12])\n\nprint(\"Vinho vermelho --END--\")\n\nprint(\"Vinho branco --BEGIN--\")\n# qualidade e pH\ncor(wine_white[,12], wine_white[,9])\ncor.test(wine_white[,12], wine_white[,9])\n\n# densidade e álcool\ncor(wine_white[,8], wine_white[,11])\ncor.test(wine_white[,8], wine_white[,11])\n\n# açúcar residual e qualidade\ncor(wine_white[,4], wine_white[,12])\ncor.test(wine_white[,4], wine_white[,12])\n\nprint(\"Vinho branco --END--\")\n\n# ------------------------------------------Questão03--------------------------------------------------------------\n# 03)Implemente uma função em R que calcule a moda de vetoresde dados criados pelo usuário. Cada vetor deve conter 15 elementos, \n# contendo apenas números inteiros positivos e/ou negativos. Crie três vetores para simulação, sendo um amodal, \n# um modal e um bimodal para teste do seu programa.\n\n# Função que calcula a moda\ncalc_moda <- function(vec){\n if(length(vec) != 15){\n print(\"Vetor inválido! O vetor deve conter 15 elementos.\")\n return(FALSE)\n }\n \n if(typeof(vec[0]) == 'character'){\n print(\"Vetor inválido! O vetor deve conter apenas inteiros.\")\n return(FALSE) \n }\n\n z <- table(as.vector(vec))\n names(z)[z == max(z)]\n \n return(z)\n}\n\n# Vetores de exemplo\namodal<-c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)\nmodal<-c(1,1,3,4,5,6,7,8,9,10,11,12,13,14,15)\nbimodal<-c(1,1,3,3,5,6,7,8,9,10,11,12,13,14,15)\n\ncalc_moda(amodal)\ncalc_moda(modal)\ncalc_moda(bimodal)\n\n# ------------------------------------------Questão04--------------------------------------------------------------\n# A tabela a seguir apresenta a quantidade de itens vendidos em um restaurante por um período\n# de tempo. Devido às rasuras alguns dados estão faltantes. Importe os dados no formato XLSX\n# para o RStudio®. Calcule média, mediana, variância e desvio padrão da Variável Quantidade.\n# Obs.: ao criar a planilha no editor utilize apenas DUAS colunas para inserir os dados.\n\n# PS está em CSV pq nao consegui instalar a LIB de xls do R 3.4\n\ndf <- data.frame(read.csv(\"questao_04.csv\", sep = \";\"))\nhead(df)\nqtd <- na.omit(df[,2])\nqtd\n\nmean(qtd) # Média\nvar(qtd) # Variância \nsd(qtd) # Desvio padrão \nmedian(qtd) # Mediana\n\n# ------------------------------------------Questão05--------------------------------------------------------------\n# Calcule as probabilidades dos seguintes eventos. Para cada letra crie o espaço amostral e o\n# evento desejado.\n\n# a) Obter três caras no lançamento de 6 vezes de uma moeda justa.\n\nS1 <- tosscoin(6, makespace = TRUE)\nhead(S1)\nE1 <- subset(S1, isrep(S1, vals = \"H\", nrep = 3))\nhead(E1)\nProb(E1)\n\n# b) Obter quatro coroas no lançamento de 7 vezes de uma moeda com p_cara = 0.65 e\n# p_coroa= 0.35.\n\nS2 <- probspace(tosscoin(7),probs = c(0.65,0.35)) #cara 65% e coroa 35%\nhead(S2)\n\nE2 <- subset(S2, isrep(S2, vals = \"T\", nrep = 4))\nhead(E2)\nProb(E2)\n\n# c) Obter a soma do resultado do lançamento de 4 vezes de um dado com 8 faces maior que\n# 22.\nS3 <-rolldie(4, nsides = 8, makespace = TRUE)\nhead(S3)\n\nE3 <- subset(S3, X1+X2+X3+X4 > 22)\nhead(E3)\nProb(E3) #resultado\n\n# d) Considere uma urna com 04 bolas verdes, 06 bolas azuis, 02 bolas pretas e 03 bolas\n# vermelhas. Determine a probabilidade de se retirada a sequencia nesta ordem (preta,\n# azul, verde, vermelha e azul) após cinco retiradas sem reposição dessa urna\n\nBalls <- rep(c(\"verde\",\"azul\",\"preta\", \"vermelha\"),times = c(4,6,2,3))\nS4 <- urnsamples(Balls, size = 5, replace = FALSE, ordered = TRUE)\nE4 <- probspace(S4)\nR4 <- Prob(E4, isin(E4, c(\"preta\",\"azul\",\"verde\",\"vermelha\",\"azul\"), ordered =\nTRUE))\n\nR4\n\n# ------------------------------------------Questão06--------------------------------------------------------------\n# 06) Para a base de dados beaver1 presente no R faça o que se pede\n\nbeav <- beaver1\nhead(beav)\n\n# a) Plote um gráfico entre as variáveis tempo (eixo X) e temperatura (eixo Y).\n\nplot(beav[,2], beav[,3], type = \"b\", main = \"Beaver1\", xlab = \"Tempo\", ylab = \"Temperatura\", col=c(\"red\", \"blue\"))\n\n# b) Faça uma regressão linear considerando Y=f(X)\n\ntime<-beav[,2]\ntemp<-beav[,3]\nx1<-time\ny1<-temp\n\nbeav.lm <- lm(y1 ~ x1, data=beav)\ncoef1<- coef(beav.lm)\ncoef1\nplot(x1,y1,type=\"p\",xlab = \"Tempo\", ylab = \"Temperatura\", col=c(\"red\", \"blue\"))\nabline(coef1)\n\n# c) Com base na regressão preveja o valor da temperatura para o tempo 960 e 1680.\n\n# d) Calcule o vetor de predições\n\nprev1<- fitted(beav.lm)\nhead(prev1, 10)\n\n# e) Calcule o vetor de resíduos\n\nres1 <- residuals(beav.lm)\nhead(res1, 10)\n\n# f) Intervalo de confiança para os níveis de 95% e 70%.\nconf1 <- confint(beav.lm, level = 0.95) #intervalo de confiança de 95%\nconf2 <- confint(beav.lm, level = 0.70) #intervalo de confiança de 70%\n\nconf1 # 95\nconf2 # 70\n\n# g) Utilizando a função ci.plot() plote os gráficos dos intervalos junto com os dados.\n\nplot(beav.lm, conf.level = 0.70)\n\nplot(beav.lm, conf.level = 0.95)\n", "meta": {"hexsha": "9057a9d7a70ac504d6852910ab661fec4f399510", "size": 7678, "ext": "r", "lang": "R", "max_stars_repo_path": "notebooks/basic-experiments.r", "max_stars_repo_name": "macio-matheus/r-language-basic-experiments", "max_stars_repo_head_hexsha": "111c5fc6b5a627738b45016bec162af58e11dd0c", "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/basic-experiments.r", "max_issues_repo_name": "macio-matheus/r-language-basic-experiments", "max_issues_repo_head_hexsha": "111c5fc6b5a627738b45016bec162af58e11dd0c", "max_issues_repo_licenses": ["MIT"], "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/basic-experiments.r", "max_forks_repo_name": "macio-matheus/r-language-basic-experiments", "max_forks_repo_head_hexsha": "111c5fc6b5a627738b45016bec162af58e11dd0c", "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.6723404255, "max_line_length": 129, "alphanum_fraction": 0.6491273769, "num_tokens": 2414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.8169288308222995}} {"text": "### 線形回帰分析(単回帰)の例\n### - Brain and Body Weights for 28 Species\n\n## パッケージの読み込み\nrequire(MASS) \nrequire(tidyverse) \nrequire(ggfortify)\n\n## データの読み込み (\"MASS::Animals\"を用いる)\ndata(Animals)\n\n## データの内容を確認\nhelp(Animals) # 内容の詳細を表示 \nprint(Animals) # データの表示\n\n## データのプロット (normal plot)\nggplot(Animals, aes(body, brain, label=rownames(Animals))) +\n geom_point(colour=\"royalblue\") + \n labs(title=\"Brain and Body Weights (normal plot)\",\n x=\"body [kg]\", y=\"brain [g]\") \n\nggplot(Animals, aes(body, brain)) +\n scale_x_log10() + scale_y_log10() +\n geom_point(colour=\"royalblue\") +\n labs(title=\"Brain and Body Weights (log-log plot)\",\n x=\"body [kg]\", y=\"brain [g]\")\n\n## 回帰分析 (単回帰)\nmodel <- lm(log(brain) ~ log(body), data=Animals)\nsummary(model) # 分析結果のまとめを表示\n\n## 区間推定\nyc <- exp(predict(model, newdata=Animals, interval=\"confidence\"))\ncolnames(yc) <- paste(\"c\",colnames(yc),sep=\".\")\nyp <- exp(predict(model, newdata=Animals, interval=\"prediction\"))\ncolnames(yp) <- paste(\"p\",colnames(yp),sep=\".\")\nmydat <- cbind(Animals, yc, yp)\n\n## 回帰式および信頼区間・予測区間の表示\nggplot(mydat, aes(body, brain, label=rownames(mydat))) +\n scale_x_log10() + scale_y_log10() + # log-log plot\n geom_line(aes(y=c.fit), color=\"dodgerblue\", lwd=1.2) +\n geom_ribbon(aes(ymin=c.lwr,ymax=c.upr), fill=\"blue\", alpha=0.2)+\n geom_ribbon(aes(ymin=p.lwr,ymax=p.upr), fill=\"blue\", alpha=0.1)+\n geom_text(size=3) + \n labs(title=\"Brain and Body Weights\", x=\"body [kg]\", y=\"brain [g]\")\n\n## 診断プロット\nautoplot(model, colour=\"royalblue\",\n smooth.colour=\"gray50\", smooth.linetype=\"dashed\",\n ad.colour=\"blue\",\n label.size=3, label.n=5, label.colour=\"red\")\n\n## 外れ値を除いた回帰分析\nidx <- c(6,16,26) # 外れ値のindex\nmodel <- lm(log(brain) ~ log(body), data=Animals, subset=-idx)\nsummary(model)\n\n## 区間推定\nyc <- exp(predict(model, newdata=Animals, interval=\"confidence\"))\ncolnames(yc) <- paste(\"c\",colnames(yc),sep=\".\")\nyp <- exp(predict(model, newdata=Animals, interval=\"prediction\"))\ncolnames(yp) <- paste(\"p\",colnames(yp),sep=\".\")\nmydat <- cbind(Animals, yc, yp)\n\n## 回帰式および信頼区間・予測区間の表示\nggplot(mydat, aes(body, brain, label=rownames(mydat))) +\n scale_x_log10() + scale_y_log10() +\n geom_line(aes(y=c.fit), color=\"royalblue\", lwd=1.2) +\n geom_ribbon(aes(ymin=c.lwr,ymax=c.upr), fill=\"blue\", alpha=0.2)+\n geom_ribbon(aes(ymin=p.lwr,ymax=p.upr), fill=\"blue\", alpha=0.1)+\n geom_text(size=3) + \n labs(title=\"Brain and Body Weights\", x=\"body [kg]\", y=\"brain [g]\")\n\n## 診断プロット\nautoplot(model, colour=\"royalblue\",\n smooth.colour=\"gray50\", smooth.linetype=\"dashed\",\n ad.colour=\"blue\",\n label.size=3, label.n=5, label.colour=\"red\")\n", "meta": {"hexsha": "798a729ff85662c0623da800a1f6d40cac848d87", "size": 2645, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/code/r-brainbody.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/r-brainbody.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/r-brainbody.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": 33.0625, "max_line_length": 70, "alphanum_fraction": 0.6517958412, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286378, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.8167812588851793}} {"text": "# See\n# http://what-when-how.com/artificial-intelligence/a-comparison-of-cooling-schedules-for-simulated-annealing-artificial-intelligence/\n\nexp_cool <- function(i, ntot, a, b) {\n (1-b)*exp(-a*i/ntot)+b\n}\n\npow_cool <- function(i, ntot, a, b) {\n (1-b)*(a^(i/ntot))+b\n}\n\nlin_cool <- function(i, ntot, a, b) {\n (1-b)*(1/(1+a*i))+b\n}\n\nquad_cool <- function(i, ntot, a, b) {\n (1-b)*(1/(1+a*(i^2)))+b\n}\n\nlog_cool <- function(i, ntot, a, b) {\n (1-b)*(1/(1+a*log(1+i)))+b\n}\n\nntot <- 10000\nx <- seq(0, ntot, by=1)\n\n# plot(\n# x,\n# pow_cool(x, ntot, 0.001, 0),\n# type=\"l\"\n# )\n\nplot(\n x,\n exp_cool(x, ntot, 3, 0),\n type=\"l\"\n)\n\nlines(\n x,\n pow_cool(x, ntot, 1e-10, 0),\n col=\"red\"\n)\n\nlines(\n x,\n lin_cool(x, ntot, 0.01, 0.01),\n col=\"green\"\n)\n\nlines(\n x,\n quad_cool(x, ntot, 0.0000002, 0.05),\n col=\"blue\"\n)\n\nlines(\n x,\n log_cool(x, ntot, 3, 0),\n col=\"purple\"\n)\n\n# plot(\n# x,\n# 0.2*cos(100*x*pi/ntot)+0.3,\n# type=\"l\",\n# ylim=c(0, 1)\n# )\n# \nplot(\n x,\n ((exp(-5*x/ntot)+0.05*cos(100*x*pi/ntot))+0.05)/1.1,\n type=\"l\"\n)\n# \n# plot(\n# seq(-1, 1, by=0.01),\n# seq(-1, 1, by=0.01)^2,\n# type=\"l\"\n# )\n\n# 1) Lift the map\n# 2) Lift-decay the map\n# 3) Discussion: adaptive\n# 4) Discussion: partial (parts) of metric\n# 5) Discussion: scale with data and parameters\n", "meta": {"hexsha": "18f7050eda35a33beae696d49699362ab13ad6ed", "size": 1277, "ext": "r", "lang": "R", "max_stars_repo_path": "doc/schedules.r", "max_stars_repo_name": "scidom/PGUManifoldMC.jl", "max_stars_repo_head_hexsha": "766cf983b122678d47524c566ebd6fffa7f804d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-08T12:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-08T12:59:00.000Z", "max_issues_repo_path": "doc/schedules.r", "max_issues_repo_name": "eford/PGUManifoldMC.jl", "max_issues_repo_head_hexsha": "0a75d899f580a79282eb742f17a207b14963ea79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-04-13T03:04:56.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-13T03:05:48.000Z", "max_forks_repo_path": "doc/schedules.r", "max_forks_repo_name": "eford/PGUManifoldMC.jl", "max_forks_repo_head_hexsha": "0a75d899f580a79282eb742f17a207b14963ea79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-21T18:03:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-21T18:03:01.000Z", "avg_line_length": 14.6781609195, "max_line_length": 133, "alphanum_fraction": 0.5489428348, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.8163963355065684}} {"text": "set.seed(102)\n\n\n#Saving plots\npdf(file = \"task3.pdf\")\n\n#prior sd is 4 prior\n#hyperparameters h_mean=0 h_sd=2\nh_mean = 4\nh_sd = 2\n \n\npar(mfrow=c(3,3),xpd=FALSE)\nN=1;\nx=rnorm(n=N,m=7,sd=4)\n#finding observed values\n\tx<-rnorm(n=N,m=7,sd=4) #creation of observed data\n\tsampleMean=mean(x);\t\n\n\tx1 <- seq(-30, 30, 0.1)\n\n\t#Finding posterior\t\n\tposterior_mean = (N*(h_sd^2)*sampleMean + 16*0 ) / ( N*(h_sd^2) + 16)\n\tposterior_var = (h_sd^2*16) / N*( h_sd^2 + 16 ) \n\tpost.norm<-rnorm(n=N,m=posterior_mean,sd=sqrt(posterior_var)) #creation of observed data\n\n\n\n\t#finding posterior, observed, prior\n\tplot(x1, dnorm(x1, 0, 2), type = \"l\",xlim=c(-20, 20), xlab=N,col=\"blue\")\n\tlines(x1,dnorm(x1, posterior_mean, sqrt(posterior_var)),col=\"gold\")\n\tlines(x,dnorm(x1, x, sqrt(0)),col=\"red\")\n\n\tlegend(\"topleft\", \n inset=.05, \n cex = 1, \n c(\"data\",\"post\",\"prior\"), \n horiz=FALSE, \n lty=c(1,1), \n lwd=c(2,2), \n col=c(\"red\",\"gold\",\"blue\"), \n box.lty=0)\n\n\n\nfor (N in c(5,10,20,50,100,1000)){\n\tprint(paste(\"The number of observed values is\", N))\n\t\n\t#finding observed values\n\tx<-rnorm(n=N,m=7,sd=4) #creation of observed data\n\tsampleMean=mean(x);\t\n\n\tx1 <- seq(-30, 30, 0.1)\n\n\t#Finding posterior\t\n\tposterior_mean = (N*(h_sd^2)*sampleMean + 16*0 ) / ( N*(h_sd^2) + 16)\n\tposterior_var = (h_sd^2*16) / N*( h_sd^2 + 16 ) \n\tpost.norm<-rnorm(n=N,m=posterior_mean,sd=sqrt(posterior_var)) #creation of observed data\n\n\n\n\t#finding posterior, observed, prior\n\tplot(x1, dnorm(x1, 0, 2), type = \"l\",xlim=c(-20, 20), xlab=N,col=\"blue\",ylim=c(0, 0.35))\n\tlines(x1,dnorm(x1, posterior_mean, sqrt(posterior_var)),col=\"darkgoldenrod1\")\n\tlines(density(x),col=\"red\")\n\n\t\n legend(\"topleft\", \n inset=.05, \n cex = 1, \n c(\"data\",\"post\",\"prior\"), \n horiz=FALSE, \n lty=c(1,1), \n lwd=c(2,2), \n col=c(\"red\",\"gold\",\"blue\"), \n box.lty=0)\n}\n\ndev.off()\n\n#Παρατηρήσεις: Η εκ των προτέρων (prior) κατανομή(με εξαιρεση Ν=1) παραμένει σταθερή,\n#η κατανομή των παρατηρήσεων παραμένει σχεδόν σταθερή με αβεβαιότητα\n#λόγω της μικρής κορυφής και η posterior, όσο αυξάνονται τα δείγματα\n# μικραίνει η διακύμανση και αποκτά μεγάλη κορυφή. Λογικό, όπως\n#αναφέρεται στη βιβλιογραφία όσο το Ν αυξάνεται η αβεβαιότητα στη posterior\n# μειώνεται αφού μειώνεται η επίδραση της σ.\n\n", "meta": {"hexsha": "69a33c3ac7f7b85527165633ed9ba8fcea0b4b9e", "size": 2305, "ext": "r", "lang": "R", "max_stars_repo_path": "MachineLearning/Project1/task3.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/Project1/task3.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/Project1/task3.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": 26.1931818182, "max_line_length": 89, "alphanum_fraction": 0.6368763557, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8158615317580088}} {"text": "# linear regression model : y= 0.15085 - 0.00288x1 - 0.00759x2 + 0.26528x3\r\nSStotal=3.328\r\nSSresidual=0.674\r\nn=21\r\nR2=(SStotal-SSresidual)/SStotal\r\nprint(R2)\r\n\r\n#test statistic\r\nF=(R2/3)/((1-R2)/(n-4))\r\nprint(F)\r\nalpha=0.05\r\nfvalue=qf(1-alpha,df1=3,df2 = 17)\r\nprint(fvalue)\r\n# Because the computed F statistic, , is greater than fvalue, we reject H0 and\r\n#conclude that one or more of the x values has some predictive power\r\n", "meta": {"hexsha": "b13daaf3435f6d5e2a0f3f6f4766b1b38130b1ab", "size": 425, "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.12/Ex12_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/CH12/EX12.12/Ex12_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/CH12/EX12.12/Ex12_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": 26.5625, "max_line_length": 79, "alphanum_fraction": 0.7011764706, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104914476339, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.8155490845841565}} {"text": "\nfilesSize<-read.table(\"xn.txt\", header = T)\nmydata = filesSize$Byte\ncat(\"Nombre de fichier:\",nrow(filesSize))\n\nh = hist(log(mydata), breaks = 15, probability= TRUE, xlab = \"log(file size)\",\n main=\"Histogramme de la taille des fichiers en échelle logarithmique\")\n\nx <- seq(min(log(mydata)), max(log(mydata)), length = 100)\ny <- dnorm( x, mean = mean(log(mydata)), sd = sd(log(mydata)))\nlines(x, y, col = \"blue\", lwd = 2)\n\n400/399 * sd(log(mydata))^2 - sd(log(mydata))^2\n\nh = hist(log(mydata), breaks = 50, probability= TRUE,\n main=\"Histogramme de la taille des fichiers en échelle logarithmique\")\n\nlog_x <- seq(-2, max(log(mydata)), length = 1000)\ny_normal <- dnorm( log_x, mean = mean(log(mydata)), sd = sd(log(mydata)))\nlines(log_x, y_normal, col = \"blue\", lwd = 2)\n\ndensité_lnorm <- function(x, mean, sd){\n return (1.0/(x*sqrt(2*pi*sd^2)) * exp(-(log(x)-mean)^2/(2*sd^2)))\n}\n\n\n#yfit_2 <- densité_lnorm(exp(xfit_2), mean(log(x)), sd(log(x)))\ny_dlnorme <- dlnorm(exp(log_x), meanlog = mean(log(mydata)), sdlog = sd(log(mydata)))\n\n\npar(new = TRUE)\nplot(log_x, y_dlnorme, type = \"l\", axes = FALSE, bty = \"n\", xlab = \"\", ylab = \"\", col='red')\naxis(4, ylim=c(0,max(y_dlnorme)), col=\"red\",col.axis=\"red\")\n\n## Add Legend\nlegend(\"topright\",legend=c(\"Densité de ln(x) suivant lois normal\",\"Densité de X suivant loi log-Nromal\"),\n text.col=c(\"black\",\"red\"),pch=c(16,15),col=c(\"black\",\"red\"))\n\nmedian(mydata)\n\nexp(mean(log(mydata)))\n\nqlnorm(p=0.95, mean=mean(log(mydata)),sd=sd(log(mydata)))\n\nexp(sqrt(399/400)*sd(log(mydata))*qnorm(p=0.95, mean=0, sd=1)+mean(log(mydata)))\n\nmean(log(mydata))\n\nprint(0.1+400/2)\n\nmu = mean(log(mydata))\n0.1 + 0.5 * sum((log(mydata) - mu)^2)\n\nmargin = seq(0,1,length=5000) \napriori = dgamma(margin, shape=0.1, scale=10) \n\nplot(x=margin,y=apriori,col=\"red\",type=\"l\",ylim=c(0,40),main=\"Densité de loi\",xlab=\"Valeur\",ylab=\"Densité\")\n\nposteriori = dgamma(margin, shape=200.1, scale=1/1708.3) \nlines(x=margin,y=posteriori,col=\"orange\",type=\"l\")\n\nabline(v=200.1/1708.3, col=\"green\", lwd = \"4\")\nabline(v=400/399/var(log(mydata)), col=\"blue\", lwd = \"2\", lty = 2)\n\n\nlegend(\"topright\",legend=c(\"Densité à priori\",\"Densité à posteriori\",\"Espérance à posteriori\",\"Espérance MV\"),col=c(\"red\",\"orange\",\"green\",\"blue\"),lty=c(1,1,1,2), cex=0.8)\n\n\nL = 8 * qchisq(p=0.95, df = 399)\nAccepte = sd(log(mydata))^2*400 <= L\nAccepte\n\nseuil = sqrt(sd(log(mydata))^2 * 400 / qchisq(p=0.95,df = 399))\nseuil\n", "meta": {"hexsha": "f3d4cbb1a83f743982814d548c0c056e4ea25f2e", "size": 2417, "ext": "r", "lang": "R", "max_stars_repo_path": "MDI202-statistiques/Mini_Projet/Fangda.ZHU/Mini-Projet.r", "max_stars_repo_name": "zhufangda/Telecom-Paristech", "max_stars_repo_head_hexsha": "13772c3b3db59598b68de0ade0170d5986491c42", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-06-20T11:06:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-28T15:09:34.000Z", "max_issues_repo_path": "MDI202-statistiques/Mini_Projet/Fangda.ZHU/Mini-Projet.r", "max_issues_repo_name": "zhufangda/Telecom-Paristech", "max_issues_repo_head_hexsha": "13772c3b3db59598b68de0ade0170d5986491c42", "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": "MDI202-statistiques/Mini_Projet/Fangda.ZHU/Mini-Projet.r", "max_forks_repo_name": "zhufangda/Telecom-Paristech", "max_forks_repo_head_hexsha": "13772c3b3db59598b68de0ade0170d5986491c42", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-05-10T13:24:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-10T14:15:07.000Z", "avg_line_length": 32.2266666667, "max_line_length": 171, "alphanum_fraction": 0.6487381051, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650672, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.8151856056080355}} {"text": "rm(list = ls()) #cleaning up\nlibrary(tidyverse)\n\ndf5=data.frame()\nfor (i in 1:10000){\n df5<-rbind(df5,rexp(5,2))\n}\ndf5$mean<-rowMeans(df5,na.rm=TRUE,dims=1)\n\nggplot(df5, aes(mean))+\n geom_histogram(data=df5, aes(mean, ..density..), binwidth = 0.01)\n\nmean(df5$mean)\n\n##############1###################\ndf1=data.frame()\nfor (i in 1:10000){\n df1<-rbind(df1,rexp(1,2))\n}\ndf1$mean<-rowMeans(df1,na.rm=TRUE,dims=1)\n\nggplot(df1, aes(mean))+\n geom_histogram(data=df1, aes(mean, ..density..), binwidth = 0.01)\n\nmean(df1$mean)\n\n##############10###################\ndf10=data.frame()\nfor (i in 1:10000){\n df10<-rbind(df10,rexp(10,2))\n}\ndf10$mean<-rowMeans(df10,na.rm=TRUE,dims=1)\n\nggplot(df10, aes(mean))+\n geom_histogram(data=df10, aes(mean, ..density..), binwidth = 0.01)\n\nmean(df10$mean)\n\n##############30###################\ndf30=data.frame()\nfor (i in 1:10000){\n df30<-rbind(df30,rexp(30,2))\n}\ndf30$mean<-rowMeans(df30,na.rm=TRUE,dims=1)\n\nggplot(df30, aes(mean))+\n geom_histogram(data=df30, aes(mean, ..density..), binwidth = 0.01)\n\nmean(df30$mean)\n\n##### same graph #####\ndf = data.frame(\"X1\" = df1$mean,\n \"X5\" = df5$mean,\n \"X10\" = df10$mean,\n \"X30\" = df30$mean)\nmean(df1$mean)\nmean(df5$mean)\nmean(df10$mean)\nmean(df30$mean)\n\nggplot(df)+\n geom_histogram(data=df1, aes(mean, ..density..), color=\"red\", binwidth = 0.01)+\n geom_histogram(data=df5, aes(mean, ..density..), color=\"orange\", binwidth = 0.01)+\n geom_histogram(data=df10, aes(mean, ..density..), color=\"yellow\", binwidth = 0.01)+\n geom_histogram(data=df30, aes(mean, ..density..), color=\"green\", binwidth = 0.01)\n\n\n##### Comparing the ratio of how decrease the starndard error ###\nsd(df30$mean)\nsd(df5$mean)/sqrt(6)\n", "meta": {"hexsha": "376bbfa681fa6285e4dc75a055eb0d15dab0ebe0", "size": 1726, "ext": "r", "lang": "R", "max_stars_repo_path": "exam.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": "exam.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": "exam.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": 24.3098591549, "max_line_length": 85, "alphanum_fraction": 0.607184241, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.8146571809561558}} {"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## B = Bloomberg Barclays Aggregate Bond index ETF (AGG), from Yahoo Finance\nexpret.bonds <- 0.0269\nvol.bonds <- 0.0292\n## E = S&P 500 index ETF (SPY), from Yahoo Finance\nvol.stocks <- 0.1027\nexpret.stocks <- 0.1076\nrf <- 0.01 ## F = risk-free rate (approximately)\n\nwt.bonds <- seq(-0.5,1.5,0.005) ## explore bond weights: short 50% to long 150%\n## create expected portfolio returns for weights\nexpret.port <- wt.bonds*expret.bonds + (1-wt.bonds)*expret.stocks\n\n## plot and set up axes\nplot.default(NULL, type='l', xlim=c(0,0.15), ylim=c(-0.01, 0.15))\nabline(h=0, lty=2, col=\"gray80\")\nlines(c(0,0), c(0.08,-0.025), lty=2, col=\"gray80\")\n\n## iterate through correlations from 1 to -1 in steps of -0.25\n## find the portfolio volatility and then plot the curve\n## RAINBOW-y for visibility and fabulous pride\nline.colors <- c(\"purple\",\"magenta\", \"red\", \"orange\", \"yellow\",\n \"chartreuse\", \"aquamarine\", \"cyan\", \"blue\")\ncorrs.bonds.stocks <- seq(1, -1, -0.25)\nlegend.keys <- c()\nfor (i in 1:length(corrs.bonds.stocks)) {\n corr.bs <- corrs.bonds.stocks[i]\n var.port.tmp <- wt.bonds^2*vol.bonds^2 + (1-wt.bonds)^2*vol.stocks^2 +\n 2*wt.bonds*(1-wt.bonds)*corr.bs*vol.bonds*vol.stocks\n vol.port.tmp <- sqrt(var.port.tmp)\n lines(vol.port.tmp, expret.port, lty=i, lwd=2, col=line.colors[i])\n legend.keys <- c(legend.keys, bquote(rho==~.(corr.bs)))\n}\n## Add a legend so we know which curves are for which correlations\nlegend.text <- as.expression(legend.keys)\nlegend(\"topleft\", legend.text, lty=1:length(legend.text), cex=0.8, lwd=2, col=line.colors)\n\n## show where F, B, and E are\npoints(0,0.01,lwd=2)\ntext(0.005, 0.01, \"F\")\npoints(vol.bonds, expret.bonds,lwd=2)\ntext(vol.bonds+0.005, expret.bonds, \"B\")\npoints(vol.stocks, expret.stocks,lwd=2)\ntext(vol.stocks, expret.stocks-0.01, \"E\")\n", "meta": {"hexsha": "7ba04706229ae15d51b761f708e598c6da473859", "size": 2111, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch9-two-risky-assets.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-two-risky-assets.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-two-risky-assets.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": 41.3921568627, "max_line_length": 90, "alphanum_fraction": 0.6792989105, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.8143101227594576}} {"text": "library(ISLR)\nnames(Smarket)\ndim(Smarket)\n\ncor(Smarket[,-9])\n\nplot(Smarket$Volume)\n\nglm.fit=glm(Direction ~ Lag1+Lag2+Lag3+Lag4+Lag5+Volume, data=Smarket, family=binomial)\nsummary(glm.fit)\n\nglm.probs=predict(glm.fit,type=\"response\")\nglm.pred=rep(\"Down\",1250)\nglm.pred[glm.probs >.5]=\"Up\"\ntable(glm.pred,Smarket$Direction)\n#in training error rate\nmean(glm.pred==Smarket$Direction )\n\ntrain=(Smarket$Year <2005)\nSmarket.2005 = Smarket[!train ,]\ndim(Smarket.2005)\nDirection.2005= Smarket$Direction[!train]\n\nglm.fit=glm(Direction~Lag1+Lag2+Lag3+Lag4+Lag5+Volume, data=Smarket, family=binomial, subset=train)\nglm.probs=predict(glm.fit,Smarket.2005,type=\"response\")\n\nglm.pred=rep(\"Down\",252)\nglm.pred[glm.probs >.5]=\"Up\"\ntable(glm.pred,Direction.2005)\n\nmean(glm.pred==Direction.2005)\n\n\nlibrary(MASS)\nlda.fit=lda(Direction~Lag1+Lag2,data=Smarket ,subset=train)\nlda.fit\nplot(lda.fit)\n\nlda.pred=predict(lda.fit , Smarket.2005)\nlda.class=lda.pred$class\ntable(lda.class, Direction.2005)\n\nqda.fit=qda(Direction ~ Lag1+Lag2,data=Smarket ,subset=train)\nqda.fit\nqda.class=predict(qda.fit,Smarket.2005)$class\ntable(qda.class, Direction.2005)\nmean(qda.class==Direction.2005)\n\nlibrary(class)\ntrain.X=cbind(Smarket$Lag1, Smarket$Lag2)[train ,]\ntest.X=cbind(Smarket$Lag1,Smarket$Lag2)[!train ,]\ntrain.Direction = Smarket$Direction [train]\n\nset.seed(1)\nknn.pred=knn(train.X,test.X,train.Direction, k=1)\ntable(knn.pred,Direction.2005)\n\nknn.pred=knn(train.X,test.X,train.Direction, k=3)\ntable(knn.pred,Direction.2005)\n\ndim(Caravan)\nstandardized.X=scale(Caravan [,-86])\nvar(Caravan [,1])\nvar(standardized.X[,1])\ntest=1:1000\ntrain.X=standardized.X[-test ,]\ntest.X=standardized.X[test ,]\ntrain.Y=Caravan$Purchase [-test]\ntest.Y=Caravan$Purchase [test]\nset.seed(1)\nknn.pred=knn(train.X,test.X,train.Y,k=1)\nmean(test.Y!=knn.pred)\nmean(test.Y!=\"No\")\n\ntable(knn.pred,test.Y)\n\n\nglm.fit=glm(Purchase~.,data=Caravan ,family=binomial, subset=-test)\nglm.probs=predict(glm.fit,Caravan[test ,],type=\"response\")\nglm.pred=rep(\"No\",1000)\nglm.pred[glm.probs >.5]=\"Yes\"\ntable(glm.pred,test.Y)\n\nglm.pred=rep(\"No\",1000)\nglm.pred[glm.probs >.25]=\"Yes\"\ntable(glm.pred,test.Y)\n", "meta": {"hexsha": "483d4c894cf79e790e70200b26a5c4f1f2e52785", "size": 2129, "ext": "r", "lang": "R", "max_stars_repo_path": "books/AnIntroductiontoStatisticalLearning/chapter04.lab.r", "max_stars_repo_name": "xunilrj/sandbox", "max_stars_repo_head_hexsha": "f92c12f83433cac01a885585e41c02bb5826a01f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "books/AnIntroductiontoStatisticalLearning/chapter04.lab.r", "max_issues_repo_name": "xunilrj/sandbox", "max_issues_repo_head_hexsha": "f92c12f83433cac01a885585e41c02bb5826a01f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "books/AnIntroductiontoStatisticalLearning/chapter04.lab.r", "max_forks_repo_name": "xunilrj/sandbox", "max_forks_repo_head_hexsha": "f92c12f83433cac01a885585e41c02bb5826a01f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 24.4712643678, "max_line_length": 99, "alphanum_fraction": 0.7435415688, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8918110461567923, "lm_q1q2_score": 0.8137206510732079}} {"text": "library(plotly)\nlibrary(htmlwidgets)\n\ngaussPdf <- function (x, mu, E) {\n k <- length(x)\n ans <- exp(-0.5 * t(x - mu) %*% solve(E) %*% (x - mu)) /\n sqrt((2 * pi) ^ k * det(E))\n return (ans)\n}\n\n\ndrawPlot <- function () {\n mu = c(0, 0)\n # E <- matrix(c(1, 3/5, 3/5, 2), nrow = 2)\n # E <- matrix(c(0.5, 0, 0, 2), nrow = 2)\n E <- matrix(c(2, 0.9, 0.9, 2), nrow = 2)\n \n xs <- seq(from = -5, to = 5, by = 0.1)\n ys <- seq(from = -5, to = 5, by = 0.1)\n z <- c()\n \n for (y in ys) {\n curr <- c()\n for (x in xs) {\n arg <- c(x, y)\n value <- gaussPdf(arg, mu, E)\n \n curr <- c(curr, value)\n }\n z <- rbind(z, curr)\n }\n\n \n fig <- plot_ly(\n type = 'surface',\n x = ~xs,\n y = ~ys,\n z = ~z) %>% add_surface(\n contours = list(\n z = list(\n show=TRUE,\n usecolormap=TRUE,\n highlightcolor=\"#ff0000\",\n project=list(z=TRUE)\n )\n )\n )\n fig <- fig %>% layout(\n scene = list(\n camera=list(\n eye = list(x=1.87, y=0.88, z=-0.64)\n )\n )\n )\n #saveWidget(fig, file=\"widget.html\")\n return (fig)\n}\n\ndrawHeatmap <- function() {\n mu = c(0, 0)\n # E <- matrix(c(1, 3/5, 3/5, 2), nrow = 2)\n # E <- matrix(c(0.5, 0, 0, 2), nrow = 2)\n E <- matrix(c(2, 0.9, 0.9, 2), nrow = 2)\n \n xs <- seq(from = -5, to = 5, by = 0.1)\n ys <- seq(from = -5, to = 5, by = 0.1)\n z <- c()\n \n \n for (y in ys) {\n curr <- c()\n for (x in xs) {\n arg <- c(x, y)\n value <- gaussPdf(arg, mu, E)\n \n curr <- c(curr, value)\n }\n z <- rbind(z, curr)\n }\n \n \n fig <- plot_ly(\n type = 'heatmap',\n x = ~xs,\n y = ~ys,\n z = ~z)\n #saveWidget(fig, file=\"widget.html\")\n return (fig)\n}\n\n# drawPlot()\ndrawHeatmap()\n\n# plotly 3D plotting tests:\n# x = c(1,2,3,4,5)\n# y = c(1,2,3,4,5)\n# z <- c()\n# z = rbind(z,\n# c(2, 1, 2.2, 1, 0),\n# c(1, 0, 1, 0, 1))\n# \n# z <- rbind(z, c(0, 1, 0, 1, 0),\n# c(1, 0, 1, 0, 1),\n# c(0, 1, 0, 1, 0))\n# \n# fig <- plot_ly(\n# type = 'surface',\n# x = ~x,\n# y = ~y,\n# z = ~z)\n# \n# fig", "meta": {"hexsha": "839a44f28c5be73e695ce4767c4b1d95d044c76a", "size": 2064, "ext": "r", "lang": "R", "max_stars_repo_path": "5 - Contour lines of the Gaussian distribution PDF/contour-lines.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": "5 - Contour lines of the Gaussian distribution PDF/contour-lines.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": "5 - Contour lines of the Gaussian distribution PDF/contour-lines.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": 18.4285714286, "max_line_length": 58, "alphanum_fraction": 0.4215116279, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.8134444386947716}} {"text": "B <- matrix(c(7,9,3,5),2,2)\r\nC <- matrix(c(3,2,3,2,8,1,4,-2,8),3,3)\r\ndeterminant_B=det(B)\r\ndeterminant_C=det(C)\r\ndeterminant_B\r\ndeterminant_C\r\nsolve(B)\r\nsolve(C)\r\n# B* inverse B\r\nx=zapsmall(solve(B)%*%B)\r\nx\r\n# C* inverse C\r\ny=zapsmall(solve(C)%*%C)\r\ny\r\n", "meta": {"hexsha": "8f981cae9114dd543f298bace16eca2b9c530f44", "size": 253, "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.27/Ex12_27.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.27/Ex12_27.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.27/Ex12_27.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": 16.8666666667, "max_line_length": 39, "alphanum_fraction": 0.6205533597, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.8134103230221966}} {"text": "#statistical analysis in R is performed by many built in functions\r\n\r\n meanfunc <- function(){\r\n#mean(x, trim = 0, na.rm = FALSE, ...)\r\n# Create a vector.\r\nx <- c(12,7,3,4.2,18,2,54,-21,8,-5)\r\n# Find Mean.\r\nresult.mean <- mean(x)\r\nprint(result.mean)\r\n#When trim parameter is supplied, the values in the vector get sorted \r\n#and then the required numbers of observations are dropped from calculating the mean.\r\n#applying the trim function\r\n#When trim = 0.3, 3 values from each end will be dropped from the calculations to find mean\r\nresult.mean <- mean(x,trim = 0.3)\r\nprint(result.mean)\r\n\r\n#If there are missing values, then the mean function returns NA.\r\n#To drop the missing values from the calculation use na.rm = TRUE. which means remove the NA values.\r\n# Create a vector. \r\nx <- c(12,7,3,4.2,18,2,54,-21,8,-5,NA)\r\n\r\n# Find mean.\r\nresult.mean <- mean(x)\r\nprint(result.mean)\r\n\r\n# Find mean dropping NA values.\r\nresult.mean <- mean(x,na.rm = TRUE)\r\nprint(result.mean)\r\n }\r\n# meanfunc()\r\n\r\n medianfunc <- function(){\r\n#median(x, na.rm = FALSE)\r\n# Create the vector.\r\nx <- c(12,7,3,4.2,18,2,54,-21,8,-5)\r\n\r\n# Find the median.\r\nmedian.result <- median(x)\r\nprint(median.result)\r\n }\r\n# medianfunc()\r\n\r\n#Unike mean and median, mode can have both numeric and character data.\r\n# This function takes the vector as input and gives the mode value as output\r\nmodefunc <- function(){\r\n# Create the function.\r\ngetmode <- function(v) {\r\n uniqv <- unique(v)\r\n uniqv[which.max(tabulate(match(v, uniqv)))]\r\n}\r\n\r\n# Create the vector with numbers.\r\nv <- c(2,1,2,3,1,2,3,4,1,5,5,3,2,3)\r\n\r\n# Calculate the mode using the user function.\r\nresult <- getmode(v)\r\nprint(result)\r\n\r\n# Create the vector with characters.\r\ncharv <- c(\"o\",\"it\",\"the\",\"it\",\"it\")\r\n\r\n# Calculate the mode using the user function.\r\nresult <- getmode(charv)\r\nprint(result)\r\n}\r\n# modefunc()\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n# Regression analysis is a very widely used statistical tool \r\n# to establish a relationship model between two variables.\r\n#one of the variables are called predictor variable which its values are gathered through the experiment\r\n#the other variable is called response variable which its values are derived from the other variable\r\n#y= ax + b \r\n# y ==> response variable\r\n# x ==> predictor variable\r\nif(FALSE){\r\n \"The steps to create the relationship is :\r\n==>Carry out the experiment of gathering a sample of observed values of height and corresponding weight.\r\n==>Create a relationship model using the lm() functions in R.\r\n==>Find the coefficients from the model created and create the mathematical equation using these\r\n==>Get a summary of the relationship model to know the average error in prediction. Also called residuals.\r\n==>To predict the weight of new persons, use the predict() function in R.\"\r\n\r\n\"# Values of height\r\n151, 174, 138, 186, 128, 136, 179, 163, 152, 131\r\n\r\n# Values of weight.\r\n63, 81, 56, 91, 47, 57, 76, 72, 62, 48\"\r\n}\r\n\r\n#lm() in linear regression syntax: lm(formula,data)\r\n# formula is a symbol presenting the relation between x and y.\r\n# data is the vector on which the formula will be applied.\r\n\r\nlinear_regression <- function(){\r\n# The predictor vector. (height)\r\nx <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)\r\n# The resposne vector. (weight)\r\ny <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)\r\n\r\n# Apply the lm() function.\r\nrelation <- lm(y~x)\r\n\r\n# print(relation)\r\n# print(summary(relation)) #summary of the relationship\r\n\r\n# predict(object, newdata)\r\n# object is the formula which is already created using the lm() function.\r\n# newdata is the vector containing the new value for predictor variable\r\n\r\n# Find weight of a person with height 170.\r\na <- data.frame(x = 170)\r\nresult <- predict(relation,a)\r\nprint(result)\r\n\r\n#************************************************************ chart of the regression line\r\n# Give the chart file a name.\r\npng(file = \"linearregression.png\")\r\n\r\n# Plot the chart.\r\nplot(y,x,col = \"blue\",main = \"Height & Weight Regression\",\r\nabline(lm(x~y)),cex = 1.3,pch = 16,xlab = \"Weight in Kg\",ylab = \"Height in cm\")\r\n\r\n# Save the file.\r\ndev.off()\r\n#*****************************************************************\r\n}\r\n# linear_regression()\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n#Nonlinear regression\r\nif(FALSE){\r\n\" In Least Square regression, we establish a regression model in which the sum of the squares of the vertical distances \r\n of different points from the regression curve is minimized. We generally start with a defined model and assume some values \r\n for the coefficients. We then apply the nls() function of R to get the more accurate values along with the confidence intervals.\"\r\n#nls(formula, data, start)\r\n\"formula is a nonlinear model formula including variables and parameters.\r\ndata is a data frame used to evaluate the variables in the formula.\r\nstart is a named list or named numeric vector of starting estimates.\"\r\n\r\n#We will consider a nonlinear model with assumption of initial values of its coefficients\r\n#Next we will see what is the confidence intervals of these assumed values so that we can judge how well these values fit into the model.\r\n}\r\n\r\n# We consider the equation a = b1*x^2+b2 for this purpose, and 1 and 3 for the coefissients and fit these values into nls() function\r\nnonlinear_regression <- function(){\r\nxvalues <- c(1.6,2.1,2,2.23,3.71,3.25,3.4,3.86,1.19,2.21)\r\nyvalues <- c(5.19,7.43,6.94,8.11,18.75,14.88,16.06,19.12,3.21,7.58)\r\n\r\n# Give the chart file a name.\r\npng(file = \"nls.png\")\r\n\r\n# Plot these values.\r\nplot(xvalues,yvalues)\r\n\r\n# Take the assumed values and fit into the model.\r\nmodel <- nls(yvalues ~ b1*xvalues^2+b2,start = list(b1 = 1,b2 = 3))\r\n\r\n# Plot the chart with new data by fitting it to a prediction from 100 data points.\r\nnew.data <- data.frame(xvalues = seq(min(xvalues),max(xvalues),len = 100))\r\nlines(new.data$xvalues,predict(model,newdata = new.data))\r\n\r\n# Save the file.\r\ndev.off()\r\n\r\n# Get the sum of the squared residuals.\r\nprint(sum(resid(model)^2))\r\n\r\n# Get the confidence intervals on the chosen values of the coefficients.\r\nprint(confint(model))\r\n}\r\n# nonlinear_regression()\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n# in multiple regression we have more than one predictor variable and one response variable.\r\n# The general mathematical equation for multiple regression is −\r\n# y = a + b1x1 + b2x2 +...bnxn (y ==> response (x1,x2,x3,..) ==> predictors)\r\n#lm() function creates the relationship model between the predictor and the response variable\r\nif(FALSE){\r\n 'Consider the data set \"mtcars\" available in the R environment.\r\n It gives a comparison between different car models in terms of mileage per gallon (mpg),\r\n cylinder displacement(\"disp\"), horse power(\"hp\"), weight of the car(\"wt\") and some more parameters\r\n The goal of the model is to establish the relationship between \"mpg\" as a response variable\r\n with \"disp\",\"hp\" and \"wt\" as predictor variables'\r\n}\r\nmultiple_regression <- function(){\r\ninput <- mtcars[,c(\"mpg\",\"disp\",\"hp\",\"wt\")]\r\nprint(head(input))\r\n\r\n# Create the relationship model.\r\nmodel <- lm(mpg~disp+hp+wt, data = input)\r\n\r\n# Show the model.\r\n# print(model)\r\n\r\n# Get the Intercept and coefficients as vector elements.\r\ncat(\"# # # # The Coefficient Values # # # \",\"\\n\")\r\n\r\na <- coef(model)[1]\r\nprint(a)\r\n\r\nXdisp <- coef(model)[2]\r\nXhp <- coef(model)[3]\r\nXwt <- coef(model)[4]\r\n\r\nprint(Xdisp)\r\nprint(Xhp)\r\nprint(Xwt)\r\n\r\n# creating the equation for the regression model\r\n#we want to create the mathematical equation \r\n# Y = a+Xdisp.x1+Xhp.x2+Xwt.x3\r\n# or\r\n# Y = 37.15+(-0.000937)*x1+(-0.0311)*x2+(-3.8008)*x3\r\n\r\n# Applying equation for prediting new values\r\na <- data.frame(disp = 190,hp=100,wt=3)\r\nresult <- predict(model,a)\r\nprint(result)\r\n}\r\n# multiple_regression()\r\n\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n#The Logistic Regression is a regression model in which the response variable (dependent variable) \r\n#has categorical values such as True/False or 0/1. \r\n#It actually measures the probability of a binary response as the value of response variable \r\n#based on the mathematical equation relating it with the predictor variables\r\nif(FALSE){\r\n \"The general mathematical equation for logistic regression is y = 1/(1+e^-(a+b1x1+b2x2+b3x3+...))\"\r\n \"y is the response variable.\r\n x is the predictor variable.\r\n a and b are the coefficients which are numeric constants\"\r\n #to create logistic regression model, we use glm() function, glm(formula,data,family)\r\n \"formula is the symbol presenting the relationship between the variables.\r\n data is the data set giving the values of these variables.\r\n family is R object to specify the details of the model. It's value is binomial for logistic regression.\"\r\n\r\n'The built-in data set \"mtcars\" describes different models of a car with their\r\n various engine specifications. In \"mtcars\" data set, the transmission mode (automatic or manual)\r\n is described by the column am which is a binary value (0 or 1). We can create a \r\n logistic regression model between the columns \"am\" and 3 other columns - hp, wt and cyl.'\r\n}\r\nlogistic_regression <- function(){\r\n # Select some columns form mtcars.\r\ninput <- mtcars[,c(\"am\",\"cyl\",\"hp\",\"wt\")]\r\nprint(head(input))\r\nam.data = glm(formula = am ~ cyl + hp + wt, data = input, family = binomial)\r\n# print(summary(am.data))\r\n\r\n# Applying equation for prediting new values\r\na <- data.frame(cyl = 7,hp=200,wt=3.65)\r\nresult <- predict(am.data,a)\r\nprint(result) #does not print 1 or 0!\r\n\r\n}\r\n# logistic_regression()\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nif(FALSE){ #Possion\r\n \"poisson Regression involves regression models in which the response variable is \r\n in the form of counts and not fractional numbers. For example, the count of number \r\n of births or number of wins in a football match series. \r\n Also the values of the response variables follow a Poisson distribution\"\r\n\r\n #log(y) = a + b1x1 + b2x2 + bnxn.....\r\n \"y is the response variable.\r\n a and b are the numeric coefficients.\r\n x is the predictor variable.\"\r\n#possion regression is created by glm() function, glm(formula,data,family)\r\n \"formula is the symbol presenting the relationship between the variables.\r\n data is the data set giving the values of these variables.\r\n family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression.\"\r\n\r\n}\r\n\r\npoisson_regression <- function(){\r\n# We have the built-in data set \"warpbreaks\" which describes the effect of wool type (A or B) and tension (low, medium or high) \r\n# on the number of warp breaks per loom. Let's consider \"breaks\" as the response variable \r\n# which is a count of number of breaks. The wool \"type\" and \"tension\" are taken as predictor variables\r\n input <- warpbreaks\r\nprint(head(input))\r\noutput <-glm(formula = breaks ~ wool+tension, data = warpbreaks,\r\n family = poisson)\r\n# print(summary(output))\r\n\r\n# Applying equation for prediting new values (does not work)\r\n#make a datframe with new data \r\n# library(caret)\r\n# newdata = data.frame(wool=\"B\", tension=\"M\")#use 'predict() to run model on new data\r\n# result <- predict(input, newdata = newdata, type = \"response\")\r\n# print(result)\r\n}\r\n# poisson_regression()\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n# R has four built-in functions to generate normal distribution. They are described below.\r\nif(FALSE){\r\n \"dnorm(x, mean, sd)\r\n pnorm(x, mean, sd)\r\n qnorm(p, mean, sd)\r\n rnorm(n, mean, sd)\"\r\n\r\n \"x is a vector of numbers.\r\n p is a vector of probabilities.\r\n n is number of observations(sample size).\r\n mean is the mean value of the sample data. It's default value is zero.\r\n sd is the standard deviation. It's default value is 1.\"\r\n\r\n}\r\n#dnorm() function gives height of the probability distribution at each point\r\n#for a given mean and standard deviation.\r\n\r\ndnorm_func <- function(){\r\n # Create a sequence of numbers between -10 and 10 incrementing by 0.1.\r\nx <- seq(-10, 10, by = .1)\r\n\r\n# Choose the mean as 2.5 and standard deviation as 0.5.\r\ny <- dnorm(x, mean = 2.5, sd = 0.5)\r\n\r\n# Give the chart file a name.\r\npng(file = \"dnorm.png\")\r\n\r\nplot(x,y)\r\n# Save the file.\r\ndev.off()\r\n}\r\n# dnorm_func()\r\n\r\n#***************************************************************************\r\n#pnorm() function gives the probability of a normally distributed random number \r\n#to be less than the value of a given number. It is also called \"Cumulative Distribution Function\r\npnorm_func <- function(){\r\n # Create a sequence of numbers between -10 and 10 incrementing by 0.2.\r\nx <- seq(-10,10,by = .2)\r\n \r\n# Choose the mean as 2.5 and standard deviation as 2. \r\ny <- pnorm(x, mean = 2.5, sd = 2)\r\n\r\n# Give the chart file a name.\r\npng(file = \"pnorm.png\")\r\n\r\n# Plot the graph.\r\nplot(x,y)\r\n\r\n# Save the file.\r\ndev.off()\r\n}\r\n# pnorm_func()\r\n\r\n#***************************************************************************\r\n# qnorm() function takes the probability value and \r\n# gives a number whose cumulative value matches the probability value.\r\nqnorm_func <- function(){\r\n# Create a sequence of probability values incrementing by 0.02.\r\nx <- seq(0, 1, by = 0.02)\r\n\r\n# Choose the mean as 2 and standard deviation as 1.\r\ny <- qnorm(x, mean = 2, sd = 1)\r\n\r\n# Give the chart file a name.\r\npng(file = \"qnorm.png\")\r\n\r\n# Plot the graph.\r\nplot(x,y)\r\n\r\n# Save the file.\r\ndev.off()\r\n}\r\n# qnorm_func()\r\n\r\n#***************************************************************************\r\n# rnorm() function is used to generate random numbers whose distribution is normal. \r\n# It takes the sample size as input and generates that many random numbers. \r\n# We draw a histogram to show the distribution of the generated numbers.\r\n\r\nrnorm_func <- function(){\r\n# Create a sample of 50 numbers which are normally distributed.\r\ny <- rnorm(50)\r\n\r\n# Give the chart file a name.\r\npng(file = \"rnorm.png\")\r\n\r\n# Plot the histogram for this sample.\r\nhist(y, main = \"Normal DIstribution\")\r\n\r\n# Save the file.\r\ndev.off()\r\n}\r\n# rnorm_func()\r\n\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nif(FALSE){\r\n \"The binomial distribution model deals with finding the probability of success \r\n of an event which has only two possible outcomes in a series of experiments. \r\n For example, tossing of a coin always gives a head or a tail. \r\n The probability of finding exactly 3 heads in tossing a coin repeatedly \r\n for 10 times is estimated during the binomial distribution.\"\r\n\r\n# R has four in-built functions to generate binomial distribution. They are described below.\r\n \"dbinom(x, size, prob)\r\n pbinom(x, size, prob)\r\n qbinom(p, size, prob)\r\n rbinom(n, size, prob)\"\r\n\r\n \"x is a vector of numbers.\r\n p is a vector of probabilities.\r\n n is number of observations.\r\n size is the number of trials.\r\n prob is the probability of success of each trial.\"\r\n}\r\n\r\n# dbinom() function gives the probability density distribution at each point.\r\ndbinom_func <- function(){\r\n# Create a sample of 50 numbers which are incremented by 1.\r\nx <- seq(0,50,by = 1)\r\n\r\n# Create the binomial distribution.\r\ny <- dbinom(x,50,0.5) #50 trials with 1/2 chance of success\r\n\r\n# Give the chart file a name.\r\npng(file = \"dbinom.png\")\r\n\r\n# Plot the graph for this sample.\r\nplot(x,y)\r\n\r\n# Save the file.\r\ndev.off()\r\n}\r\n# dbinom_func()\r\n\r\n# pbinom() function gives the cumulative probability of an event. \r\n# It is a single value representing the probability.\r\npbinom_func <- function(){\r\n# Probability of getting 26 or less heads from a 51 tosses of a coin.\r\nx <- pbinom(26,51,0.5)\r\n\r\nprint(x)\r\n}\r\n# pbinom_func()\r\n\r\n# qbinom() function takes the probability value and gives a number \r\n# whose cumulative value matches the probability value.\r\nqbinom_func <- function(){\r\n# How many heads will have a probability of 0.25 will come out when a coin\r\n# is tossed 51 times.\r\nx <- qbinom(0.25,51,1/2)\r\n\r\nprint(x)\r\n}\r\n# qbinom_func()\r\n\r\n# rbinom() function generates required number of random values of given probability from a given sample.\r\nrbinom_func <- function(){\r\n# Find 8 random values from a sample of 150 with probability of 0.4.\r\nx <- rbinom(8,150,.4)\r\n\r\nprint(x)\r\n}\r\n# rbinom_func()\r\n\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n#ANCOVA Analysis\r\nif(FALSE){\r\n'Create a data frame containing the fields \"mpg\", \"hp\" and \"am\" from the data set mtcars.\r\nHere we take \"mpg\" as the response variable, \"hp\" as the predictor variable and \"am\" as the categorical variable.'\r\n'We create a regression model taking \"hp\" as the predictor variable and \"mpg\" as the response variable \r\ntaking into account the interaction between \"am\" and \"hp\".'\r\n}\r\n\r\nancova <- function(){\r\n# Get the dataset.\r\ninput <- mtcars\r\n\r\n# Create the regression model. (Model with interaction between categorical variable and predictor variable)\r\nresult1 <- aov(mpg~hp*am,data = input)\r\n# print(summary(result1))\r\n\r\n# Create the regression model. (Model without interaction between categorical variable and predictor variable)\r\nresult2 <- aov(mpg~hp+am,data = input)\r\n# print(summary(result2))\r\n\r\n# Compare the two models.\r\nprint(anova(result1,result2))\r\n# As the p-value is greater than 0.05(0.9806) we conclude that the interaction between horse power and transmission type is not significant. \r\n# So the mileage per gallon will depend in a similar manner on the horse power of the car in both auto and manual transmission mode.\r\n}\r\nancova()\r\n# input <- mtcars[,c(\"am\",\"mpg\",\"hp\")]\r\n# print(head(input))\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": "e0ab70c02577a1474bbfec2e251b693ee831c2db", "size": 17871, "ext": "r", "lang": "R", "max_stars_repo_path": "R/statistics.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/statistics.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/statistics.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": 34.904296875, "max_line_length": 142, "alphanum_fraction": 0.6551396117, "num_tokens": 4352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802362, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.8132967215465864}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Non parametric Tests - Exercise 10\n\nrm(list = ls())\n\nx.f <- c(60, 21, 11, 4, 3, 1)\ny.f <- c(130, 50, 10, 6, 4, 0)\n\nx <- rep(1:length(x.f), x.f)\ny <- rep(1:length(y.f), y.f)\n\n(n.x <- length(x))\n# 100\n\n(n.y <- length(y))\n# 200\n\n(n <- n.x + n.y)\n# 300\n\n(W.x <- sum(rank(c(x, y))[1:n.x]))\n# 15806\n\n(W.xy <- W.x - n.x * (n.x + 1) / 2)\n# 10756\n\n(W.xy.mean <- n.x * n.y / 2)\n# 10000\n\n(W.xy.var <- n.x * n.y * (n.x + n.y + 1) / 12)\n# 501666.67\n\n(ties <- table(c(x, y)))\n# 1 2 3 4 5 6\n# 190 71 21 10 7 1\n\n(W.xy.var.corrected <- n.x * n.y / 12 * ((n + 1) - sum(ties ^ 3 - ties) / (n * (n - 1))))\n# 367381.716833891\n\n# Asymptotic pvalue (with continuity correction, without tie correction)\n2 * (1 - pnorm(abs(W.xy + 0.5 * sign(W.xy.mean - W.xy) - W.xy.mean) / sqrt(W.xy.var)))\n# 0.286124467472471\n\n## Asymptotic pvalue (with continuity correction, with tie correction)\n2 * (1 - pnorm(abs(W.xy + 0.5 * sign(W.xy.mean - W.xy) - W.xy.mean) / sqrt(W.xy.var.corrected)))\n# 0.21259835316298\n\n## Exact pvalue (not valid with ties)\n2 * (1 - pwilcox(W.xy - (W.xy.mean < W.xy), n.x, n.y, lower.tail = W.xy.mean < W.xy))\n# 0.286650510800022\n\n\nwilcox.test(x, y, alternative = \"two.sided\", exact = FALSE)\n# Wilcoxon rank sum test with continuity correction\n#\n# data: x and y\n# W = 10756, p-value = 0.2126\n# alternative hypothesis: true location shift is not equal to 0\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "29eceb4cf8d9406f769cb8ab3357be0cbe926b60", "size": 1448, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/non-parametric/exercise-10.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-10.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-10.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.8051948052, "max_line_length": 96, "alphanum_fraction": 0.5725138122, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8740772253241803, "lm_q1q2_score": 0.8132923668712172}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Non parametric Tests - Exercise 01\n\nrm(list = ls())\n\nx <- c(518, 174, 613, 2010, 2139, 156, 450, 536)\n(n.x <- length(x))\n# 8\n\ny <- c(899, 326, 2118, 839, 820, 1423, 1687, 1010, 3011, 1739, 1185, 1320, 646,\n 505, 4236, 4481, 1433, 1806, 400, 421, 335, 1164, 1713, 1356, 390)\n(n.y <- length(y))\n# 25\n\n(n <- n.x + n.y)\n# 33\n\n\nsum(duplicated(c(y, x))) > 0\n# FALSE\n\n(W <- sum(rank(c(y, x))[1:length(y)]))\n# 459\n\n(W.mean <- n.y * (n + 1) / 4)\n# 212.5\n\n(W.var <- (n.y * n.x * (n + 1)) / 12)\n# 566.666666666667\n\n(W.yx <- W - n.y * (n.y + 1) / 2)\n# 134\n\n(W.yx.mean <- n.x * n.y / 2)\n# 100\n\n(W.yx.var <- n.x * n.y * (n + 1) / 12)\n# 566.667\n\n### H0: X <= Y\n\n## Asymptotic pvalue (with continuity correction)\n1 - pnorm((W.yx - 0.5 - W.yx.mean) / sqrt(W.yx.var))\n# 0.0796719687339751\n\n## Exact pvalue\n1 - pwilcox(W.yx - 1, n.y, n.x)\n# 0.0812147313815834\n\n### Shift Parameter Estimation\n\na <- matrix(rep(0, n.x * n.y), n.x, n.y)\nfor (i in 1:n.x) {\n for (j in 1:n.y) {\n a[i, j] <- y[j] - x[i]\n }\n}\n\n# Exact\nmedian(a)\n# 491\n\nwilcox.test(y, x, alternative = \"greater\", conf.int = TRUE)\n# Wilcoxon rank sum test\n#\n# data: y and x\n# W = 134, p-value = 0.08121\n# alternative hypothesis: true location shift is greater than 0\n# 95 percent confidence interval:\n# -60 Inf\n# sample estimates:\n# difference in location\n# 491\n", "meta": {"hexsha": "72c9df0237a8dde43c5bc794c74ae2f87031da17", "size": 1399, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/non-parametric/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/non-parametric/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/non-parametric/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": 18.9054054054, "max_line_length": 79, "alphanum_fraction": 0.5632594711, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.8132356605514892}} {"text": "## Punto 1 ##\nn <- 200\n\nnj <- c(60,80,30,20,10)\nhj <- nj/n\nNj <- cumsum(nj)\nHj <- cumsum(hj)\n\n#Marca de clase\nli <- c(0,10,20,30,100)\nls <- c(10,20,30,100,200)\nx <- (li+ls)/2\n\n#Promedio\nx_bar <- sum(x*nj)/n\n\nsum(hj[2:4])\n\n\n## Punto 2 ##\n\n#Importar archivo\nlibrary(rstudioapi)\nfilename = \"taller3.r\"\nfilepath = rstudioapi::getActiveDocumentContext()$path\ndir = substr(filepath, 1, nchar(filepath)-nchar(filename))\nsetwd(dir)\n\ndatos <- read.table(file=\"taller03_datos.txt\")\ncal <- datos$V1\n\nR <- (max(cal)-min(cal))\ny_bar <- mean(cal)\nn_2 <- length(cal)\nm_2 <- 10\na_2 <- R/10\n\nlim <- min(cal) + (0:m_2)*a_2\nnj_2 <- table(cut(x = cal, breaks = lim, include.lowest = T))\nhj_2 <- nj_2/n_2\nNj_2 <- cumsum(nj_2)\nHj_2 <- cumsum(hj_2)\n\n\n## Punto 3 ##\n\nM1 <- c(0.32, 0.35, 0.37, 0.39, 0.42, 0.47, 0.51, 0.58, 0.60, 0.62, 0.65, 0.68, 0.75)\n\nM2 <- c(0.25, 0.40, 0.48, 0.55, 0.56, 0.58, 0.60, 0.65, 0.70, 0.76, 0.80, 0.91, 0.99)\nR1 <- max(M1)-min(M1)\nR2 <- max(M2)-min(M2)\n\n\n## Punto 4 ##\n\nc <- 87.3\nf <- (9*c)/5 + 32\n\n## Punto 5 ##\n\nx_b <- 168\nn_5 <- 21\nx <- ((x_b+2)*(n_5+1))-(x_b*n_5)\n\n\n## Punto 6 ##\n\nd <- c(300,400,500,600,700)\nnj_6 <- c(10,16,35,26,13)\n\nx_b <- sum(d*nj_6)/sum(nj_6)\ng <- (d*1.02)\nj <- d+10\n", "meta": {"hexsha": "7f9139575ea1b6ac0510bdc1c819d621db3d25f4", "size": 1200, "ext": "r", "lang": "R", "max_stars_repo_path": "03.medidadTendenciaCentral/taller3.r", "max_stars_repo_name": "devHectorGa/UNALProbabilidadEstadistica", "max_stars_repo_head_hexsha": "1cd472cc1b39daa8a9b81d40ec128d3d168af0a5", "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.medidadTendenciaCentral/taller3.r", "max_issues_repo_name": "devHectorGa/UNALProbabilidadEstadistica", "max_issues_repo_head_hexsha": "1cd472cc1b39daa8a9b81d40ec128d3d168af0a5", "max_issues_repo_licenses": ["MIT"], "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.medidadTendenciaCentral/taller3.r", "max_forks_repo_name": "devHectorGa/UNALProbabilidadEstadistica", "max_forks_repo_head_hexsha": "1cd472cc1b39daa8a9b81d40ec128d3d168af0a5", "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.2162162162, "max_line_length": 85, "alphanum_fraction": 0.5725, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8757869900269366, "lm_q1q2_score": 0.8130883506877662}} {"text": "#Example randomization code, written (mostly) in class\n#30/10/2013\n\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)\n\nrand.func<-function(data,n=999,H0=0){\n#Purpose: Perform randomziation test on a mean of a univariate data sample\n#Inputs:\n# data - vector of data\n# n - number of resamples\n# H0 - null hypothesis mean value\n#Outputs:\n# p-value of test\n\n #Error checking code should go here\n \n #vector to store the sim means means\n resample.means<-numeric(n+1)\n #create symetric dataset and turn to all positive\n centered.pos.data<-abs(data-H0)\n n.data<-length(data)\n \n #Repeat the following two steps many times:\n for(i in 1:n){\n #(a) Simulate a data set according to H0\n # simulate random signs\n signs<-sample(c(-1,1),n.data,replace=T)\n sim.data<-centered.pos.data*signs\n #(b) Calculate T(x) using the simulated data\n resample.means[i]<-mean(sim.data)\n }\n\n #Add T(x) evaluated from the sample data\n resample.means[n+1]<-mean(data)-H0\n\n #p-value is the proportion of the T(x)s as extreme or more \n # extreme than the one from the sample data\n p.value<-sum(abs(resample.means)>=abs(resample.means[n+1]))/(n+1)\n \n return(p.value)\n}\n\nx<-rand.func(martin,n=10000)\nprint(x)\n", "meta": {"hexsha": "a6fffbbcd6e025feee24fbb290cb34fad282feef", "size": 1242, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Lecture 6/randtest.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 6/randtest.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 6/randtest.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": 27.6, "max_line_length": 84, "alphanum_fraction": 0.6835748792, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.8130163051951959}} {"text": "\nejercicio1 <- read.csv('../Data/ejercicio1.csv')\nejercicio2 <- read.csv('../Data/ejercicio2.csv')\nejercicio3 <- read.csv('../Data/ejercicio3.csv')\n\nbest_ecuation <- function(data){\n X <- sum(data$X)\n Y <- sum(data$Y)\n XY <- sum(data$X * data$Y)\n X2 <- sum(data$X * data$X)\n Y2 <- sum(data$Y * data$Y)\n \n SSxy <- XY - (X*Y/length(data$X))\n \n SSx <- X2 - (X*X)/length(data$Y)\n \n b1 <- SSxy/SSx\n \n b0 <- (Y - (b1 * X))/length(data$X)\n \n result <- function(x) {\n return(b0 + b1*x)\n }\n \n return(result)\n}\n\n#fit <- lm(Y ~ X, data=data)\n\n#print(summary(fit))\n\n#MC(ejercicio1)\n\n## Section Ejercicio 1\n\njpeg(\"../Images/ejercicio1.jpeg\")\n\nplot(ejercicio1$X,ejercicio1$Y,\n xlab=\"x\",\n ylab=\"f(x)\",main = 'Gráfico de Dispersión con recta de mejor ajuste. (Ejercicio 1)')\n\nfit1 <- lm(Y ~ X, data=ejercicio1)\n\nabline(fit1)\n\n\ndev.off()\n\necuation1 <-best_ecuation(ejercicio1)\n\nprint(paste(\"El valor estimado de la función para x = 1 es: \",ecuation1(1)))\n\n## Section Ejercicio 2\n\njpeg(\"../Images/ejercicio2.jpeg\")\n\nplot(ejercicio2$X,ejercicio2$Y,\n xlab=\"x\",\n ylab=\"f(x)\",main = 'Gráfico de Dispersión con recta de mejor ajuste. (Ejercicio 2)')\n\nfit2 <- lm(Y ~ X, data=ejercicio2)\n\nabline(fit2)\n\ndev.off()\n\necuation2 <-best_ecuation(ejercicio2)\n\nprint(paste(\"El valor estimado de la función para x = 0 es: \",ecuation2(0)))\nprint(paste(\"El valor estimado de la función para x = 2 es: \",ecuation2(2)))\n\n## Section Ejercicio 3\n\njpeg(\"../Images/ejercicio3norecta.jpeg\")\n\nplot(ejercicio3$X,ejercicio3$Y,\n xlab=\"Velocidad (ft/s)\",\n ylab=\"Rapidez de pasos\",main = 'Gráfico de Dispersión. (Ejercicio 3)')\n\ndev.off()\n\njpeg(\"../Images/ejercicio3.jpeg\")\n\nplot(ejercicio3$X,ejercicio3$Y,\n xlab=\"Velocidad (ft/s)\",\n ylab=\"Rapidez de pasos\",main = 'Gráfico de Dispersión con recta de mejor ajuste. (Ejercicio 3)')\n\n\nfit3 <- lm(Y ~ X, data=ejercicio3)\n\nabline(fit3)\n\ndev.off()\n\necuation3 <-best_ecuation(ejercicio3)\n\nsummary(fit3)\n\nprint(paste(\"El valor estimado de la función para una velocidad de 19 pasos por segundo es: \",ecuation3(19)))\n", "meta": {"hexsha": "af2c43f86e054e9d1e8160bd6f655e529f3f2ca9", "size": 2062, "ext": "r", "lang": "R", "max_stars_repo_path": "First Assigment/Code/code.r", "max_stars_repo_name": "rmarticedeno/statistics_assigments", "max_stars_repo_head_hexsha": "02123f59dd7569823cf37b89c46893906efd394a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-06T14:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-06T14:47:05.000Z", "max_issues_repo_path": "First Assigment/Code/code.r", "max_issues_repo_name": "rmarticedeno/statistics_assigments", "max_issues_repo_head_hexsha": "02123f59dd7569823cf37b89c46893906efd394a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "First Assigment/Code/code.r", "max_forks_repo_name": "rmarticedeno/statistics_assigments", "max_forks_repo_head_hexsha": "02123f59dd7569823cf37b89c46893906efd394a", "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.62, "max_line_length": 109, "alphanum_fraction": 0.6542192047, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465044347828, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.8126540976443714}} {"text": "\r\n\r\n# Goal: Prices and returns\r\n\r\n# I like to multiply returns by 100 so as to have \"units in percent\".\r\n# In other words, I like it for 5% to be a value like 5 rather than 0.05.\r\n\r\n###################################################################\r\n# I. Simulate random-walk prices, switch between prices & returns.\r\n###################################################################\r\n# Simulate a time-series of PRICES drawn from a random walk\r\n# where one-period returns are i.i.d. N(mu, sigma^2).\r\nranrw <- function(mu, sigma, p0=100, T=100) {\r\n cumprod(c(p0, 1 + (rnorm(n=T, mean=mu, sd=sigma)/100)))\r\n}\r\nprices2returns <- function(x) {\r\n 100*diff(log(x))\r\n}\r\nreturns2prices <- function(r, p0=100) {\r\n c(p0, p0 * exp(cumsum(r/100)))\r\n}\r\n\r\ncat(\"Simulate 25 points from a random walk starting at 1500 --\\n\")\r\np <- ranrw(0.05, 1.4, p0=1500, T=25)\r\n # gives you a 25-long series, starting with a price of 1500, where\r\n # one-period returns are N(0.05,1.4^2) percent.\r\nprint(p)\r\n\r\ncat(\"Convert to returns--\\n\")\r\nr <- prices2returns(p)\r\nprint(r)\r\n\r\ncat(\"Go back from returns to prices --\\n\")\r\ngoback <- returns2prices(r, 1500)\r\nprint(goback)\r\n\r\n###################################################################\r\n# II. Plenty of powerful things you can do with returns....\r\n###################################################################\r\nsummary(r); sd(r) # summary statistics\r\nplot(density(r)) # kernel density plot\r\nacf(r) # Autocorrelation function\r\nar(r) # Estimate a AIC-minimising AR model\r\nBox.test(r, lag=2, type=\"Ljung\") # Box-Ljung test\r\nlibrary(tseries)\r\nruns.test(factor(sign(r))) # Runs test\r\nbds.test(r) # BDS test.\r\n\r\n###################################################################\r\n# III. Visualisation and the random walk\r\n###################################################################\r\n# I want to obtain intuition into what kinds of price series can happen,\r\n# given a starting price, a mean return, and a given standard deviation.\r\n# This function simulates out 10000 days of a price time-series at a time,\r\n# and waits for you to click in the graph window, after which a second\r\n# series is painted, and so on. Make the graph window very big and\r\n# sit back and admire.\r\n# The point is to eyeball many series and thus obtain some intuition\r\n# into what the random walk does.\r\nvisualisation <- function(p0, s, mu, labelstring) {\r\n N <- 10000\r\n x <- (1:(N+1))/250 # Unit of years\r\n while (1) {\r\n plot(x, ranrw(mu, s, p0, N), ylab=\"Level\", log=\"y\",\r\n type=\"l\", col=\"red\", xlab=\"Time (years)\",\r\n main=paste(\"40 years of a process much like\", labelstring))\r\n grid()\r\n z=locator(1)\r\n }\r\n}\r\n\r\n# Nifty -- assuming sigma of 1.4% a day and E(returns) of 13% a year\r\nvisualisation(2600, 1.4, 13/250, \"Nifty\")\r\n\r\n# The numerical values here are used to think about what the INR/USD\r\n# exchange rate would have looked like if it started from 31.37, had\r\n# a mean depreciation of 5% per year, and had the daily vol of a floating\r\n# exchange rate like EUR/USD.\r\nvisualisation(31.37, 0.7, 5/365, \"INR/USD (NOT!) with daily sigma=0.7\")\r\n# This is of course not like the INR/USD series in the real world -\r\n# which is neither a random walk nor does it have a vol of 0.7% a day.\r\n\r\n# The numerical values here are used to think about what the USD/EUR\r\n# exchange rate, starting with 1, having no drift, and having the observed\r\n# daily vol of 0.7. (This is about right).\r\nvisualisation(1, 0.7, 0, \"USD/EUR with no drift\")\r\n\r\n###################################################################\r\n# IV. A monte carlo experiment about the runs test\r\n###################################################################\r\n# Measure the effectiveness of the runs test when faced with an\r\n# AR(1) process of length 100 with a coeff of 0.1\r\nset.seed(101)\r\none.ts <- function() {arima.sim(list(order = c(1,0,0), ar = 0.1), n=100)}\r\ntable(replicate(1000, runs.test(factor(sign(one.ts())))$p.value < 0.05))\r\n# We find that the runs test throws up a prob value of below 0.05\r\n# for 91 out of 1000 experiments.\r\n# Wow! :-)\r\n# To understand this, you need to look up the man pages of:\r\n# set.seed, arima.sim, sign, factor, runs.test, replicate, table.\r\n# e.g. say ?replicate\r\n\r\n", "meta": {"hexsha": "bbbc8cc7148fbcfa97acdc1849ac8f7551f57aca", "size": 4404, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/b3.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)/b3.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)/b3.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": 42.7572815534, "max_line_length": 77, "alphanum_fraction": 0.5638056312, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8125304734805779}} {"text": "#' Fisher's Combined P-value\n#'\n#' Fisher's combined p-value, used to combine the results of individual statistical tests into an overall hypothesis.\n#' @param x - A vector of p-values (floating point numbers).\n#' @return a floating point number, a combined p-value using Fisher's method.\n#' @export stats.fishersMethod\n#' @examples\n#' stats.fishersMethod(c(0.2,0.1,0.3))\n#' > 0.1152162\nstats.fishersMethod = function(x) {\n return (pchisq(-2 * sum(log(x)),df=2*length(x),lower=FALSE))\n}\n", "meta": {"hexsha": "df4b49249264d088676b39e7052a66ffdf788554", "size": 488, "ext": "r", "lang": "R", "max_stars_repo_path": "R/stats.fishersMethod.r", "max_stars_repo_name": "Xiqi-Li/CTD", "max_stars_repo_head_hexsha": "3002736b9cc43e5435b8a0bf07535b0146a1e32c", "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/stats.fishersMethod.r", "max_issues_repo_name": "Xiqi-Li/CTD", "max_issues_repo_head_hexsha": "3002736b9cc43e5435b8a0bf07535b0146a1e32c", "max_issues_repo_licenses": ["MIT"], "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/stats.fishersMethod.r", "max_forks_repo_name": "Xiqi-Li/CTD", "max_forks_repo_head_hexsha": "3002736b9cc43e5435b8a0bf07535b0146a1e32c", "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.5384615385, "max_line_length": 117, "alphanum_fraction": 0.7151639344, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.8123951214340163}} {"text": "# oneway.test.r\r\ny <- c( 11, 11, 10, 10, 10, 11, 10, 8, 10, 9,\r\n 12, 11, 11, 13, 12, 11, 11, 11, 12, 9,\r\n 12, 13, 13, 11, 10, 13, 11, 12, 13, 11,\r\n 9, 10, 8, 10, 13, 10, 10, 10, 10, 8)\r\nmy.i <- c(mean(y[1:10]), mean(y[11:20]), mean(y[21:30]),mean(y[31:40]))\r\nn.i <- c(10,10,10,10)\r\nCT <- length(y)*mean(y)^2\r\nSST <- sum (y^2) - CT\r\nSSTrt <- sum(n.i*my.i^2) - CT\r\nSSE <- SST - SSTrt\r\nMSTrt <- SSTrt /(4-1)\r\nMSE <- SSE / (40-4)\r\nF0 <- MSTrt / MSE\r\nF0\r\n1-pf(F0, 3, 36)\r\n\r\n#====================\r\n\r\ny <- c( 11, 11, 10, 10, 10, 11, 10, 8, 10, 9,\r\n 12, 11, 11, 13, 12, 11, 11, 11, 12, 9,\r\n 12, 13, 13, 11, 10, 13, 11, 12, 13, 11,\r\n 9, 10, 8, 10, 13, 10, 10, 10, 10, 8)\r\nx <- c(rep(1,10), rep(2,10), rep(3,10), rep(4,10))\r\nfert <- data.frame(y,x)\r\noneway.test(y ~x, var.equal=T)\r\n\r\n", "meta": {"hexsha": "1bb69524d6796893d84ad8c0230985060b9fb984", "size": 829, "ext": "r", "lang": "R", "max_stars_repo_path": "R.2019.2/advanced.R/Rcode/Chap3/oneway.test.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/oneway.test.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/oneway.test.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.6071428571, "max_line_length": 72, "alphanum_fraction": 0.4439083233, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556619, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.8123776994094056}} {"text": "################\n#---PACKAGES---#\n################\nrequire(ggplot2)\nrequire(reshape2)\n\n\n#########################\n#---JC69 CTMC EXAMPLE---#\n#########################\nJC69 <- function (theta, t) {\n p0 = 1/4 + 3/4 * exp(-4*theta*t)\n p1 = 1/4 - 1/4 * exp(-4*theta*t)\n \n trans_prob = matrix(c(p0, p1, p1, p1,\n p1, p0, p1, p1,\n p1, p1, p0, p1,\n p1, p1, p1, p0\n ), nrow = 4, ncol = 4, byrow = T)\n \n colnames(trans_prob) <- rownames(trans_prob) <- c(\"T\", \"C\", \"A\", \"G\")\n return(trans_prob)\n}\n\nN = 50\ntimes = seq(0, 0.1, length.out = N)\ndata <- data.frame(\n T = rep(NA, N),\n C = rep(NA, N),\n A = rep(NA, N),\n G = rep(NA, N)\n)\n\n# set.seed(123)\nr <- runif(4)\nvect <- r / sum(r)\n\n\ndata[1, ] <- vect\ntheta <- 2\n\nfor (i in 2 : N) {\n probs = as.matrix(data[i - 1, ], nrow = 1, ncol = 4)\n data[i, ] <- probs %*% JC69(theta, t = times[i]) \n}\n\ndata_melt <- melt(cbind(t = times, data), id.vars = \"t\") \n\np <- ggplot(data_melt)\np <- p + geom_line(aes(x = t, y = value, color = variable)) \np <- p + xlab(\"Time\") + ylab(\"Probability\")\ntheme <- theme(\n axis.title = element_text(colour = \"black\"),\n axis.text = element_text(colour = \"black\"),\n axis.line = element_line(colour = \"black\"),\n axis.ticks = element_line(colour = \"black\"),\n panel.background = element_rect(size = 1, fill = \"white\", colour = NA),\n plot.background = element_rect(colour = NA),\n panel.border = element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()\n)\np <- p + theme\nprint(p)\n\n###################################\n#---BINOMIAL LIKELIHOOD EXAMPLE---#\n###################################\nmyBlue = rgb(r = 86, g = 110, b = 126, maxColorValue = 250)\n\n\n\nlike <- function(theta, k = 8, n = 10) {\n return(dbinom(k, n, theta))\n}\n\n# 900 x 600\ntheta <- seq(from = 0, to = 1, by = 0.01)\nplot(theta, like(theta), type = \"l\", col = myBlue, lwd = 3)\n\n\npoints(0.8, like(0.8), pch = 19, col = myBlue, cex = 1.5)\n\n\n# fair coin?\n\n", "meta": {"hexsha": "4dfd81ea3a20362c800b1ea18596d5a02bbbcce6", "size": 2002, "ext": "r", "lang": "R", "max_stars_repo_path": "ML_methods_and_hypothesis_testing_in_molecular_phylogenetics/plots/plots.r", "max_stars_repo_name": "fbielejec/VEME2016", "max_stars_repo_head_hexsha": "b7a0d19f3335353b80ec3a0c6c67a944add19c4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-19T15:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T15:57:45.000Z", "max_issues_repo_path": "ML_methods_and_hypothesis_testing_in_molecular_phylogenetics/plots/plots.r", "max_issues_repo_name": "fbielejec/VEME2016", "max_issues_repo_head_hexsha": "b7a0d19f3335353b80ec3a0c6c67a944add19c4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML_methods_and_hypothesis_testing_in_molecular_phylogenetics/plots/plots.r", "max_forks_repo_name": "fbielejec/VEME2016", "max_forks_repo_head_hexsha": "b7a0d19f3335353b80ec3a0c6c67a944add19c4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-19T15:57:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T15:57:47.000Z", "avg_line_length": 23.0114942529, "max_line_length": 73, "alphanum_fraction": 0.50999001, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983308, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.8121319302048571}} {"text": "# Example : 2.1A Chapter : 2.1 Pageno : 39\n#Solving the equations by Column picture\n#Column Picture : solution is the linear combination of columns of A that makes b\nA=matrix(c(1,2,3,3,2,5,2,2,6),ncol=3)\nb=c(-3,-2,-5)\nx<-solve(A,b)\nx\n#if b=(4,4,8)\nb=c(4,4,8)\nx<-solve(A,b)\nx", "meta": {"hexsha": "6d8a1e7c787d880efcc6463e5877320f105f5366", "size": 277, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.1.a/Ex2_2.1a.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.a/Ex2_2.1a.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.a/Ex2_2.1a.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.1818181818, "max_line_length": 81, "alphanum_fraction": 0.6570397112, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.8121319239553736}} {"text": "###########################################################\n### C10 Class: Linear Models\n###########################################################\n\n# Fitting simple linear models\n\ndata(father.son, package = \"UsingR\")\nlibrary(ggplot2)\nlibrary(useful)\nlibrary(coefplot)\n\nggplot(father.son, aes(fheight, sheight)) +\n geom_point() +\n geom_smooth(method=\"lm\") +\n labs(x=\"Fathers\", y=\"Sons\")\n\nheights_lm <- lm(sheight ~ fheight, data=father.son)\nsummary(heights_lm)\n\n# digression into anova and different data set\ndata(tips, package=\"reshape2\")\n\ntipsAnova <- aov(tip~day-1, data=tips)\ntipsLM <- lm(tip~day-1, data=tips)\nsummary(tipsAnova)\nsummary(tipsLM)\n# LM has more information than Anova and thus is preferred\n\n# Explore the data for multiple regression, predict one variable on multiple variables\n# get some data from website\nhousing <- read.table(\"http://www.jaredlander.com/data/housing.csv\", sep = \",\", header = TRUE, stringsAsFactors = FALSE)\n# clean up col names\nnames(housing) <- c(\"Neighborhood\", \"Class\", \"Units\", \"Years_Built\", \"SqFt\", \"Income\", \"IncomePerSqFt\",\n \"Expense\", \"ExpensePerSqFt\", \"NetIncome\", \"Value\", \"ValuePerSqFt\", \"Boro\")\n# make an exploratory viz\nggplot(housing, aes(x=ValuePerSqFt, fill=Boro, alpha=1/2)) +\n geom_histogram(binwidth=10) +\n labs(x=\"Value per sq ft\") + \n facet_wrap(~Boro)\n\nggplot(housing, aes(x=SqFt)) + \n geom_histogram()\n\nggplot(housing, aes(x=SqFt, y=ValuePerSqFt)) +\n geom_point()\n\n# see that there are very large buildings skewing results, so subset\n\nggplot(housing[housing$Units < 1000, ], aes(x=SqFt)) + \n geom_histogram()\n\nggplot(housing[housing$Units < 1000, ], aes(x=SqFt, y=ValuePerSqFt)) +\n geom_point()\n\n# right track, so determine how many units to exclude\nsum(housing$Units >= 1000)\n# yields 6, so few, so remove outliers\nhousing <- housing[housing$Units < 1000, ]\n\n# name the first model\nhouse1 <- lm(ValuePerSqFt ~ Units + SqFt + Boro, data=housing)\nsummary(house1)\n\nlibrary(coefplot)\ncoefplot(house1)\n# seek coefficients with CI > 0\n# let's try other models\nhouse2 <- lm(ValuePerSqFt ~ Units*SqFt + Boro, data=housing)\ncoefplot(house2)\n\nhouse3 <- lm(ValuePerSqFt ~ Units:SqFt, data=housing)\ncoefplot(house3)\n\nhouse4 <- lm(ValuePerSqFt ~ SqFt*Units*Income, housing)\ncoefplot(house4)\n\nhouse5 <- lm(ValuePerSqFt ~ Class*Boro, housing)\ncoefplot(house5)\n\nhouse6 <- lm(ValuePerSqFt ~ I(SqFt/Units) + Boro, housing)\ncoefplot(house6)\n\nhouse7 <- lm(ValuePerSqFt ~ I(Units + SqFt)^2, housing)\ncoefplot(house7)\n\n# plot multiple models\nmultiplot(house1, house2, house3)\n\n# now let's use a regression model for prediction\n\nhousingNew <- read.table(\"http://www.jaredlander.com/data/housingNew.csv\", sep = \",\", header = TRUE, stringsAsFactors = FALSE)\n\nhousePredict <- predict(house1, newdata=housingNew, se.fit=TRUE, interval=\"prediction\", level=0.95)\n\n# logistic regression\n# modelling a yes/no response\n\n# lets grab some data\nacs <- read.table(\"http://www.jaredlander.com/data/acs_ny.csv\", sep = \",\", header = TRUE, stringsAsFactors = FALSE)\n\nacs$Income <- with(acs, FamilyIncome >= 150000)\nnames(acs)[length(acs)] <- \"Income\" # error in names in data fixed\n\nggplot(acs) +\n aes(x=FamilyIncome) +\n geom_density(fill=\"grey\", color=\"blue\") +\n geom_vline(xintercept=150000, color=\"red\") +\n scale_x_continuous(label=multiple.dollar, limits=c(0,1000000)) +\n ggtitle(\"Density of National Income\")\n\n# fit some glms\nincome1 <- glm(Income ~ HouseCosts + NumWorkers + OwnRent +\n NumBedrooms + FamilyType, \n data=acs, family=binomial(link=\"logit\"))\n\n# summary of data and coefplot\nsummary(income1)\ncoefplot(income1)\n# shows that OwnRentOutright is the most positive coefficient in set.\n\nincome1$coefficients\n#this shows scale of coefficients is still on logit scale. want to return scale back to original for \n#further understanding.\ninvlogit <- function(x) {\n 1/(1 + exp(-x))\n}\n\ninvlogit(income1$coefficients)\n# now back on normal P scale\n\n# Poisson regression\n# models count data, number of children, accidents, errors, etc.\n\n# make a plot of number of children\nggplot(acs) +\n aes(x=NumChildren) +\n geom_histogram(binwidth=1)\n\n# appears close to poisson, so fit a glm poisson\nchildren1 <- glm(NumChildren ~ FamilyIncome + FamilyType + OwnRent,\n data=acs, family=poisson(link=\"log\"))\n\nsummary(children1)\ncoefplot(children1)\n\n# for a nice poisson fit, we need to check for overdipsersion\nz <- (acs$NumChildren - children1$fitted.values) /\n sqrt(children1$fitted.values)\nsum(z^2) / children1$df.residual\n# > 1, considered no overdispersion\n# one more test\npchisq(sum(z^2), df=children1.df)\n# does indicate overdispersion, so let's refit poisson\nchildren2 <- glm(NumChildren ~ FamilyIncome + FamilyType + OwnRent,\n data=acs, family=quasipoisson(link=\"log\"))\n\n# let us compare the two models\nmultiplot(children1, children2)\n\n\n# Analyze survival data\n\nlibrary(survival)\n\nhead(bladder)\n# in this dataset there are censored data that we need to take into account to not\n# over-fit. Need to find events (whether there was a reccurrence) and stop (if they dropped or something else).\n# event = 1 is the area of concern\n\nsurvObject <- with(bladder[100:105, ] Surv(stop, event))\n\n# fit a model to see if treatment was significant\n\ncox1 <- coxph(Surv(stop, event) ~ rx + number + size + enum, data=bladder)\nsummary(cox1)\ncoefplot(cox1)\nplot(survfit(cox1), xlab=\"Days\", ylab=\"Survival Rate\", conf.int=TRUE)\n\n# in this analysis, we have munged real and placebos together. Let's separate them\ncox2 <- coxph(Surv(stop, event) ~ strata(rx) + number + size + enum, data=bladder)\nsummary(cox2)\nplot(survfit(cox2), xlab=\"Days\", ylab=\"Survival Rate\", conf.int=TRUE, col=1:2)\nlegend(\"bottomleft\", legend=c(1,2), lty=1, col=1:2, text.col=1:2, title=\"rx\")\n\n# test proportionality\ncox.zph(cox1)\ncox.zph(cox2)\n\n# Model to predict number of events rather than just time to event\n# use a different dataset with start and stop times\nag1 <- coxph(Surv(start, stop, event) ~ rx + number + size + enum +\n cluster(id), data=bladder2)\nag2 <- coxph(Surv(start, stop, event) ~ strata(rx) + number + size + enum +\n cluster(id), data=bladder2)\nplot(survfit(ag1), conf.int = TRUE)\nplot(survfit(ag2), conf.int = TRUE, col=1:2)\nlegend(\"topright\", legend=c(1,2), lty=1, col=1:2, text.col=1:2, title=\"rx\")\n\n# assess model quality with residuals\n\n# fit a lm on housing data\nhouse1 <- lm(ValuePerSqFt ~ Units + SqFt + Boro, data=housing)\n# residual diagnostic info available with fortify function\nhead(fortify(house1))\n\nggplot(aes(x=.fitted, y=.resid), data=house1) +\n geom_point() +\n geom_hline(yintercetp = 0) +\n geom_smooth(se=FALSE) +\n labs(x=\"Fitted Values\", y=\"Residuals\") +\n geom_point(aes(color=Boro))\n# Q-Q plot\n# using base graphics\nplot(house1, which=2)\n# note that we get deviance from the straight fit, especially at the tails. Indicates a poor fit\n# recreate same plot in ggplot\nggplot(house1) +\n aes(sample=.stdresid)) +\n stat_qq() +\n geom_abline()\n\n#want residuals to be normally distributed, so lets make a histogram of them\nggplot(house1) +\n aes(x=.resid) +\n geom_histogram()\n\n#not quite as random as we would like.\n\n# lets construct several models to compare\n\nhouse1 <- lm(ValuePerSqFt ~ Units + SqFt + Boro, housing)\nhouse2 <- lm(ValuePerSqFt ~ Units * SqFt + Boro, housing)\nhouse3 <- lm(ValuePerSqFt ~ Units + SqFt * Boro + Class, housing)\nhouse4 <- lm(ValuePerSqFt ~ Units + SqFt * Boro + SqFt*Class, housing)\nhouse5 <- lm(ValuePerSqFt ~ Boro + Class, housing)\n\nmultiplot(house1, house2, house3, house4, house5, pointSize = 2)\n\n# now lets get some numerical analysis with anova\n\nanova(house1, house2, house3, house4, house5)\n\n#Low RSS is a good indicator of quality, but also could be also a problem with overfitting with multiple variables\n#Let's use AIC/BIC for multiple coefficients to penalize for complexity\n\nAIC(house1, house2, house3, house4, house5)\nBIC(house1, house2, house3, house4, house5)\n\n# Anova, AIC and BIC all point to house4\n\n# when working with glms, we don't use residuals, but rather deviance. \n# let's build up five glms and compare them with deviance.\n\nhousing$HighValue <- housing$ValuePerSqFt >= 150 # returns T/F for those observations\n\nhigh1 <- glm(HighValue ~ Units + SqFt + Boro, housing, family=binomial(link=\"logit\"))\nhigh2 <- glm(HighValue ~ Units * SqFt + Boro, housing, family=binomial(link=\"logit\"))\nhigh3 <- glm(HighValue ~ Units + SqFt * Boro + Class, housing, family=binomial(link=\"logit\"))\nhigh4 <- glm(HighValue ~ Units + SqFt * Boro + SqFt*Class, housing, family=binomial(link=\"logit\"))\nhigh5 <- glm(HighValue ~ Boro + Class, housing, family=binomial(link=\"logit\"))\n\n# now look at deviances\n\nanova(high1, high2, high3, high4, high5)\nAIC(high1, high2, high3, high4, high5)\nBIC(high1, high2, high3, high4, high5)\n\n# Now lets validate with k-fold validation\n# with a K=10, we can train on 9, test on 1, and track the errors, then rotate.\n\nlibrary(boot)\n\n# build a model\nhouseG1 <- glm(ValuePerSqFt ~ Units + SqFt + Boro, data=housing, family=gaussian(link=\"identity\"))\n\n# now cross validate\nhouseCV1 <- cv.glm(housing, houseG1, K=5)\nhouseCV1$delta #validated error and adjusted validated error\n\n# errors are similar, so we can leave out leave-1-out cross validation\n# this is useful for comparing one model to another\n\nhouseG2 <- glm(ValuePerSqFt ~ Units*SqFt + Boro, data=housing, family=gaussian(link=\"identity\"))\nhouseG3 <- glm(ValuePerSqFt ~ Units + SqFt*Boro + Class, data=housing, family=gaussian(link=\"identity\"))\nhouseG4 <- glm(ValuePerSqFt ~ Units + SqFt*Boro + SqFt*Class, data=housing, family=gaussian(link=\"identity\"))\nhouseG5 <- glm(ValuePerSqFt ~ Boro + Class, data=housing, family=gaussian(link=\"identity\"))\n\nhouseCV2 <- cv.glm(housing, houseG2, K=5)\nhouseCV3 <- cv.glm(housing, houseG3, K=5)\nhouseCV4 <- cv.glm(housing, houseG4, K=5)\nhouseCV5 <- cv.glm(housing, houseG5, K=5)\n\n# Now, with the cross validation performed and saved, lets place results in a single df for analysis\n\ncvResults <- as.data.frame(rbind(houseCV1$delta, houseCV2$delta, \n houseCV3$delta, houseCV4$delta, houseCV5$delta))\n\nnames(cvResults) <- c(\"Error\", \"Adjusted Error\")\ncvResults$Model <- sprintf(\"houseG%s\", 1:5)\n\ncvAnova <- anova(houseG1, houseG2, houseG3, houseG4, houseG5)\ncvAIC <- AIC(houseG1, houseG2, houseG3, houseG4, houseG5)\ncvBIC <- BIC(houseG1, houseG2, houseG3, houseG4, houseG5)\n\ncvResults$Anova <- cvAnova$'Resid. Dev'\ncvResults$AIC <- cvAIC$AIC\ncvResults$BIC <- cvBIC$BIC\n\ncvResults\n\n# Estimate uncertainty with Bootstrap when there is no analytic solution\n# calculate CI for batting averages\n\nlibrary(plyr)\n#subset the data\nbaseball <- baseball[baseball$year >= 1990, ]\n\nbat.avg <- function(data, indices=1:NROW(data), hits=\"h\", at.bats=\"ab\"){\n sum(data[indices, hits], na.rm=TRUE) /\n sum(data[indices, at.bats], na.rm=TRUE)\n}\n\nbat.avg(baseball)\n\n# now we need uncertainty, so load bootstrap\nlibrary(boot)\navgBoot <- boot(data=baseball, statistic=bat.avg, R=1200, stype = \"i\")\navgBoot # this gives a standard error for the distribution\n# now use bootstrap to make the CI\nboot.ci(avgBoot, conf=.95, type=\"norm\")\n# let's build up a plot of these averages with the CI as vlines\nggplot() + geom_histogram(aes(x=avgBoot$t), fill=\"grey\", color=\"grey\") +\n geom_vline(xintercept=avgBoot$t0 + c(-1,1)*2*sqrt(var(avgBoot$t)), linetype=2)\n\n# choose variables in a model with stepwise selection\n# use housing data and step function in R\n# build a simple model\nnullModel <- lm(ValuePerSqFt ~ 1, data=housing)\nfullModel <- lm(ValuePerSqFt ~ Units + SqFt*Boro + Boro*Class, housing)\nhouseStep <- step(nullModel,\n scope=list(lower=nullModel, upper=fullModel),\n direction=\"both\")\n", "meta": {"hexsha": "ffc53457bae938aadc3ad5a81f504fe2ec781e04", "size": 11811, "ext": "r", "lang": "R", "max_stars_repo_path": "C10.r", "max_stars_repo_name": "smehan/r-scratch", "max_stars_repo_head_hexsha": "5eafce3db85646df19cbacd8068c78b66ec0a351", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-01-30T20:05:46.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-30T20:05:46.000Z", "max_issues_repo_path": "C10.r", "max_issues_repo_name": "smehan/r-scratch", "max_issues_repo_head_hexsha": "5eafce3db85646df19cbacd8068c78b66ec0a351", "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": "C10.r", "max_forks_repo_name": "smehan/r-scratch", "max_forks_repo_head_hexsha": "5eafce3db85646df19cbacd8068c78b66ec0a351", "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.4344023324, "max_line_length": 126, "alphanum_fraction": 0.705190077, "num_tokens": 3522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.8962513682840824, "lm_q1q2_score": 0.8119946252700283}} {"text": "#criar funcao que retorne a soma dos divisores proprios de um numero\nsomaDivisoresProprios <- function(n) {\n soma = 0\n for(i in 1:(n-1)) {\n if(n%%i == 0) {\n print(i)\n soma = soma + i\n }\n }\n return(soma)\n} \n\nnumeroPerfeito <- function(n) {\n if(somaDivisoresProprios(n) == n) {\n return(TRUE)\n } else {\n return(FALSE)\n }\n}\n\nnumerosAmigos <- function(a, b) {\n if(somaDivisoresProprios(a) == b & somaDivisoresProprios(b) == a) {\n return(TRUE)\n } else {\n return(FALSE)\n }\n}", "meta": {"hexsha": "4054aad7d421215266891c43fae7030d94db32f2", "size": 505, "ext": "r", "lang": "R", "max_stars_repo_path": "resolucao/r/funcoes_divisores.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/funcoes_divisores.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/funcoes_divisores.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": 18.7037037037, "max_line_length": 69, "alphanum_fraction": 0.5920792079, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.8115680615180388}} {"text": "################################################################################\r\n#This function calculates extraterrestrial solar radiation (radiation at the top\r\n#of the earth's atmosphere, aka insolation) from day of the year and latitude.\r\n#It is calculated separately for each day of the year.\r\n#NB: Latitude should be in radians (not degrees).\r\n#NB: Non-real values are produced for w (sunset hour angle) at times of the year\r\n#and at latitudes where the sun never rises or sets. However, it makes sense to\r\n#use just the real portion of the value, as it sets w to 0 in the winter and pi\r\n#(~3.14) in the summer. \r\n#Source: Allen et al. (1998)\r\n################################################################################\r\n\r\ncalcRa <- function(jd,lat,nrow,ncol) { #what follows is part of the function\r\n\r\n#Calculate the earth-sun distance, which is a function solely of Julian day. It is a single value for each day\r\nd <- 1+(0.033*cos(2*pi*jd/365))\r\n\r\n#Calculate declination, a function of Julian day. It is a single value for each day.\r\ndc <- 0.409*sin(((2*pi/365)*jd)-1.39)\r\n\r\n#Pre-allocate the sunset hour angle (w) matrix\r\nw <- matrix(NA,nrow,ncol)\r\n#Calculate the sunset hour angle, a function of latitude and declination. Note that at v. high latitudes, this function can produce non-real values. \r\nw[!is.na(lat)] <- as.matrix(Re(acos(as.complex(-1*tan(dc)*tan(lat[!is.na(lat)])))))\r\n\r\n#Pre-allocate the Ra matrix\r\nRa <- matrix(NA,nrow,ncol)\r\n\r\n#Calculate Ra using the above variables\r\n#S is the solar constant and is =0.082 MJ/m2min\r\nRa[!is.na(lat)] <- as.matrix((24*60/pi)*d*0.082*(w[!is.na(lat)]*sin(lat[!is.na(lat)])*sin(dc)+cos(lat[!is.na(lat)])*cos(dc)*sin(w[!is.na(lat)])))\r\nreturn(Ra)\r\n} #this closes the function\r\n\r\n", "meta": {"hexsha": "51d06d34d90788e8a68cbe555027fa1f4f43849c", "size": 1745, "ext": "r", "lang": "R", "max_stars_repo_path": "snap_scripts/baseline_climatologies/radiation/calcRa.r", "max_stars_repo_name": "ua-snap/downscale", "max_stars_repo_head_hexsha": "3fe8ea1774cf82149d19561ce5f19b25e6cba6fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-24T21:55:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T16:32:54.000Z", "max_issues_repo_path": "snap_scripts/old_scripts/tem_iem_older_scripts_april2018/tem_inputs_iem/FromSteph_and_Dave_Radiation/calcRa.r", "max_issues_repo_name": "ua-snap/downscale", "max_issues_repo_head_hexsha": "3fe8ea1774cf82149d19561ce5f19b25e6cba6fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2016-01-04T23:37:47.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-17T20:57:02.000Z", "max_forks_repo_path": "old/bin/calcRa.r", "max_forks_repo_name": "ua-snap/downscale", "max_forks_repo_head_hexsha": "3fe8ea1774cf82149d19561ce5f19b25e6cba6fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-16T04:48:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-25T03:46:00.000Z", "avg_line_length": 49.8571428571, "max_line_length": 151, "alphanum_fraction": 0.6383954155, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846684978779, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.8110210170499721}} {"text": "\n\nsieve <- function(x){\n primes <- 2\n for(i in 2:x){\n s <- ceiling(sqrt(i))\n pflag <- TRUE\n for(p in primes[primes<=s]){\n pflag <- pflag & i %% p\n }\n if(pflag){\n primes <- c(primes,i)\n }\n }\n primes\n}\n\nis_prime <- function(x){\n if(x==2){\n return(TRUE)\n }\n s <- ceiling(sqrt(x))\n primes <- sieve(s)\n for(p in primes){\n if(x %% p ==0){\n return(FALSE)\n }\n }\n return(TRUE)\n}\n\nfactorize <- function(x){\n s <- ceiling(sqrt(x))\n primes <- sieve(s)\n factorization <- c()\n while(x>1 & !is_prime(x)){\n for(p in primes){\n if(x%%p==0){\n factorization[length(factorization)+1] <- p\n x <- x/p\n }\n }\n }\n if(x==1){\n return(factorization)\n }\n c(factorization,x)\n}\n\n\n\n\n", "meta": {"hexsha": "d2bb97df706e24da82b042d8813784ca5d86b113", "size": 744, "ext": "r", "lang": "R", "max_stars_repo_path": "R/primes.r", "max_stars_repo_name": "JorgeRiescoDavila/somecrypto", "max_stars_repo_head_hexsha": "4060ec8ccfdf757b389cab1451c74572633667d6", "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/primes.r", "max_issues_repo_name": "JorgeRiescoDavila/somecrypto", "max_issues_repo_head_hexsha": "4060ec8ccfdf757b389cab1451c74572633667d6", "max_issues_repo_licenses": ["MIT"], "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/primes.r", "max_forks_repo_name": "JorgeRiescoDavila/somecrypto", "max_forks_repo_head_hexsha": "4060ec8ccfdf757b389cab1451c74572633667d6", "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.0377358491, "max_line_length": 51, "alphanum_fraction": 0.4946236559, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.8109424301268516}} {"text": "x <- c(1, 3, -5)\ny <- c(4, -2, -1)\n\nsum(x*y) # compute products, then do the sum\nx %*% y # inner product\n\n# loop implementation\ndotp <- function(x, y) {\n\tn <- length(x)\n\tif(length(y) != n) stop(\"invalid argument\")\n\ts <- 0\n\tfor(i in 1:n) s <- s + x[i]*y[i]\n\ts\n}\n\ndotp(x, y)\n", "meta": {"hexsha": "2c865049281c119c6990786d8e1f1ec0d57ee821", "size": 276, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Dot-product/R/dot-product.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/Dot-product/R/dot-product.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/Dot-product/R/dot-product.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": 16.2352941176, "max_line_length": 45, "alphanum_fraction": 0.5362318841, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.8108171596770186}} {"text": "## 1. A Review On Mutual Exclusivity ##\n\nstatement_1 <- FALSE\nstatement_2 <- TRUE\nstatement_3 <- TRUE\n\n## 2. From Conditional to Marginal ##\n\np_spam <- 0.2388\np_secret_given_spam <- 0.4802\np_secret_given_non_spam <- 0.1284\np_non_spam <- 1 - p_spam\np_spam_and_secret <- p_spam * p_secret_given_spam\np_non_spam_and_secret <- p_non_spam * p_secret_given_non_spam\np_secret <- p_spam_and_secret + p_non_spam_and_secret\n\n## 3. A General Formula ##\n\np_boeing <- 0.73\np_airbus <- 0.27\np_delay_given_boeing <- 0.03\np_delay_given_airbus <- 0.08\n\np_delay <- p_boeing*p_delay_given_boeing + p_airbus*p_delay_given_airbus\n\n## 4. Extending Our Formula ##\n\np_boeing <- 0.62\np_airbus <- 0.35\np_erj <- 0.03\np_delay_boeing <- 0.06 \np_delay_airbus <- 0.09\np_delay_erj <- 0.01\np_delay <- p_boeing*p_delay_boeing + p_airbus*p_delay_airbus + p_erj*p_delay_erj\n\n## 6. Bayes' Theorem ##\n\np_boeing <- 0.73\np_airbus <- 0.27\np_delay_given_boeing <- 0.03\np_delay_given_airbus <- 0.08\np_delay <- p_boeing*p_delay_given_boeing + p_airbus*p_delay_given_airbus\np_airbus_delay <- (p_airbus * p_delay_given_airbus) / p_delay\n\n## 7. Prior and Posterior Probability ##\n\np_spam <- 0.2388\np_secret_given_spam <- 0.4802\np_secret_given_non_spam <- 0.1284\n# Exercise 1\np_non_spam <- 1 - p_spam\np_secret <- p_spam*p_secret_given_spam + p_non_spam*p_secret_given_non_spam\np_spam_given_secret <- (p_spam*p_secret_given_spam) / p_secret\n\n# Exercise 2 and 3\nprior <- p_spam\nposterior <- p_spam_given_secret\n\n# Exercise 4\nratio <- posterior/prior", "meta": {"hexsha": "c5af93aac5c8e4ee72e394596ae242a5d61e939e", "size": 1499, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/4. Conditional Probability in R/3. Bayes Theorem.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/3. Bayes Theorem.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/3. Bayes Theorem.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": 24.9833333333, "max_line_length": 80, "alphanum_fraction": 0.7618412275, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.8577681049901036, "lm_q1q2_score": 0.8105863204286285}} {"text": "#######################################################\n### Gamma distribution with Lambda = 8, Alpha = 0.5 ###\n#######################################################\n\n\n\n## Sample the samples\nnSamples <- 10000\nlambda = 8\nalpha = 0.5\nxVal <- rgamma(nSamples, shape=lambda, rate=alpha)\n\n\n## Calculate characteristics\nxA1 <- mean(xVal) # mean\nxM2 <- mean((xVal - xA1)^2) # biased sample variance\nxS2 <- nSamples * xM2 / (nSamples - 1) # unbiased sample variance\nxSigma <- sd(xVal) # standard deviation (sqrt(m2))\nxSem <- xSigma / sqrt(nSamples) # error of mean\nxMed <- median(xVal) # median\nxMax <- max(xVal) # max value\nxMin <- min(xVal) # min value\nxQuant <- quantile(xVal) # quantiles\nxIqr <- IQR(xVal) # interquartile range\nxM3 <- mean((xVal - xA1)^3) # third central moment\nxGamma1 <- xM3 / xSigma^3 # skewness\nxM4 <- mean((xVal - xA1)^4) # forth central moment\nxGamma2 <- xM4 / xSigma^4 # kurtosis\n\n\n## Parameter estimation (moment method)\nprint('################################')\n# E[x] = lambda / alpha; D[x] = lambda^2 / alpha\nalphaEstMM <- xA1 / xS2\nlambdaEstMM <- xA1^2 / xS2\nprint(paste0('Estimated alpha (MM): ', alphaEstMM))\nprint(paste0('Estimated lambda (MM): ', lambdaEstMM))\n\n\n## Parameter estimation (maximum likelihood)\nlibrary(dglm)\nfit <- dglm(xVal~1, family=Gamma(link=\"log\"), mustart=mean(xVal))\nsummary(fit)\n\n\n\n", "meta": {"hexsha": "173e03aa612567cc6b4a4080ba71ea4cf6512ddf", "size": 1335, "ext": "r", "lang": "R", "max_stars_repo_path": "TASK1/lab1/parEst/parEst.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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": "TASK1/lab1/parEst/parEst.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TASK1/lab1/parEst/parEst.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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.4042553191, "max_line_length": 65, "alphanum_fraction": 0.6052434457, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.8104440765662736}} {"text": "\r\n\r\nybar = 380 # sample mean \r\nmu0 = 395 # hypothesized value \r\nsigma = 35.2 # population standard deviation \r\nn = 50 # sample size \r\nz = abs((ybar- mu0)/(sigma/sqrt(n)))\r\n # test statistic\r\nprint(z)\r\n# We then compute the critical value at .01 significance level.\r\nalpha = .01 \r\n# critical value\r\nz.alpha = qnorm(1-alpha) \r\nprint(z.alpha)\r\n# computing Beta for hypothesized value\r\nBeta_onetailedtest<-pnorm(z.alpha-z)\r\nprint(Beta_onetailedtest)\r\n# power for test\r\npowerfortest<-1-Beta_onetailedtest\r\nprint(powerfortest)\r\n \r\n \r\n \r\n \r\n\r\n", "meta": {"hexsha": "319684633277f941c4879b8e5e02facd8f351bae", "size": 583, "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.8/Ex5_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/CH5/EX5.8/Ex5_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/CH5/EX5.8/Ex5_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": 22.4230769231, "max_line_length": 64, "alphanum_fraction": 0.6380789022, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102514755852, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.8103221393692277}} {"text": "LISP Interpreter Run\n\n[[[[[\n\n Elementary Set Theory in LISP (finite sets) \n\n]]]]]\n\n[Set membership predicate:]\n\ndefine (member? e[lement] set)\n [Is set empty?]\n if atom set [then] false [else] \n [Is the element that we are looking for the first element?]\n if = e car set [then] true [else] \n [recursion step!]\n [return] (member? e cdr set)\n\ndefine member?\nvalue (lambda (e set) (if (atom set) false (if (= e (car\n set)) true (member? e (cdr set)))))\n\n \n(member? 1 '(1 2 3))\n\nexpression (member? 1 (' (1 2 3)))\nvalue true\n\n(member? 4 '(1 2 3))\n\nexpression (member? 4 (' (1 2 3)))\nvalue false\n\n \n[Subset predicate:]\n\ndefine (subset? set1 set2)\n [Is the first set empty?]\n if atom set1 [then] true [else]\n [Is the first element of the first set in the second set?]\n if (member? car set1 set2) \n [then] [recursion!] (subset? cdr set1 set2) \n [else] false \n\ndefine subset?\nvalue (lambda (set1 set2) (if (atom set1) true (if (memb\n er? (car set1) set2) (subset? (cdr set1) set2) fal\n se)))\n\n \n(subset? '(1 2) '(1 2 3))\n\nexpression (subset? (' (1 2)) (' (1 2 3)))\nvalue true\n\n(subset? '(1 4) '(1 2 3))\n\nexpression (subset? (' (1 4)) (' (1 2 3)))\nvalue false\n\n\n[Set union:]\n\ndefine (union x y)\n [Is the first set empty?] \n if atom x [then] [return] y [else]\n [Is the first element of the first set in the second set?]\n if (member? car x y) \n [then] [return] (union cdr x y)\n [else] [return] cons car x (union cdr x y)\n\ndefine union\nvalue (lambda (x y) (if (atom x) y (if (member? (car x) \n y) (union (cdr x) y) (cons (car x) (union (cdr x) \n y)))))\n\n\n(union '(1 2 3) '(2 3 4))\n\nexpression (union (' (1 2 3)) (' (2 3 4)))\nvalue (1 2 3 4)\n\n\n[Union of a list of sets:]\n\ndefine (unionl l) if atom l nil (union car l (unionl cdr l))\n\ndefine unionl\nvalue (lambda (l) (if (atom l) nil (union (car l) (union\n l (cdr l)))))\n\n\n(unionl '((1 2) (2 3) (3 4)))\n\nexpression (unionl (' ((1 2) (2 3) (3 4))))\nvalue (1 2 3 4)\n\n\n[Set intersection:]\n\ndefine (intersection x y)\n [Is the first set empty?]\n if atom x [then] [return] nil [empty set] [else]\n [Is the first element of the first set in the second set?]\n if (member? car x y) \n [then] [return] cons car x (intersection cdr x y)\n [else] [return] (intersection cdr x y)\n\ndefine intersection\nvalue (lambda (x y) (if (atom x) nil (if (member? (car x\n ) y) (cons (car x) (intersection (cdr x) y)) (inte\n rsection (cdr x) y))))\n\n\n(intersection '(1 2 3) '(2 3 4))\n\nexpression (intersection (' (1 2 3)) (' (2 3 4)))\nvalue (2 3)\n\n\n[Relative complement of two sets x and y = x - y:]\n\ndefine (complement x y)\n [Is the first set empty?]\n if atom x [then] [return] nil [empty set] [else]\n [Is the first element of the first set in the second set?]\n if (member? car x y) \n [then] [return] (complement cdr x y)\n [else] [return] cons car x (complement cdr x y)\n\ndefine complement\nvalue (lambda (x y) (if (atom x) nil (if (member? (car x\n ) y) (complement (cdr x) y) (cons (car x) (complem\n ent (cdr x) y)))))\n\n\n(complement '(1 2 3) '(2 3 4))\n\nexpression (complement (' (1 2 3)) (' (2 3 4)))\nvalue (1)\n\n\n\n[Cartesian product of an element with a list:]\n\ndefine (product1 e y) \n if atom y \n [then] nil \n [else] cons cons e cons car y nil (product1 e cdr y)\n\ndefine product1\nvalue (lambda (e y) (if (atom y) nil (cons (cons e (cons\n (car y) nil)) (product1 e (cdr y)))))\n\n\n(product1 3 '(4 5 6))\n\nexpression (product1 3 (' (4 5 6)))\nvalue ((3 4) (3 5) (3 6))\n\n\n[Cartesian product of two sets = set of ordered pairs:]\n\ndefine (product x y)\n [Is the first set empty?]\n if atom x [then] [return] nil [empty set] [else]\n [return] (union (product1 car x y) (product cdr x y))\n\ndefine product\nvalue (lambda (x y) (if (atom x) nil (union (product1 (c\n ar x) y) (product (cdr x) y))))\n\n\n(product '(1 2 3) '(x y z))\n\nexpression (product (' (1 2 3)) (' (x y z)))\nvalue ((1 x) (1 y) (1 z) (2 x) (2 y) (2 z) (3 x) (3 y) (\n 3 z))\n\n\n[Product of an element with a list of sets:]\n\ndefine (product2 e y) \n if atom y \n [then] nil \n [else] cons cons e car y (product2 e cdr y)\n\ndefine product2\nvalue (lambda (e y) (if (atom y) nil (cons (cons e (car \n y)) (product2 e (cdr y)))))\n\n\n(product2 3 '((4 5) (5 6) (6 7)))\n\nexpression (product2 3 (' ((4 5) (5 6) (6 7))))\nvalue ((3 4 5) (3 5 6) (3 6 7))\n\n\n[Set of all subsets of a given set:]\n\ndefine (subsets x)\n if atom x \n [then] '(()) [else]\n let y [be] (subsets cdr x) [in]\n (union y (product2 car x y))\n\ndefine subsets\nvalue (lambda (x) (if (atom x) (' (())) ((' (lambda (y) \n (union y (product2 (car x) y)))) (subsets (cdr x))\n )))\n\n\n(subsets '(1 2 3))\n\nexpression (subsets (' (1 2 3)))\nvalue (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3))\n\nlength (subsets '(1 2 3))\n\nexpression (length (subsets (' (1 2 3))))\nvalue 8\n\n(subsets '(1 2 3 4))\n\nexpression (subsets (' (1 2 3 4)))\nvalue (() (4) (3) (3 4) (2) (2 4) (2 3) (2 3 4) (1) (1 4\n ) (1 3) (1 3 4) (1 2) (1 2 4) (1 2 3) (1 2 3 4))\n\nlength (subsets '(1 2 3 4))\n\nexpression (length (subsets (' (1 2 3 4))))\nvalue 16\n\nEnd of LISP Run\n\nElapsed time is 0 seconds.\n", "meta": {"hexsha": "8de3b6b48fe5d936f172a7e6bbdc3db13e03800b", "size": 5486, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/sets.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/sets.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/sets.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 23.1476793249, "max_line_length": 62, "alphanum_fraction": 0.5413780532, "num_tokens": 1945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739774, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.8101458337879546}} {"text": "# Example : 1 Chapter : 6.4 Page No: 331\r\n# Eigen Values and Eigen vectors of A\r\nA<-matrix(c(1,2,2,4),ncol=2)\r\nlambda<-eigen(A)$values\r\nx<-eigen(A)$vectors #These are Normalised eigen vectors\r\n#to get eigen vectors in textbook\r\nx[,1]<-x[,1]*(1/x[1,1])\r\nx[,2]<-x[,2]*(2/x[1,2])\r\nprint(\"Eigen values and eigen vectors of respective eigen values of A\")\r\nprint(lambda)\r\nprint(x)\r\n#The answer may slightly vary due to rounding off values\r\n#The answers provided in the text book may vary because of the computation process\r\n#Both answers are correct , here it is taken -Ax+b=0 , In the text book it is considered as Ax-b=0\r\n", "meta": {"hexsha": "9baefa7d9ce21bd5be4171733a31d7e72e11d4db", "size": 626, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.4.1/Ex6.4_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/CH6/EX6.4.1/Ex6.4_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/CH6/EX6.4.1/Ex6.4_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": 41.7333333333, "max_line_length": 99, "alphanum_fraction": 0.696485623, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.8100798249629514}} {"text": "# the 95% confidence level would imply the 97.5th percentile of the normal distribution at the upper tail\r\nzstar <-qnorm(.975)\r\n# standard deviation\r\n sd <- 125\r\n # level of accuracy\r\n E <- 25\r\nsample_size<- zstar^2 * sd * sd/ E^2\r\n print(ceiling(sample_size))\r\n # A sample size of 97 or larger is recommended to obtain an estimate of the mean textbook\r\n ", "meta": {"hexsha": "556b3a5781206041a7c50654058c097796d66d67", "size": 358, "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.3/Ex5_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/CH5/EX5.3/Ex5_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/CH5/EX5.3/Ex5_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": 35.8, "max_line_length": 107, "alphanum_fraction": 0.7122905028, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.8100798191351551}} {"text": "integrate.rect <- function(f, a, b, n, k=0) {\n #k = 0 for left, 1 for right, 0.5 for midpoint\n h <- (b-a)/n\n x <- seq(a, b, len=n+1)\n sum(f(x[-1]-h*(1-k)))*h\n}\n\nintegrate.trapezoid <- function(f, a, b, n) {\n h <- (b-a)/n\n x <- seq(a, b, len=n+1)\n fx <- f(x)\n sum(fx[-1] + fx[-length(x)])*h/2\n}\n\nintegrate.simpsons <- function(f, a, b, n) {\n h <- (b-a)/n\n x <- seq(a, b, len=n+1)\n fx <- f(x)\n sum(fx[-length(x)] + 4*f(x[-1]-h/2) + fx[-1]) * h/6\n}\n\nf1 <- (function(x) {x^3})\nf2 <- (function(x) {1/x})\nf3 <- (function(x) {x})\nf4 <- (function(x) {x})\n\nintegrate.simpsons(f1,0,1,100) #0.25\nintegrate.simpsons(f2,1,100,1000) # 4.60517\nintegrate.simpsons(f3,0,5000,5000000) # 12500000\nintegrate.simpsons(f4,0,6000,6000000) # 1.8e+07\n\nintegrate.rect(f1,0,1,100,0) #TopLeft 0.245025\nintegrate.rect(f1,0,1,100,0.5) #Mid 0.2499875\nintegrate.rect(f1,0,1,100,1) #TopRight 0.255025\n\nintegrate.trapezoid(f1,0,1,100) # 0.250025\n", "meta": {"hexsha": "7ed1885b7f76f258817f0630ada7fb001c41bd98", "size": 924, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Numerical-integration/R/numerical-integration.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/Numerical-integration/R/numerical-integration.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/Numerical-integration/R/numerical-integration.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.972972973, "max_line_length": 53, "alphanum_fraction": 0.5854978355, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298657, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.8099268372400397}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Goodness of Fit - Exercise 13\n\n\nrm(list = ls())\n\n\nobserved <- c(1, 10, 20, 36, 23, 10)\n\n(k <- length(observed))\n# 6\n\n(n <- sum(observed))\n# 100\n\n## common p = 0.5\n\n(expected.equilibred <- n * dbinom(0:(k - 1), size = k - 1, prob = 0.5))\n# 3.125 15.625 31.25 31.25 15.625 3.125\n\n(Q.equilibred <- sum((observed - expected.equilibred) ^ 2 / expected.equilibred))\n# 26.848\n\n(pvalue.equilibred <- 1 - pchisq(Q.equilibred, k - 1))\n# 6.10645404716115e-05\n\n## common p\n\n(p.hat <- sum(observed * 0:(k - 1)) / (n * (k - 1)))\n# 0.6\n\n(expected.common <- n * dbinom(0:(k - 1), size = k - 1, prob = p.hat))\n# 1.024 7.68 23.04 34.56 25.92 7.776\n\n\n(Q.common <- sum((observed - expected.common) ^ 2 / expected.common))\n# 2.12753986625515\n\n(pvalue.common <- 1 - pchisq(Q.common, (k - 1) - 1))\n# 0.712314637750688\n", "meta": {"hexsha": "66177cbb5e874362c611dc2fdcc778ce24cf8c60", "size": 862, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/goodness-of-fit/exercise-13.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-13.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-13.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.0243902439, "max_line_length": 82, "alphanum_fraction": 0.6044083527, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.8098019260590626}} {"text": "p_d1=0.028\r\np_d2=0.012\r\np_d3=0.032\r\np_d4=0.928\r\np_a4_d1=0.02\r\np_a4_d2=0.09\r\np_a4_d3=0.10\r\np_a4_d4=0.95\r\n# the probabilities that the board has no defect or a D1, D2, or D3 type of defect\r\np_nodefect_or_d1=(p_d1*p_a4_d1)/((p_d1*p_a4_d1)+(p_d2*p_a4_d2)+(p_d3*p_a4_d3)+(p_d4*p_a4_d4))\r\nprint(p_nodefect_or_d1)\r\n\r\np_nodefect_or_d2=(p_d2*p_a4_d2)/((p_d1*p_a4_d1)+(p_d2*p_a4_d2)+(p_d3*p_a4_d3)+(p_d4*p_a4_d4))\r\nprint(p_nodefect_or_d2)\r\n\r\np_nodefect_or_d3=(p_d3*p_a4_d3)/((p_d1*p_a4_d1)+(p_d2*p_a4_d2)+(p_d3*p_a4_d3)+(p_d4*p_a4_d4))\r\nprint(p_nodefect_or_d3)\r\n\r\np_nodefect_or_d4=(p_d4*p_a4_d4)/((p_d1*p_a4_d1)+(p_d2*p_a4_d2)+(p_d3*p_a4_d3)+(p_d4*p_a4_d4))\r\nprint(p_nodefect_or_d4)\r\n", "meta": {"hexsha": "a26285bce94d2931010188ee789eeb095b0a1acb", "size": 675, "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.4/Ex4_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/CH4/EX4.4/Ex4_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/CH4/EX4.4/Ex4_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.1428571429, "max_line_length": 94, "alphanum_fraction": 0.7437037037, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.8459424450764199, "lm_q1q2_score": 0.8098019248249039}} {"text": "\r\nx=c(14.6, 14.8, 15.2, 15.7, 17.0, 17.5, 17.3, 16.8, 15.4, 15.0, 14.4, 14.5, 15.0, 15.1, 15.0, 14.9, 14.6, 13.9, 13.8, 13.5, 13.1, 13.0, 13.1, 13.0, 12.8, 12.3, 11.9, 11.7, 11.5, 11.3, 10.9, 10.8, 10.6, 10.6, 10.1, 9.7, 9.3, 9.6, 9.7, 9.9, 10.0, 9.7, 9.10, 8.60, 8.0, 7.55, 7.3, 7.70, 8.00, 8.40, 8.90, 9.80) \r\ny=c(14.7, 12.3, 11.0, 10.2, 8.20, 6.70, 6.60, 6.80, 8.30, 8.80, 9.10, 8.80, 6.30, 5.50, 5.00, 4.70, 4.60, 5.40, 5.80, 6.90, 8.20, 7.60, 5.2, 4.50, 4, 4.2, 5.70, 7.00, 7.80, 8.30, 7.30, 6.70, 5.50, 5.50, 4.60, 4.4, 5.5, 7.2, 7.8, 8.60, 9.40, 10.0, 10.7, 9.9, 9.25, 9.1, 9.3, 11.7, 12.3, 13.0, 13.7, 15.5) \r\n\r\n\r\nplot(x,-y, pch=19, cex=1, col = \"red\", asp=1,xlab=\"X\", ylab=\"Y\", main=\"Diagrama \")\r\n\r\nInterpolacion <- function(x,y) {\r\n \r\n a = rep(y)\r\n n = length(x)\r\n \r\n h <- (c(x,0) - c(0,x))[2:n]\r\n alph <- (3/c(1,h,1,1)*(c(a,1,1) - c(1,a,1)) - 3/c(1,1,h,1)*(c(1,a,1)-c(1,1,a)))[3:n]\r\n \r\n A <- c(1,rep(0,times=n-1))\r\n for (i in 1:(n-2)) {\r\n A <- rbind(A,c( rep(0,times=i-1) , c(h[i],2*(h[i]+h[i+1]),h[i+1]) , rep(0,times=n-i-2) ) )\r\n }\r\n \r\n A <- rbind(A,c(rep(0,times=n-1),1))\r\n b <- c(0,alph,0)\r\n c <- solve(A, b)\r\n \r\n b <- ((c(a,0) - c(0,a))/c(1,h,1) - c(1,h,1)/3*(c(c,0) + 2*c(0,c)))[2:n]\r\n d <- ((c(c,0) - c(0,c))/(3*c(1,h,1)))[2:n]\r\n ans = rbind(a[1:n-1],b,c[1:n-1],d)\r\n}\r\n\r\ndraw <- function(x,y) {\r\n t = 1:length(x)\r\n sx = Interpolacion(t,x)\r\n sy = Interpolacion(t,y)\r\n \r\n for (i in 1:(length(t)-1)) {\r\n dat<- data.frame(t=seq(t[i],t[i+1], by=0.1) )\r\n fx <- function(x) (sx[1,i] + sx[2,i]*(x-t[i]) + sx[3,i]*(x-t[i])^2 + sx[4,i]*(x-t[i]))\r\n fy <- function(x) (sy[1,i] + sy[2,i]*(x-t[i]) + sy[3,i]*(x-t[i])^2 + sy[4,i]*(x-t[i]))\r\n \r\n dat$y=fy(dat$t)\r\n dat$x=fx(dat$t)\r\n points(dat$x,dat$y,type='l', col='red')\r\n }\r\n}\r\ndraw(x,-y)\r\n", "meta": {"hexsha": "7d9a38ab6c4561000c3c56f4b7aa2ed4f2717d2b", "size": 1904, "ext": "r", "lang": "R", "max_stars_repo_path": "mano.r", "max_stars_repo_name": "oscartorres098/Interpolacion", "max_stars_repo_head_hexsha": "9b7503ec8775c8323e0df4aed9c2ba7c5eb5f7ec", "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": "mano.r", "max_issues_repo_name": "oscartorres098/Interpolacion", "max_issues_repo_head_hexsha": "9b7503ec8775c8323e0df4aed9c2ba7c5eb5f7ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mano.r", "max_forks_repo_name": "oscartorres098/Interpolacion", "max_forks_repo_head_hexsha": "9b7503ec8775c8323e0df4aed9c2ba7c5eb5f7ec", "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.3913043478, "max_line_length": 414, "alphanum_fraction": 0.4222689076, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.8098019180137124}} {"text": "# Computing binomial normal marginal\n# using 16-point Gaussian quadrature\n\nxi<- c(.0950125098,.2816035507,.4580167776,.6178762444,\n .7554044083,.8656312023,.9445750230,.9894009439)\nxi<- c(-xi[8:1],xi)\nwi<- c(.1894506104,.1826034150,.1691565193,.1495959888,\n .1246289712,.0951585116,.0622535239,.0271524594)\nwi<- c(wi[8:1],wi)\n\ndbinorm<- function(x,n,p,sig){\n th <- log(p/(1-p))\n u<- xi*4*sig\n pu <- exp(th+u)/(1+exp(th+u))\n pu<- ifelse(pu1-exp(-25),1-exp(-25),pu)\n probu<- dbinom(x,n,pu)*dnorm(u,0,sig)\n 4*sig*sum(wi*probu)\n }\n\n# 32-point gaussian quadrature\n\ndbinorm32<- function(x,n,p,sig){\nxi<- c(.0483076656,.1444719615,.2392873622,.3318686022, \n .4213512761,.5068999089,.5877157572,.6630442669, \n .7321821187,.7944837959,.8493676137,.8963211557, \n .9349060759,.9647622555,.9856115115,.9972638618)\n xi<- c(-xi[16:1],xi)\nwi<- c(.0965400885,.0956387200,.0938443990,.0911738786, \n .0876520930,.0833119242,.0781938957,.0723457941, \n .0658222227,.0586840934,.0509980592,.0428358980, \n .0342738629,.0253920653,.0162743947,.0070186100)\n wi<- c(wi[16:1],wi)\nth <- log(p/(1-p))\n u<- xi*4*sig\npu <- exp(th+u)/(1+exp(th+u))\n pu<- ifelse(pu1-exp(-25),1-exp(-25),pu)\n probu<- dbinom(x,n,pu)*dnorm(u,0,sig)\n 4*sig*sum(wi*probu)\n }\n\n# example:\nxprob<-NULL\nfor (i in 0:16){\n a<- dbinorm32(i,16,0.5,4)\n xprob<- c(xprob,a)\n}\n#plot(xprob,ylim=c(0,.25))\n\n\n", "meta": {"hexsha": "a438ef1022cf6a258d83e29dd09b0e5c2445cf3e", "size": 1509, "ext": "r", "lang": "R", "max_stars_repo_path": "R/LKPACK/binormal.r", "max_stars_repo_name": "covuworie/in-all-likelihood", "max_stars_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "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/LKPACK/binormal.r", "max_issues_repo_name": "covuworie/in-all-likelihood", "max_issues_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:53:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T20:16:17.000Z", "max_forks_repo_path": "R/LKPACK/binormal.r", "max_forks_repo_name": "covuworie/in-all-likelihood", "max_forks_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-21T10:24:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T10:24:59.000Z", "avg_line_length": 29.0192307692, "max_line_length": 60, "alphanum_fraction": 0.6361829026, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.8097712632000157}} {"text": "# ......................................................................................\n# ................Exercise 9. Confidence Interval estimates (one sample) ...............\n# ................Michal Béreš, Martina Litschmannová, Veronika Kubíčková...............\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# Demonstration - what is interval estimation? ####\n# \n# Consider a random variable following the normal distribution with a mean value of\n# $\\mu$ and a standard deviation of $\\sigma$. We will work with selections from this\n# random variable and using them we try to estimate the mean value of the\n# distribution(here we know its true value, but in practice its value is unknown).\n\n\nn = 30 # selection size\nmu = 100 # mean value\nsigma = 10 # st. deviation\n\n# simulation of random selection from a given random variable\nsample = rnorm(n = n, mean = mu, sd = sigma)\n\nX = mean(sample) # sampling average as a point estimate\nS = sd(sample) # st. dev. of the sample\nX\nS\n\n# For clarity, we can visualize the selection.\n# \n\n\nhist(sample)\nboxplot(sample)\n\n# ** The construction of the confidence interval estimation using a selection ####\n# characteristic\n# \n# We will use this selection characteristic:(we assume that we do not know any real\n# parameters of the distribution, only that it is following the normal distribution)\n# \n# $Y=\\frac{\\bar X - \\mu}{S}\\sqrt{n} \\sim t_{n-1}$Since we know the distribution of\n# Y, we are able to compute $a$ a $b$ in the following expression:$P(a\\frac{9}{p(1-p)}$\n# - we have a lot of different options: \n# - Clopper - Pearson estimate(binom.test) **preferred one**\n# - does not take data as a parameter, but the number of successes and the\n# number of observations\n# - Wald's - from selection characteristics using normal distribution\n\n\npi = 0.3\nn = 60\nalpha = 0.05\nsample = runif(n = n, min = 0, max = 1) < pi\n\n# verification of assumptions\np = mean(sample)\np\n9/(p*(1-p))\n\n# point estimate\np\n# Clopper - Pearson interval estimation\nsample_size = length(sample)\nn_successes = sum(sample)\nbinom.test(x = n_successes, n = sample_size, alternative = 'two.sided', \n conf.level = 1 - alpha)$conf.int\n\n# Wald's interval estimation\ndol_q = qnorm(alpha/2)\nhor_q = qnorm(1-alpha/2)\n\np - hor_q*sqrt(p*(1-p)/n) # lower IO limit\np - dol_q*sqrt(p*(1-p)/n) # upper IO limit\n\n\n# Calculation of the 11 most frequently used confidence intervals param. bin. distribution\n# using binom package\n# install.packages(\"binom\")\nbinom::binom.confint(n = sample_size, x = n_successes)\n\n# Examples ####\n\n\n# we may need theese\nlibrary(dplyr)\nlibrary(rstatix)\n\n# \n# * Example 1. ####\n# \n# During control tests of 16 light bulbs, an estimate of the mean value of $\\bar\n# x$=3,000 hours and the standard deviation s=20 hours of their service life were\n# determined. Assuming that the lamp life has a normal distribution, determine a 90%\n# interval estimate for the mean value µ.\n# \n\n\n# We estimate the mean value of the lamp life\n# Part of the input is information about data normality\n\nn = 16 # sample size\nx.bar = 3000 # hours.... average(point estimate of mean value)\ns = 20 # hours.... sample standard deviation(point estimate of standard deviation)\nalpha = 0.1 # significance level(reliability 1-alpha=0.9)\n\n\n# two sided interval estimate of the mean\ndol_q = qt(alpha/2,n-1)\nhor_q = qt(1 - alpha/2,n-1)\n\nx.bar - hor_q*s/sqrt(n) # lower limit of IO\nx.bar - dol_q*s/sqrt(n) # upper limit of IO\n\n\n# * Example 2. ####\n# \n# The depth of the sea is measured with an instrument whose systematic error is zero and\n# the random errors have a normal distribution with a standard deviation of 20 m. How\n# many measurements do we need to take if we need 95% confidence interval of maximum\n# size 20m = $<\\overline{X}-10,\\overline{X}+10>$.\n# \n\n\n# Remember:\n# \n# Confidence interval have the form of: $P(\\bar X - z_{1-\\alpha /\n# 2}\\frac{S}{\\sqrt{n}}<\\mu<\\bar X - z_{\\alpha / 2}\\frac{S}{\\sqrt{n}})\\geq 1 - \\alpha$\n\n\n# We determine the estimate of the required selection range(number of required measurements)\n\n# We assume data normality, with known variance(according to assignment)\n\nsigma = 20 # meters.... known standard deviation\nalpha = 0.05 # significance level(reliability 1-alpha=0.95)\ndelta = 10 # meters... permissible measurement error\n\n# Estimate selection range\n# we need to find n such z*S/sqrt(n)>10, \n# where z is 1-alpha/2 quantile of the normal distribution\nz_alpha = qnorm(1 - alpha/2,0,1)\n(z_alpha*sigma/delta)^2 \n\n# * Example 3. ####\n# \n# Suppose that in a random selection of 200 young men, 120 of them have higher than\n# recommended serum cholesterol levels. Determine a 95% confidence interval for the\n# percentage of young men with higher cholesterol levels in the population.\n# \n\n\n# We estimate the proportion of men with higher cholesterol levels in the entire population,\n# ie the probability that a randomly selected man will have a higher cholesterol level\n\nn = 200 # file range\nx = 120 # number of \"successes\"\np = x/n # relative frequency(probability point estimate)\np\nalpha = 0.05 # significance level(reliability 1-alpha=0.95)\n\n# Verification of assumptions\n9/(p*(1-p))\n\n# two sided Clopper - Pearson(exact) int. Estimate param. binom. distribution\nbinom.test(x,n,alternative=\"two.sided\",conf.level=0.95)$conf.int\n\n# * Example 4. ####\n# \n# In a research study, we are working with a random selection of 70 women from the Czech\n# population. Hemoglobin was measured in each of the women with an accuracy of 0.1 g/100\n# ml. The measured values are listed in the Hemoglobin.xls file. Find 95% interval\n# estimates of standard deviation and mean hemoglobin in the population of Czech\n# women.(Check the normality based on the exploration graphs.)\n# \n\n\n# We estimate the mean and standard deviation of hemoglobin in serum\n\n# Read data from xlsx file(using readxl package)\nhem = readxl::read_excel(\"data/intervalove_odhady.xlsx\",\n sheet = \"Hemoglobin\")\nhead(hem)\n\n# lets rename the column for easier work\ncolnames(hem) = \"value\"\n\n# Exploratory analysis\nboxplot(hem$value)\n# no outliers\n\n# Verification of normality - exploratory\nqqnorm(hem$value)\nqqline(hem$value)\n\nmoments::skewness(hem$value)\nmoments::kurtosis(hem$value) - 3\n# Both skew and sharpness meet the standards. distribution.\n\n# normality verification: exact - normality test.\n# Shapirs. Wilk's test.\nshapiro.test(hem$value)$p.value\n# we cannot reject normality at significance 0.05\n\n# 95% two sided interval estimate of the mean\nmean(hem$value)\nt.test(hem$value, altarnative=\"two.sided\", conf.level=0.95)$conf.int\n\n# # 95% two-way interval standard deviation estimate\nsd(hem$value)\nsqrt(EnvStats::varTest(hem$value, alternative = \"two.sided\", conf.level = 0.95)$conf.int)\n\n# * Example 5. ####\n# \n# In the data file pr7.xlsx you will find the measurement of noise caused by the\n# computer fan [dB]. Calculate the 95% interval estimate of the average noise and the\n# 95% interval estimate of the noise variability.\n# \n\n\n# read data\ndata = readxl::read_excel(\"data/pr7.xlsx\")\nhead(data)\n\n# visualization\nboxplot(data$dB)\n# there is an outlier!!\n\n# removal of OP\noutliers = data %>% identify_outliers(dB)\noutliers\n\ndata$dB_no_outliar = ifelse(data$ID %in% outliers$ID,NA,data$dB)\n\nboxplot(data$dB_no_outliar)\n\n# data normality test exploratory\nmoments::skewness(data$dB_no_outliar, na.rm = TRUE)\nmoments::kurtosis(data$dB_no_outliar, na.rm = TRUE) - 3\n\nqqnorm(data$dB_no_outliar)\nqqline(data$dB_no_outliar)\n\n# normality test exactly\nshapiro.test(data$dB_no_outliar)$p.value\n\n# point and interval estimation of the mean\nmean(data$dB_no_outliar, na.rm = TRUE)\n\nt.test(data$dB_no_outliar, alternative = \"two.sided\", conf.level = 0.95)$conf.int\n\n# point and interval estimation of the standard deviation\nsd(data$dB_no_outliar, na.rm = TRUE)\n\nres = EnvStats::varTest(data$dB_no_outliar,alternative = \"two.sided\", conf.level = 0.95)\nsqrt(res$conf.int)\n\n# * Example 6. ####\n# \n# In the data file pr8.xlsx you will find the measurement of the time to failure of the\n# electrical component [h]. Calculate the 99% interval estimate of the average life of a\n# given component type.\n# \n\n\n# read data\ndata = readxl::read_excel(\"data/pr8.xlsx\")\nhead(data)\n\n# visualization and verification of OP\nboxplot(data$cas_h)\n# there is an outliar, but is it really \"bad\" value?\n# cannot we assume that the data came from exponential dist.?\n\nhist(data$cas_h)\n# looks very likeli as exponential distr. \n# we keep the outliar as its not really outliar\n# we already know we dont have normality and symmetry\n\n# data normality test exploratory\nmoments::skewness(data$cas_h)\nmoments::kurtosis(data$cas_h) - 3\n\nqqnorm(data$cas_h)\nqqline(data$cas_h)\n\n# median point and interval estimation\nmedian(data$cas_h)\n# IO\n# install.packages(\"BSDA\")\nalpha = 0.01\nBSDA::SIGN.test(data$cas_h, alternative = 'two.sided', conf.level = 1-alpha, \n conf.int = TRUE)$conf.int\n\n# * Example from slides - 2 ####\n# Company FactoryX produces packages with cocoa. The weight (in grams) of a randomly\n# chosen packages is recorded in the dataset (cocoa.csv). Perform EDA and the two-sided\n# 95% confidence interval for the mean weight of the packages from the whole production\n# (or for median if necessary).\n\n\ndata = read.csv2(\"data/cocoa.csv\")\nhead(data)\n\nboxplot(data$weight)\n\nshapiro.test(data$weight)\n\nt.test(data$weight, alternative = \"two.sided\")\n\n# * Example from slides - 3 ####\n# Let's assume, that 30 out of 100 asked students in our university are smokers. What is\n# the two-sided 95% confidence interval of the proportion of smokers among all\n# university students? (The source data are also available in smokers.csv.)\n\n\ndata = read.csv2(\"data/smokers.csv\")\nhead(data)\n\ntab = table(data$Smokers)\ntab\n\nn = sum(tab)\nn\nx = tab['Y']\nx\n\np = x/n\np\n9/(p*(1-p))\n\nbinom.test(x,n,alternative=\"two.sided\",conf.level=0.95)\n\n# * Example from slides - 4 ####\n# The hospital observed 50 patients with lung cancer and recorded their survival time in\n# years (time.csv). Find the left-sided 95% confidence interval for the mean time of\n# survival (or for median if necessary).\n\n\ndata = read.csv2(\"data/time.csv\")\nhead(data)\n\nboxplot(data$values)\n\nshapiro.test(data$values)\n\nmoments::skewness(data$values)\nhist(data$values)\n# no normality, but we can assume symmetry\n\nmedian(data$values)\nwilcox.test(data$values,alternative = \"greater\",conf.int = TRUE, conf.level = 0.95)$conf.int\n\n", "meta": {"hexsha": "721cf3562b55d3fbc6e8fcc440c232760d7d53e7", "size": 18150, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 9/T11_Confidence_intervals.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 9/T11_Confidence_intervals.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 9/T11_Confidence_intervals.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.8519736842, "max_line_length": 92, "alphanum_fraction": 0.6937741047, "num_tokens": 5062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.8095102308600195}} {"text": "# Example : 3 Chapter : 7.3 Page No: 402\n# Polar Decomposition\nA<-matrix(c(2,-1,2,1),ncol=2)\nQ<-round(svd(A)$u)%*%t(svd(A)$v)\nH<-t(Q)%*%A\nprint(\"Polar Decomposition A=QH\")\nprint(\"Q is \")\nprint(Q)\nprint(\"H is \")\nprint(H)\n#The answer may slightly vary due to rounding off values\n#The answers provided in the text book may vary because of the computation method followed.\n", "meta": {"hexsha": "8a7369ce0dc7df84b7e73c10d2ded698b2eca121", "size": 377, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH7/EX7.3.3/Ex7.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/CH7/EX7.3.3/Ex7.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/CH7/EX7.3.3/Ex7.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": 29.0, "max_line_length": 91, "alphanum_fraction": 0.6816976127, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004808, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.8095059556442837}} {"text": "set.seed(21)\nx <- seq(1, 40, 1)\nrep = 100\nslope <- c(rep)\nfor (i in 1:rep) {\n y <- 2 * x + 1 + 5 * rnorm(length(x))\n reg <- lm(y ~ x)\n slope[i] <- summary(reg)$coefficients[2, 1]\n}\n\npar(mfrow=c(1,2))\n\nhist(slope, freq =FALSE)\nx_app <- cbind(rep(1, 40), x)\nsd_beta <- sqrt(solve(t(x_app) %*% x_app)[2, 2] * 25)\nprint(sd_beta)\nlines(seq(1.7,2.3,by=0.01),dnorm(seq(1.7,2.3,by=0.01),mean=2.,sd=sd_beta))\n\nmean_slope <- mean(slope)\nstd_slope <- sd(slope)\nprint(mean_slope)\nprint(std_slope)\n\n\nfor (i in 1:rep) {\n y <- 2 * x + 1 + 5 * (1-rchisq(length(x), df=1))/sqrt(2)\n reg <- lm(y ~ x)\n slope[i] <- summary(reg)$coefficients[2, 1]\n}\n\n\nhist(slope, freq =FALSE)\nx_app <- cbind(rep(1, 40), x)\nsd_beta <- sqrt(solve(t(x_app) %*% x_app)[2, 2] * 25)\nprint(sd_beta)\nlines(seq(1.7,2.3,by=0.01),dnorm(seq(1.7,2.3,by=0.01),mean=2.,sd=sd_beta))\n\nmean_slope <- mean(slope)\nstd_slope <- sd(slope)\nprint(mean_slope)\nprint(std_slope)", "meta": {"hexsha": "774aad6cf9373562b2e8b4472aaba90c06f3daec", "size": 936, "ext": "r", "lang": "R", "max_stars_repo_path": "Computational_Statistics/Exercices/1_4.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/1_4.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/1_4.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": 22.8292682927, "max_line_length": 74, "alphanum_fraction": 0.5993589744, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.8095059511362619}} {"text": "## Plotting Ulam spiral (for primes) 2/12/17 aev\n## plotulamspirR(n, clr, fn, ttl, psz=600), where: n - initial size;\n## clr - color; fn - file name; ttl - plot title; psz - picture size.\n##\nrequire(numbers);\nplotulamspirR <- function(n, clr, fn, ttl, psz=600) {\n cat(\" *** START:\", date(), \"n=\",n, \"clr=\",clr, \"psz=\", psz, \"\\n\");\n if (n%%2==0) {n=n+1}; n2=n*n;\n x=y=floor(n/2); xmx=ymx=cnt=1; dir=\"R\";\n ttl= paste(c(ttl, n,\"x\",n,\" matrix.\"), sep=\"\", collapse=\"\");\n cat(\" ***\", ttl, \"\\n\");\n M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);\n for (i in 1:n2) {\n if(isPrime(i)) {M[x,y]=1};\n if(dir==\"R\") {if(xmx>0) {x=x+1;xmx=xmx-1}\n else {dir=\"U\";ymx=cnt;y=y-1;ymx=ymx-1}; next};\n if(dir==\"U\") {if(ymx>0) {y=y-1;ymx=ymx-1}\n else {dir=\"L\";cnt=cnt+1;xmx=cnt;x=x-1;xmx=xmx-1}; next};\n if(dir==\"L\") {if(xmx>0) {x=x-1;xmx=xmx-1}\n else {dir=\"D\";ymx=cnt;y=y+1;ymx=ymx-1}; next};\n if(dir==\"D\") {if(ymx>0) {y=y+1;ymx=ymx-1}\n else {dir=\"R\";cnt=cnt+1;xmx=cnt;x=x+1;xmx=xmx-1}; next};\n };\n plotmat(M, fn, clr, ttl,,psz);\n cat(\" *** END:\",date(),\"\\n\");\n}\n\n## Executing:\nplotulamspirR(100, \"red\", \"UlamSpiralR1\", \"Ulam Spiral: \");\nplotulamspirR(200, \"red\", \"UlamSpiralR2\", \"Ulam Spiral: \",1240);\n", "meta": {"hexsha": "7c9b3fd2a1b7a96a84b44dc737673629cfd93da5", "size": 1271, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Ulam-spiral--for-primes-/R/ulam-spiral--for-primes-.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/Ulam-spiral--for-primes-/R/ulam-spiral--for-primes-.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/Ulam-spiral--for-primes-/R/ulam-spiral--for-primes-.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": 41.0, "max_line_length": 74, "alphanum_fraction": 0.5232100708, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.8095059370417662}} {"text": "weights=c(501.4, 498.0, 498.6 ,499.2, 495.2 ,501.4 ,509.5 ,494.9 ,498.6, 497.6,\r\n 505.5 ,505.1 ,499.8 ,502.4, 497.0 ,504.3 ,499.7 ,497.9 ,496.5, 498.9,\r\n 504.9 ,503.2 ,503.0 ,502.6 ,496.8 ,498.2, 500.1 ,497.9 ,502.2, 503.2)\r\nn=length(weights)\r\nybar=mean(weights)\r\ns=sd(weights)\r\n# The upper-tail chi-square value\r\nXU=qchisq(.995, df=29)\r\n# The lower-tail chi-square value\r\nXL=qchisq(.005, df=29)\r\n# The 99% confidence interval for standard deviation\r\nright_i=sqrt((n-1)*(s^2)/(XL))\r\nleft_i=sqrt((n-1)*(s^2)/(XU))\r\nprint(left_i)\r\nprint(right_i)\r\n# The 99% confidence interval for mean\r\nmargin <- qnorm(0.995)*s/sqrt(n)\r\nleft_interval_mean=ybar-margin\r\nright_interval_mean=ybar+margin\r\nprint(left_interval_mean)\r\nprint(right_interval_mean)", "meta": {"hexsha": "7f0662b97a26c842d5a29c63fda9c6fc00bbd222", "size": 755, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH7/EX7.1/Ex7_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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH7/EX7.1/Ex7_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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH7/EX7.1/Ex7_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": 35.9523809524, "max_line_length": 80, "alphanum_fraction": 0.6662251656, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290913825541, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.8092657550621611}} {"text": "#########################################\n# A toy example of Metropolis- Hastings \n# (a Markov Chain Monte Carlo method)\n# author: Alberto Lumbreras\n#########################################\nlibrary(mvtnorm) # multivariate normal\nlibrary(coda) # MCMC checks\npar(mfrow=c(1,1))\n\n# demo 1: A mixture of Gammas (unidimensional)\n# demo 2: A mixture of Gaussians (bi-dimensional)\ndemo <- 2\n\nif(demo==1){\n \n # Target distribution\n dugly <- function(x) {\n 0.5*dgamma(x, shape=15) + 0.5*dgamma(x, shape=30) \n }\n \n x <- seq(-10,75, by=0.1)\n plot(x, dugly(x), type='l', lwd=3)\n title(\"Metropolis-Hastings samplings\") \n\n\n # Proposal distribution \n # (propose jumps to another state in the Markov Chain)\n rproposal <- function(jump){\n rnorm(1, 0, jump)\n }\n \n # Metropolis-Hastings\n ###########################\n nsamples <-10000\n samples <- matrix(NA,nsamples, 1)\n jump <- 5\n samples[1] <- 200 # init\n for (i in 2:nsamples){\n candidate <- samples[i-1] + rproposal(jump) # hence the \"Markov Chain\"!\n \n # take it or leave it !\n p.acceptance <- dugly(candidate)/dugly(samples[i-1])\n if (runif(1) > p.acceptance){\n samples[i] <- samples[i-1]\n }\n else{\n samples[i] <- candidate\n }\n }\n\n hist(samples, breaks=100, add=TRUE, probability = TRUE)\n \n # The Coda package allows to plot results, \n # perform convergence checks, etc\n plot(mcmc(samples))\n}\n\n# 2-D demo for the sake of beauty\n# (and because we will be able to visalize the )\nif(demo==2){\n par(mfrow=c(1,1))\n \n # Target distribution\n dugly <- function(xy) {\n x <- xy[1]\n y <- xy[2]\n covariance1 <- matrix(c(1, 0, 0, 100), nrow=2)\n covariance2 <- matrix(c(100,0, 0, 1), nrow=2)\n res <- (1/3)*mvtnorm::dmvnorm(c(x,y), mean = c(-5,0), sigma=covariance1) + \n (1/3)*mvtnorm::dmvnorm(c(x,y), mean = c(+0,0), sigma=covariance2) +\n (1/3)*mvtnorm::dmvnorm(c(x,y), mean = c(+5,0), sigma=covariance1)\n res\n }\n \n # Plot target distribution\n x <- seq(-20, 20, length.out=100)\n y <- seq(-20, 20, length.out=100)\n z <- matrix(NA, nrow=100, ncol=100)\n i <- 1\n for (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 }\n contour(x,y,z)\n title(\"Metropolis-Hastings sampling\") \n \n # Proposal distribution \n # (propose jumps to another state in the Markov Chain)\n rproposal <- function(jump){\n covariance <- matrix(c(1, 0, 0, 1), nrow=2)\n mvtnorm::rmvnorm(1, mean = c(0,0), sigma=covariance*jump)\n }\n \n # Metropolis-Hastings\n ###########################\n nsamples <- 10000\n samples <- matrix(NA,nsamples, 2)\n jump <- 20 # Play with it to get around a 20-30% of acceptance rate\n samples[1,] <-c(20,20) # init\n for (i in 2:nsamples){\n candidate <- samples[i-1,] + rproposal(jump) # hence the \"Markov Chain\"!\n \n # take it or leave it !\n p.acceptance <- dugly(candidate)/dugly(samples[i-1,])\n if (runif(1) > p.acceptance){\n samples[i,] <- samples[i-1,]\n }\n else{\n samples[i,] <- candidate\n }\n }\n}\n\n# Plot samples\nlines(samples, col='yellow')\npoints(samples, col='red', pch=19, cex=0.2)\n\n# The Coda package allow to plot results, \n# perform convergence checks, etc\nplot(mcmc(samples))\n\n# Check that the acceptance rate (after burn-in) is good (20-30%)\nburn <- nsamples*0.5 # drop the first half of the chain\nacceptance <- 100-mean(duplicated(samples[-(1:burn),]))*100\ncat (\"Acceptance ratio (recommended 30%):\", acceptance, \"%\")", "meta": {"hexsha": "08418e21d8f8ddafd5ba44ec54ca9eeabda4a11b", "size": 3467, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/metropolis.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/metropolis.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/metropolis.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": 27.2992125984, "max_line_length": 79, "alphanum_fraction": 0.5912892991, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.8092574702419708}} {"text": "# y denote the number of successes in the n sample trials,\r\n# sample proportion\r\ny=43\r\nn=50\r\npie=y/n\r\nsigma=sqrt((pie*(1-pie))/n)\r\nalpha=0.025\r\nz.alpha=qnorm(1-alpha)\r\nerror=z.alpha*sigma\r\n# 95% confidence interval \r\nleft_i=pie-error\r\nright_i=pie+error\r\nprint(\" Wald 95 % confidence interval\")\r\nprint(left_i)\r\nprint(right_i)\r\n\r\n# Using the WAC confidence interval, we need to compute:\r\nybar = y + 0.5*(z.alpha^2)\r\nnbar = n + (z.alpha^2)\r\npie_bar=ybar/nbar\r\n\r\n\r\nsigma_bar=sqrt((pie_bar*(1-pie_bar))/nbar)\r\nerror_bar=z.alpha*sigma_bar\r\nleft=pie_bar-error_bar\r\nright=pie_bar+error_bar\r\nprint(\" WAC 95% confidence interval\")\r\nprint(left)\r\nprint(right)\r\n", "meta": {"hexsha": "e546172738457c4e118a0b2b46951453250f0526", "size": 651, "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.2/Ex10_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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.2/Ex10_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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.2/Ex10_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": 21.7, "max_line_length": 59, "alphanum_fraction": 0.708141321, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305318133554, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.8088573904676516}} {"text": "#\n# Shipment of 100 packets; shipment is denied if more than 5 packets are wrong.\n# K is number of packets to check (randomly) in shipment = sample.\n# Shipment is accepted if no wrong packets are found in the sample.\n# Find K where P(bad shipment is accepted) < 0.1\n#\nfor (k in c(2:100)){\n p <- choose(6, 0)*choose(94, k)/choose(100, k)\n if ( p <= 0.1){\n print(paste(\"k:\", k, \" and p:\", p))\n break\n }\n}\n\n# Now shipment is accepted if there is at most 1 wrong packet in the sample\nfor (k in c(2:100)){\n p <- choose(6, 1)*choose(94, k-1)/choose(100, k)\n if ( p <= 0.1){\n print(paste(\"k:\", k, \" and p:\", p))\n break\n }\n}\n\n#\n# Let the number of chocolate chips in a certain type of cookie have a Poisson distribution.\n# Probability that a randomly chosen cookie has at least 2 chocolate chips > 0.99\n# Find the possible values of mean in 6,7,8 or 9 to assure that.\nfor (lambda in c(6,7,8,9)){\n p <- 1 - lambda^0 * exp(-lambda) / factorial(0) - lambda^1 * exp(-lambda) / factorial(1)\n print(paste(\"lambda: \",lambda, \" p:\", p))\n}\n\n# Another way\nfor (lambda in c(6,7,8,9)){\n p <- ppois(1, lambda = lambda, lower = FALSE)\n print(paste(\"lambda: \",lambda, \" p:\", p))\n}\n", "meta": {"hexsha": "fa325e9d3e90c90d44509d7c907c3841b24672da", "size": 1180, "ext": "r", "lang": "R", "max_stars_repo_path": "homework5.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": "homework5.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": "homework5.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": 31.0526315789, "max_line_length": 92, "alphanum_fraction": 0.6338983051, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811571768047, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.8086225373034208}} {"text": "install.packages(\"fpp\", repos = \"http://cran.us.r-project.org\", dependencies = TRUE)\nlibrary(fpp)\n\n\ndata1 = read.table(\"transcoding_measurement.tsv\",header=TRUE)\nplot(data1$size ~ data1$duration, xlab = \"Duration of video\", ylab = \"Size of the video\")\nfit = lm(data1$size ~ data1$duration ) ; abline(fit) #Add straight lines through the current plot\nsummary(fit) \n# We verify by the plot that the duration of a video does affect the size of it.\n# Typically, we can see the the duration and the size of a video are connected with a linear relationship.\n# The Multiple R-squared error is 0.1738, meaning that the x-y variables are a bit connected. \n# We can see that the line intersects for sure many observations,\n# although the data1-set is too big and we can not see distinct it so much.\n# They(x-y) could be less connected(we tested previously another set with an R-squared error of 0.004!)\n\n# Also, the estimated regression line is : \\hat y = 2513851.4 + 78589.4x\n\n\n## Residual plots\n\nres = residuals(fit) # Calculate residuals from the modeling function 'lm'\nplot(res ~ data1$duration, ylab = \"Residuals\", xlab = \"Duration of video\", ylim = c(-5.0e+08,5.0e+08)); abline(0,0)\n# Seeing the plot, we can understand that most of the residuals are between the \n# -5.0e+08 and the +5.03e+08 values(0e+00 and 1e+08 value specifically,if we add the ylim parameter in the plot), \n# with most of the observations having values 0 and 3000 about the duration of the video.\n# So, yes, there is a pattern since the values are not so scattered around.\n\n## Forecasting with regression\nfitted(fit)[1]\nnewdata = data.frame(data1$duration)\n\nfcast <- forecast(fit,newdata[1] > 130.3567)#=data.frame(duration>30)) \n# It will take a while due to the large size of the data(see global env)\n\nplot(fcast, xlab=\"Duration of video\", ylab=\"Size of video\")\n# This will plot us the result of the forecasting method for the the videos(data) that have duration larger thatn 130.3567 time units\n\n## P-value \nsummary(fit)$coef # We calculate the probability of obtaining a value of β^1\n # as large as we have calculated if the null hypothesis were true\n\n## Confidence intervals\nconfint(fit, level = 0.95) # Provide an interval estimate for β^1 in the fitted model\n\n### Non-linear functional forms\n# Simply transforming variables y and/or x and then estimating a regression model \n# using the transformed variables is the simplest way of obtaining a non-linear specification.\n# We are going to use the log-log functional form \n\npar(mfrow=c(1,2), mar=c(9,4,0,2)+0.1)\nfit2 <- lm(log(data1$size) ~ log(data1$duration)) # Do the fit for : log(y_i) = β_0 + β_1*log(x_i) + ε_i\n\nplot(data1$size ~ data1$duration, xlab = \"Duration of video\", ylab = \"Size of the video\") # Plot standard x-y form\nlines(1:25000, exp(fit2$coef[1]+fit2$coef[2]*log(1:25000))) \n\nplot(log(data1$size) ~ log(data1$duration), xlab = \"log Duration of video \", ylab = \"log Size of the video\") # log-log functional form\nabline(fit2) # Draw a line through our second fitting model\n# See that in this log-log form, the regression is much better since it gets through a lot more points\n\n## Residuals in log-log functional form\n\nres = residuals(fit2)\nplot( res ~ data1$duration, xlab = \"log(Duration)\", ylab= \"Residuals\")\n# We see that most residuals are between -2 and +3 while most log(Duration) points is between 0 and 3000\n# Oh, and there is our lonely value right there with log(Duration) = ~25000\n\n\n## Regression with time series data\n\n# We are going to replace our x variable with 'utime' now.\n# utime = total transcoding time for transcoding\n# We are trying to impersonate utime with 'time' in this series of data, for the sake of simplicity.\n# So, we can give as input a \"future\" 'utime' value and we will 'scenario-based' forecast the size of the video, \n# after we do the regression.\n#\n# Warning: It would be better to replace the 'utime' variable with a 'Year' variable. As said, we do not want to change\n# the data only because of this example!\n\npar(mfrow=c(1,2)) # Change parameters for plot\n\nfit.ex3 <- lm(data1$size ~ data1$utime) # Linear Model Fit for size ~ utime\nplot(data1$size ~ data1$utime, ylab=\"% change in consumption and income\", type=\"single\", col=1:2, xlab=\"utime\") #plot\n\nlegend(\"topright\", legend=c(\"Size\",\"utime\"), lty=1, col=c(1,2), cex=.9)\n\nplot(data1$size ~ data1$utime, ylab=\"% change in size\", xlab=\"% change in utime\")\n\nabline(fit.ex3)\nsummary(fit.ex3)$coef\n\n# The scatter plot includes the estimated regression line \\hat{C} = 21760322.7 + 325380.9i\n\n## Linear trend\n\n# A common feature of time series data is a trend. Using regression we can model and\n# forecast the trend in time series data by including t=1,…,T,t=1,…,T, as a predictor variable:\n# y_t = β_0 + β_1*t + ε_t\nlibrary('forecast')\n\n\ny=ts(data1[15], frequency = 5) # Take column No.11-size for each video- and make it a Time-Series object\nfit.ex4 <- tslm(y ~ trend) # Do Linear Modeling Fit for y ~ trend\nf <- forecast(fit.ex4, h=5,level=c(80,95)) # And do the forecast\nplot(f, ylab=\"Size of video\", xlab=\"t\")\n\nlines(fitted(fit.ex4),col=\"blue\")\nsummary(fit.ex4)$coef\n\n## Residual autocorrelation\n\npar(mfrow=c(2,2))\nres3 <- ts(resid(fit.ex3),s=1970.25,f=4) # Create time-series object using the residuals of 'fit.ex3' variable\nplot.ts(res3,ylab=\"res (utime)\", xlab = \"utime units(instead of Time)\") \nabline(0,0)\n\nacf(res3) # autocorrelation function for the model res3 (utime residuals)\n\n## Same thing for 'fit.ex4' variable \nres4 <- resid(fit.ex4)\nplot(res4,ylab=\"res (size)\")\nabline(0,0)\nacf(res4)\n\n#################################################\npar(mfrow=c(2,2))\nres3 <- ts(resid(fit.ex3),s=1970.25,f=4)\nplot.ts(res3,ylab=\"res (size) \")\nabline(0,0)\nacf(res3)\n\nres4 <- resid(fit.ex4)\nplot(res4,ylab=\"res (size)\")\nabline(0,0)\nacf(res4)", "meta": {"hexsha": "9831b27c2e1ff9af9d6c7ecbfa4fae6865d4cf2a", "size": 5792, "ext": "r", "lang": "R", "max_stars_repo_path": "labs/lab4/simple_regression.r", "max_stars_repo_name": "eloukas/uth-machine-learning", "max_stars_repo_head_hexsha": "9bd0db8866ad29e1e9d53dc804d42b6299d45405", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-10-01T17:42:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-01T17:42:00.000Z", "max_issues_repo_path": "labs/lab4/simple_regression.r", "max_issues_repo_name": "eloukas/PSEs-and-Data-Science", "max_issues_repo_head_hexsha": "9bd0db8866ad29e1e9d53dc804d42b6299d45405", "max_issues_repo_licenses": ["MIT"], "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/lab4/simple_regression.r", "max_forks_repo_name": "eloukas/PSEs-and-Data-Science", "max_forks_repo_head_hexsha": "9bd0db8866ad29e1e9d53dc804d42b6299d45405", "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.223880597, "max_line_length": 135, "alphanum_fraction": 0.7147790055, "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.8084703583992302}} {"text": "polbooks <- read.delim(\"polbooks.dat\", header = F, sep = \",\")\nlesmis <- read.delim(\"lesmis.dat\", header = F, sep = \",\")\n#d <- data.frame((lesmis[,1] + 1), (lesmis[,2] + 1)) \nd <- data.frame((polbooks[,1] + 1), (polbooks[,2] + 1)) \nn <- max(d) #No. of vertices\na <- matrix(0,n,n,dimnames = list(c(seq(1:n)),c(seq(1:n))))\n\n#Creating adjacency matrix from given list\nfor (i in 1:nrow(d)){\n x <- d[i,1] \n y <- d[i,2]\n a[x,y] <- 1\n a[y,x] <- 1\n}\n\n#Degree\ndegree <- function(x){return(as.numeric(rowSums(a)[x]))}\n\n#Global clustering coefficient\nT <- 0 #number of triples\nfor (i in 1:n) {\n k <- degree(i)\n t <- (k * (k - 1))/2\n T <- t + T\n}\ntr <- sum(diag(a %*% a %*% a))/6 #number of triangles\n\nC_gcc <-(tr/T) *3 #Global clust. coeff.\ncat(sprintf(\"Global clustering coefficient is : %f \\n\",C_gcc))\n\n#Degree assortativity\nc <- sum(rowSums(a))/n #Avg degree\nm <- (n*c)/2 #No. of edges\nR1 <- NULL\nR2 <- NULL\nfor (i in 1:n) {\n for (j in 1:n) {\n if(i == j){d = 1} #Kronecker delta\n if(i != j){d = 0}\n r1 <- (a[i,j] - (degree(i)*degree(j))/(2*m))*(degree(i)*degree(j))\n r2 <- ((degree(i)*d) - (degree(i)*degree(j))/(2*m))*(degree(i)*degree(j))\n R1 <- c(r1, R1)\n R2 <- c(r2, R2)\n }\n}\nr <- sum(R1)/sum(R2) #Degree assort.\ncat(sprintf(\"Degree assortativity coefficient is : %f \\n\",r))\n", "meta": {"hexsha": "c6050bc7bff896a6d9e06c69e036b737ca43380e", "size": 1301, "ext": "r", "lang": "R", "max_stars_repo_path": "CN_comp_assign2/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_assign2/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_assign2/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": 27.1041666667, "max_line_length": 77, "alphanum_fraction": 0.5549577248, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8757869867849167, "lm_q1q2_score": 0.8083856939526132}} {"text": "library(tidyverse)\nlibrary(ggplot2)\n\n# Set for reproducibility\nset.seed(777)\nsampleSize <- 10000\n\n\n# Normal Distribution\ndataN1 <- tibble(Outcome = rnorm(sampleSize, mean = 0, sd = 1), distribution = \"N(0,1)\")\ndataN2 <- tibble(Outcome = rnorm(sampleSize, mean = 0, sd = 3), distribution = \"N(0,3)\")\ndataN3 <- tibble(Outcome = rnorm(sampleSize, mean = 2, sd = 5), distribution = \"N(2,5)\")\ndataN4 <- tibble(Outcome = rnorm(sampleSize, mean = 5, sd = 10), distribution = \"N(5,10)\")\ndataN5 <- tibble(Outcome = rnorm(sampleSize, mean = 10, sd = 2), distribution = \"N(10,2)\")\n\ndata <- bind_rows(dataN1, dataN2, dataN3, dataN4, dataN5)\n\nggplot(data, aes(x = Outcome, fill = distribution)) + \n geom_density(aes(group = distribution), alpha = 0.25) +\n labs(\n title = \"Sampling from normal distributions\",\n subtitle = \"10,000 samples\"\n )\n\n\n\n# chi-squared\ndataChiSq1 <- tibble(Outcome = rchisq(sampleSize, df = 1), distribution = \"Chi(1)\")\ndataChiSq2 <- tibble(Outcome = rchisq(sampleSize, df = 2), distribution = \"Chi(2)\")\ndataChiSq3 <- tibble(Outcome = rchisq(sampleSize, df = 5), distribution = \"Chi(5)\")\ndataChiSq4 <- tibble(Outcome = rchisq(sampleSize, df = 10), distribution = \"Chi(10)\")\ndataChiSq5 <- tibble(Outcome = rchisq(sampleSize, df = 20), distribution = \"Chi(20)\")\n\ndata <- bind_rows(dataChiSq1, dataChiSq2, dataChiSq3, dataChiSq4, dataChiSq5)\n\nggplot(data, aes(x = Outcome, fill = distribution)) + \n geom_density(aes(group = distribution), alpha = 0.25) +\n labs(\n title = \"Sampling from chi-squared distributions\",\n subtitle = \"10,000 samples\"\n )\n\n# f-distribution\ndataF1 <- tibble(Outcome = rf(sampleSize, df1 = 1, df2 = 1), distribution = \"F(1,1)\")\ndataF2 <- tibble(Outcome = rf(sampleSize, df1 = 5, df2 = 5), distribution = \"F(5,5)\")\ndataF3 <- tibble(Outcome = rf(sampleSize, df1 = 10, df2 = 20), distribution = \"F(10,20)\")\ndataF4 <- tibble(Outcome = rf(sampleSize, df1 = 30, df2 = 5), distribution = \"F(30,5)\")\ndataF5 <- tibble(Outcome = rf(sampleSize, df1 = 15, df2 = 30), distribution = \"F(15, 30)\")\n\ndata <- bind_rows(dataF1, dataF2, dataF3, dataF4, dataF5)\n\nggplot(data, aes(x = Outcome, fill = distribution)) + \n geom_density(aes(group = distribution), alpha = 0.25) +\n labs(\n title = \"Sampling from F-distributions\",\n subtitle = \"10,000 samples. Removed curves after x=15\"\n ) +\n xlim(0, 15)\n\n\n# Exponential\ndataExp1 <- tibble(Outcome = rexp(sampleSize, rate = 1), distribution = \"Exp(1)\")\ndataExp2 <- tibble(Outcome = rexp(sampleSize, rate = .1), distribution = \"Exp(0.1)\")\ndataExp3 <- tibble(Outcome = rexp(sampleSize, rate = .2), distribution = \"Exp(0.2)\")\ndataExp4 <- tibble(Outcome = rexp(sampleSize, rate = .5), distribution = \"Exp(0.5)\")\ndataExp5 <- tibble(Outcome = rexp(sampleSize, rate = .8), distribution = \"Exp(0.8)\")\n\ndata <- bind_rows(dataExp1, dataExp2, dataExp3, dataExp4, dataExp5)\n\nggplot(data, aes(x = Outcome, fill = distribution)) + \n geom_density(aes(group = distribution), alpha = 0.25) +\n labs(\n title = \"Sampling from Exponential distributions\",\n subtitle = \"10,000 samples\"\n )\n\n# Cauchy\ndataCauchy1 <- tibble(Outcome = rcauchy(sampleSize, location = 0, scale = 1), distribution = \"Cauchy(0,1)\")\ndataCauchy2 <- tibble(Outcome = rcauchy(sampleSize, location = 0, scale = 2), distribution = \"Cauchy(0,2)\")\ndataCauchy3 <- tibble(Outcome = rcauchy(sampleSize, location = 0, scale = 0.5), distribution = \"Cauchy(0,0.5)\")\ndataCauchy4 <- tibble(Outcome = rcauchy(sampleSize, location = -1, scale = 5), distribution = \"Cauchy(-1,5)\")\ndataCauchy5 <- tibble(Outcome = rcauchy(sampleSize, location = -5, scale = 1), distribution = \"Cauchy(-5,1)\")\n\ndata <- bind_rows(dataCauchy1, dataCauchy2, dataCauchy3, dataCauchy4, dataCauchy5)\n\nggplot(data, aes(x = Outcome, fill = distribution)) + \n geom_density(aes(group = distribution), alpha = 0.25) +\n labs(\n title = \"Sampling from Cauchy distributions\",\n subtitle = \"10,000 samples\"\n ) +\n xlim(-10,10)\n\n\n# Gamma\ndataGamma1 <-tibble(Outcome = rgamma(sampleSize, shape = 1, rate = 1), distribution = \"Gamma(1,1)\")\ndataGamma2 <- tibble(Outcome = rgamma(sampleSize, shape = 2, rate = 1), distribution = \"Gamma(2,1)\")\ndataGamma3 <- tibble(Outcome = rgamma(sampleSize, shape = 3, rate = 1), distribution = \"Gamma(3,1)\")\ndataGamma4 <- tibble(Outcome = rgamma(sampleSize, shape = 1, rate = 5), distribution = \"Gamma(1,5)\")\ndataGamma5 <- tibble(Outcome = rgamma(sampleSize, shape = 3, rate = 5), distribution = \"Gamma(3,5)\")\n\ndata <- bind_rows(dataGamma1, dataGamma2, dataGamma3, dataGamma4, dataGamma5)\n\nggplot(data, aes(x = Outcome, fill = distribution)) + \n geom_density(aes(group = distribution), alpha = 0.25) +\n labs(\n title = \"Sampling from Gamma distributions\",\n subtitle = \"10,000 samples. 1st parameter = shape, 2nd parameter = rate\"\n ) +\n xlim(0, 8)\n\n\n# Beta\ndataBeta1 <-tibble(Outcome = rbeta(sampleSize, shape1 = .5, shape2 = .5), distribution = \"Beta(0.5,0.5)\")\ndataBeta2 <- tibble(Outcome = rbeta(sampleSize, shape1 = 2, shape2 = 1), distribution = \"Beta(2,1)\")\ndataBeta3 <- tibble(Outcome = rbeta(sampleSize, shape1 = 3, shape2 = 1), distribution = \"Beta(3,1)\")\ndataBeta4 <- tibble(Outcome = rbeta(sampleSize, shape1 = 1, shape2 = 5), distribution = \"Beta(1,5)\")\ndataBeta5 <- tibble(Outcome = rbeta(sampleSize, shape1 = 3, shape2 = 5), distribution = \"Beta(3,5)\")\n\ndata <- bind_rows(dataBeta1, dataBeta2, dataBeta3, dataBeta4, dataBeta5)\n\nggplot(data, aes(x = Outcome, fill = distribution)) + \n geom_density(aes(group = distribution), alpha = 0.25) +\n labs(\n title = \"Sampling from Beta distributions\",\n subtitle = \"10,000 samples. 1st parameter = shape 1, 2nd parameter = shape 2\"\n )\n\n?rnorm\n\n", "meta": {"hexsha": "6af043120072e9e552f5714f67718cdf1a0e008d", "size": 5639, "ext": "r", "lang": "R", "max_stars_repo_path": "a24c54d72bd73f7d09b18a953c8502a2/Continuous.r", "max_stars_repo_name": "researchdata-sheffield/dataviz-hub2-qa", "max_stars_repo_head_hexsha": "bd746b5859a1e26f732663eb288b3bad8212c1f2", "max_stars_repo_licenses": ["0BSD", "Apache-2.0", "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": "a24c54d72bd73f7d09b18a953c8502a2/Continuous.r", "max_issues_repo_name": "researchdata-sheffield/dataviz-hub2-qa", "max_issues_repo_head_hexsha": "bd746b5859a1e26f732663eb288b3bad8212c1f2", "max_issues_repo_licenses": ["0BSD", "Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a24c54d72bd73f7d09b18a953c8502a2/Continuous.r", "max_forks_repo_name": "researchdata-sheffield/dataviz-hub2-qa", "max_forks_repo_head_hexsha": "bd746b5859a1e26f732663eb288b3bad8212c1f2", "max_forks_repo_licenses": ["0BSD", "Apache-2.0", "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.0458015267, "max_line_length": 111, "alphanum_fraction": 0.6793757758, "num_tokens": 1865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.8080748456939051}} {"text": "# simple varaince and standard deviation\r\nClassInterval <- c(\"16.25-18.75\", \"18.75-21.25\", \"21.25-23.75\",\"23.75-26.25\", \"26.25-28.75\", \" 28.75-31.25\", \" 31.25-33.75\", \"33.75-36.25\",\"36.25-38.75\", \" 38.75- 41.25\",\"41.25- 43.75\")\r\nfreq <- c( 2,7,7,14,17,24,11,11,3,3,1)\r\nmid_interval<- c(17.5,20.0,22.5,25.0,27.5,30.0,32.5,35.0,37.5,40.0,42.5)\r\nfmi<-freq*mid_interval\r\n\r\nmean_y<-sum(fmi)/sum(freq)\r\nsample_variance <-(sum(freq*((mid_interval-mean_y)^2)/(sum(freq)-1)))\r\nprint(sample_variance)\r\nstandard_deviation <-sqrt(sample_variance)\r\nprint(standard_deviation)", "meta": {"hexsha": "3264ea3ab830fe18ae2feed8d18f1c927fab9320", "size": 561, "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.10/Ex3_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/CH3/EX3.10/Ex3_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/CH3/EX3.10/Ex3_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": 51.0, "max_line_length": 186, "alphanum_fraction": 0.6595365419, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158576, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.8078420397009404}} {"text": "# https://fivethirtyeight.com/features/pick-a-card-any-card/\n# From a shuffled deck of 100 cards that are numbered 1 to 100, \n# you are dealt 10 cards face down. You turn the cards over one by one. \n# After each card, you must decide whether to end the game. \n# If you end the game on the highest card in the hand you were dealt, you win; \n# otherwise, you lose.\n# What is the strategy that optimizes your chances of winning? \n# How does the strategy change as the sizes of the deck and the hand are changed?\n\n# Libraries\nlibrary(tidyverse)\n\n# Input\nno_cards <- 100\nno_turns <- 10\n\n#Code\ncards <- no_cards:1\nturns <- no_turns:1\n\n# If current card is not your high card then continue picking\n# Otherwise if current card is your high card:\n\ny <- matrix(NA, nrow = max(turns), ncol = max(cards))\nfor (i in cards) {\n x <- numeric(max(turns))\n for (j in turns) {\n lwr <- i - (max(turns) - j)\n tot <- max(cards) - (max(turns) - j)\n a <- pmax(0, (lwr - 1):(lwr - j))\n b <- (tot - 1):(tot - j)\n x[(max(turns) - j + 1)] <- tail(cumprod(a / b), 1)\n }\n y[, (max(cards) - i + 1)] <- x\n}\n\nxval <- yval <- numeric(nrow(y))\nfor (i in 1:nrow(y)) {\n xval[i] <- i\n yval[i] <- max(cards) - max(which(y[i, ] > 0.5))\n}\nyval <- c(yval[2:max(turns)], max(turns))\nline <- tibble(x = xval, y = yval)\n\ncolnames(y) <- max(cards):1\ny <- as_tibble(y) %>% \n mutate(turn = 1:max(turns)) %>% \n gather(max(cards):1, key = card, value = prob) %>% \n mutate(card = as.numeric(card))\n\n# Output\nggplot(y, aes(turn, card)) + \n geom_tile(aes(fill = prob)) + \n scale_fill_gradient(low = \"white\", high = \"steelblue\") +\n theme_minimal() +\n layer(geom = \"line\", stat = \"identity\", \n position = \"identity\", data = line,\n aes(x, y))\nas_tibble(paste0(\"For turn \", xval, \" stop if card >= \", yval))\n", "meta": {"hexsha": "dce76a66257c47e001f12e6a6e1e10232b07ffc4", "size": 1794, "ext": "r", "lang": "R", "max_stars_repo_path": "pickCard.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": "pickCard.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": "pickCard.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.9, "max_line_length": 81, "alphanum_fraction": 0.6209587514, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109826342959, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.8078219420735131}} {"text": "#Copyright (c) 2016 Riccardo Francescato\nX = c(10,20,50,100,150,200)\nY = c(9.4,9.2,9.0,8.5,8.1,7.4)\n\nalpha = .05\nSigmaX = sum( (X - mean(X) )^2 )\nSigmaY = sum( (Y - mean(Y) )^2 )\nCovXY = cov(X,Y)\nCorXY = cor(X,Y)\nBeta1 = sum((Y - mean(Y))*(X - mean(X) ))/SigmaX\nBeta0 = mean(Y)-mean(X)*Beta1\nSigma2 = (SigmaY-(SigmaX*Beta1^2))/(length(X)-2)\nYstim = Y-(Beta0+Beta1*X)\nErrors = Y-Ystim\nSSR = sum((Ystim-mean(Y))^2)\nSSE = sum(Errors^2)\nSST = sum((Y-mean(Y))^2)\nMSR = SSR/1\nMSE = SSE/(length(X)-2)\nMST = SST/(length(X)-1)\nF0 = MSR/MSE\nFa = qf(alpha,df1=1,df2=(length(X)-2),lower.tail=F)\n\nif(F0 > Fa) print(paste0(\" reject H0 \", F0)) else print(paste0(\" Accept H0 \", F0))\ncat(paste0(\" Regression SS: \",SSR,\" Df: \", 1 ,\" MS: \",MSR, \" F0: \",F0,\n\t\t\"\\n Error SS: \",SSE,\" Df: \", (length(X)-2) ,\" MS: \",MSE,\n\t\t\"\\n Total SS: \",SST,\" Df: \", (length(X)-1)))\n\n\nmydata = data.frame(\n y = c(2256,2340,2426,2293,2330,2368,2250,2409,2364,2379,2440,2364,2404,2317,2309,2328),\n x1 = c(80,93,100,82,90,99,81,96,94,93,97,95,100,85,86,87),\n x2 = c(8,9,10,12,11,8,8,10,12,11,13,11,8,12,9,12)\n)\n# Multiple Linear Regression Example \nfit <- lm(y ~ x1 + x2, data=mydata)\nsummary(fit) # show results\n# Other useful functions \ncoefficients(fit) # model coefficients\nconfint(fit, level=0.95) # CIs for model parameters \nfitted(fit) # predicted values\nresiduals(fit) # residuals\nanova(fit) # anova table \nvcov(fit) # covariance matrix for model parameters \ninfluence(fit) # regression diagnostics", "meta": {"hexsha": "4d91e179d6beae86e6b5eaab2b2457451789c836", "size": 1471, "ext": "r", "lang": "R", "max_stars_repo_path": "linear_reg.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": "linear_reg.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": "linear_reg.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": 32.6888888889, "max_line_length": 89, "alphanum_fraction": 0.6335825969, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.8078219319105641}} {"text": "data <- read.csv('Oil_Prices.csv')\nlibrary(ggplot2)\nWTI_ts <- ts(data$WTI, frequency=12, start=c(1999,9))\nBrent_ts <- ts(data$Brent, frequency=12, start=c(1999,9))\n\n\nlibrary(forecast)\nhist(WTI_ts, breaks=20, freq=FALSE, col='blue')\nlines(density(WTI_ts) , col='red', lwd=3)\n\n\nmonthplot(WTI_ts,col.base='red')\nseasonplot(WTI_ts,col=1:20, year.labels=TRUE)\n# We can determine a slight seasonal pattern. We see demand increases in the end \n#of the year months,however these are not strong enough to determine seasonality.\n\n\nt0 = c(1999,9)\nt1 = c(2018,12)\nt2 = c(2019,7) \nWTI_train <- window(WTI_ts, start=t0, end=t1)\nWTI_test <- window(WTI_ts, start=t2)\n\n#Univariate Case\nlibrary(urca)\nWTI_ADF_none <- ur.df(WTI_train, type=\"none\", lags=12, selectlags = \"AIC\")\nsummary(WTI_ADF_none)\n\nWTI_ADF_drift <- ur.df(WTI_train, type=\"drift\", lags=12, selectlags = \"AIC\")\nsummary(WTI_ADF_drift)\n\nWTI_ADF_trend <- ur.df(WTI_train, type=\"trend\", lags=12, selectlags = \"AIC\")\nsummary(WTI_ADF_trend)\n# We fail to reject null for all test. This means WTI is not a stationary process\n# for all test.\n# You cannot reject the no drift null. You do not need a drift coefficient.\n# You do not need to include a drift nor trend in our data\n\n\n\nDWTI <-diff(WTI_train)\nDWTI_ADF_none <- ur.df(DWTI, type=\"none\", lags=12, selectlags = \"AIC\")\nsummary(DWTI_ADF_none)\nDWTI_ADF_drift <- ur.df(DWTI, type=\"drift\", lags=12, selectlags = \"AIC\")\nsummary(DWTI_ADF_drift)\nDWTI_ADF_trend <- ur.df(DWTI, type=\"trend\", lags=12, selectlags = \"AIC\")\nsummary(DWTI_ADF_trend)\n# The best version is the no drift and no trend. Based on this we say it\n# is stationary integrated order 1.\n\n\n\nWTIarimaA <- auto.arima(DWTI, d=0, max.p=5, max.q=5, max.order=10,\nseasonal=FALSE, stepwise=FALSE, ic='aic')\nWTIarimaB <- auto.arima(DWTI, d=0, max.p=5, max.q=5, max.order=10,\nseasonal=FALSE, stepwise=FALSE, ic='bic')\n\nWTIarimaA\nWTIarimaB\n\n\nfuture= forecast(WTIarimaA, h = 20)\nplot(future)\n\n\n# Bivariate Case\n\nlibrary(vars)\nBrent_train <- window(Brent_ts, start=t0, end=t1)\nBrent_test <- window(Brent_ts, start=t2)\ndf_level <-data.frame(WTI_train, Brent_train) \n\n\nvecm <- ca.jo(df_level, type = 'eigen', ecdet = 'const', K=2,spec='transitory')\nsummary(vecm)\n# The null r=0 is rejected so there is atleast 1 cointegration factor. The \n# second test is not rejected therefore there is only one cointegration factor. \n\n\n\nvecm.rls <- cajorls(vecm, r = 1)\nerror <- vecm.rls$rlm$model['ect1']\ntsdisplay(error$ect1)\nerror_ADF <- ur.df(error$ect1, type=\"none\", lags=12, selectlags = \"AIC\")\nsummary(error_ADF)\n# The error correction term is stationary and is not a white noise process.\n\n\n\ncajorls(vecm)\ncoef(summary(cajorls(vecm)$rlm))\n# At 5% significance WTI responds most to our error correction term\n\n\nvar.model = vec2var(vecm)\nH = 12\nfc <- predict(var.model, n.ahead=H)\n\n\nWTI_forecast <- ts(fc$fcst$WTI_train[1:H,1], frequency=12, start=t2)\nBrent_forecast <- ts(fc$fcst$Brent_train[1:H,1], frequency=12, start=t2)\n\n\nprint('WTI error')\nx = accuracy(WTI_forecast,WTI_test)\ncat('RMSE:',x[1,'RMSE'], '\\n')\ncat('MAE:',x[1,'MAE'], '\\n')\n\nprint('Brent error')\ny = accuracy(Brent_forecast,Brent_test)\ncat('RMSE:',y[1,'RMSE'], '\\n')\ncat('MAE:',y[1,'MAE'], '\\n')\n\nWTI_forecast\nBrent_forecast\n\nplot(fc)\n", "meta": {"hexsha": "c3b067f115e79dfd1e5d7cfe41aebdfd947bc47d", "size": 3229, "ext": "r", "lang": "R", "max_stars_repo_path": "ForecastingCrudeOil.r", "max_stars_repo_name": "mnamazi5/ForecastingOilPrices", "max_stars_repo_head_hexsha": "51ac853107a3414dba138eb487da002553bd635e", "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": "ForecastingCrudeOil.r", "max_issues_repo_name": "mnamazi5/ForecastingOilPrices", "max_issues_repo_head_hexsha": "51ac853107a3414dba138eb487da002553bd635e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ForecastingCrudeOil.r", "max_forks_repo_name": "mnamazi5/ForecastingOilPrices", "max_forks_repo_head_hexsha": "51ac853107a3414dba138eb487da002553bd635e", "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.3644067797, "max_line_length": 81, "alphanum_fraction": 0.717559616, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.87407724336544, "lm_q1q2_score": 0.8077713399642589}} {"text": "### 線形回帰分析の例\n### - Ashenfelter's Wine Equation\n\n## パッケージの読み込み\nrequire(tidyverse) \nrequire(ggfortify)\nrequire(GGally)\n\n## データの読み込み(\"wine.csv\"を用いる)\nscan(file=\"data/wine.txt\", what=character(), sep=\";\") # データの説明の表示\nwine <- read.csv(file=\"data/wine.csv\", row.names=1) # データの読み込み\n\n## データの内容を確認\nprint(wine) # データの表示\n\n## データのプロット\nggpairs(wine,\n lower=list(continuous=wrap(\"smooth_loess\",colour=\"blue\"))) +\n theme(axis.title.x=element_text(size=8),\n axis.title.y=element_text(size=8)) # 文字の大きさを調整\n\n## ボルドーワインの価格(質)を冬の降雨量(WRAIN),育成期平均気温(DEGREES),\n## 収穫期降雨量(HRAIN),年数(TIME_SV)で回帰する\nmodel <- lm(LPRICE2 ~ ., data=wine)\nsummary(model)\nround(coef(model), digits=6) # 係数を確認する\n\n## 診断プロット\nautoplot(model)\n## autoplot(model, which=1) # res vs fit\n## autoplot(model, which=2) # qq plot\n## autoplot(model, which=4) # Cook's dist\n## autoplot(model, which=1:6)\n\n## 回帰による予測結果を比較\nyear <- rownames(wine)\nprice <- exp(wine$LPRICE2)\npredict <- exp(predict(model, newdata=wine, interval=\"prediction\"))\nmydat <- data.frame(year=year, price=price, predict)\n\n## 実測値と予測値の比較\nggplot(mydat, aes(price, fit, label=year)) +\n geom_text(na.rm=TRUE) + # text で表示\n scale_x_log10() + scale_y_log10() + # log-log plot\n labs(title=\"Bordeaux Wine Price (log)\", x=\"Price\", y=\"Prediction\")\n\n## 各年の比較\nggplot(mydat, aes(year, price, group=1)) +\n geom_ribbon(aes(ymin=lwr, ymax=upr),\n fill=\"red\", alpha=.1, na.rm=TRUE) +\n geom_path(aes(y=price, colour=\"Price\"), na.rm=TRUE) + \n geom_path(aes(y=fit, colour=\"Predict\"), na.rm=TRUE) +\n theme(axis.text.x=element_text(angle = 90, hjust=1, vjust=.5),\n legend.position=c(.9,.9)) + # 文字の向きと凡例の位置を調整\n labs(title=\"Bordeaux Wine Price\", x=\"Year\") \n\n### 専門家の評価が高かったのは1986年だが,予測では凡庸\n### その後1989/1990年の気温(かなり高い)を用いて予測した内容が話題となる\n", "meta": {"hexsha": "3d299b5397ceb0994223ff318975b57b2b43538f", "size": 1784, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/code/r-wine.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/r-wine.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/r-wine.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": 30.2372881356, "max_line_length": 70, "alphanum_fraction": 0.673206278, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839606, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.8074325986248055}} {"text": "library(repr) ; options(repr.plot.width = 4, repr.plot.height = 4) # Change plot sizes (in cm)\n\nrm(list = ls())\ngraphics.off()\n\nS_data <- seq(1,50,5)\nS_data\n\nV_data <- ((12.5 * S_data)/(7.1 + S_data))\nplot(S_data, V_data)\n\nset.seed(1456) # To get the same random fluctuations in the \"data\" every time\nV_data <- V_data + rnorm(10,0,1) # Add 10 random fluctuations with standard deviation of 0.5 to emulate error\nplot(S_data, V_data)\n\nMM_model <- nls(V_data ~ V_max * S_data / (K_M + S_data))\n\nplot(S_data,V_data, xlab = \"Substrate Concentration\", ylab = \"Reaction Rate\") # first plot the data \nlines(S_data,predict(MM_model),lty=1,col=\"blue\",lwd=2) # now overlay the fitted model \n\ncoef(MM_model) # check the coefficients\n\nSubstrate2Plot <- seq(min(S_data), max(S_data),len=200) # generate some new x-axis values just for plotting\n\nPredict2Plot <- coef(MM_model)[\"V_max\"] * Substrate2Plot / (coef(MM_model)[\"K_M\"] + Substrate2Plot) # calculate the predicted values by plugging the fitted coefficients into the model equation \n\nplot(S_data,V_data, xlab = \"Substrate Concentration\", ylab = \"Reaction Rate\") # first plot the data \nlines(Substrate2Plot, Predict2Plot, lty=1,col=\"blue\",lwd=2) # now overlay the fitted model\n\nsummary(MM_model)\n\nconfint(MM_model)\n\nMM_model2 <- nls(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = 12, K_M = 7))\n\ncoef(MM_model)\ncoef(MM_model2)\n\nMM_model3 <- nls(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = .01, K_M = 20))\n\ncoef(MM_model)\ncoef(MM_model2)\ncoef(MM_model3)\n\nplot(S_data,V_data) # first plot the data \nlines(S_data,predict(MM_model),lty=1,col=\"blue\",lwd=2) # overlay the original model fit\nlines(S_data,predict(MM_model3),lty=1,col=\"red\",lwd=2) # overlay the latest model fit\n\nnls(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = 0, K_M = 0.1))\n\nnls(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = -0.1, K_M = 100))\n\nMM_model4 <- nls(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = 12.96, K_M = 10.61))\n\ncoef(MM_model)\ncoef(MM_model4)\n\nrequire(\"minpack.lm\")\n\nMM_model5 <- nlsLM(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = 2, K_M = 2))\n\ncoef(MM_model2)\ncoef(MM_model5)\n\nMM_model6 <- nlsLM(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = .01, K_M = 20))\n\nMM_model7 <- nlsLM(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = 0, K_M = 0.1))\n\nMM_model8 <- nlsLM(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = -0.1, K_M = 100))\n\ncoef(MM_model6)\ncoef(MM_model7)\ncoef(MM_model8)\n\nnlsLM(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = -10, K_M = -100))\n\nnlsLM(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = 0.1, K_M = 0.1))\n\nnlsLM(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = 0.1, K_M = 0.1), lower=c(0.4,0.4), upper=c(100,100))\n\nnlsLM(V_data ~ V_max * S_data / (K_M + S_data), start = list(V_max = 0.5, K_M = 0.5), lower=c(0.4,0.4), upper=c(20,20))\n\nhist(residuals(MM_model6))\n\nMyData <- read.csv(\"../data/GenomeSize.csv\") # using relative path assuming that your working directory is \"code\"\n\nhead(MyData)\n\nData2Fit <- subset(MyData,Suborder == \"Anisoptera\")\n\nData2Fit <- Data2Fit[!is.na(Data2Fit$TotalLength),] # remove NA's\n\nplot(Data2Fit$TotalLength, Data2Fit$BodyWeight, xlab = \"Body Length\", ylab = \"Body Weight\")\n\nlibrary(\"ggplot2\")\n\nggplot(Data2Fit, aes(x = TotalLength, y = BodyWeight)) + \ngeom_point(size = (3),color=\"red\") + theme_bw() + \nlabs(y=\"Body mass (mg)\", x = \"Wing length (mm)\")\n\nnrow(Data2Fit)\n\nPowFit <- nlsLM(BodyWeight ~ a * TotalLength^b, data = Data2Fit, start = list(a = .1, b = .1))\n\npowMod <- function(x, a, b) {\n return(a * x^b)\n}\n\nPowFit <- nlsLM(BodyWeight ~ powMod(TotalLength,a,b), data = Data2Fit, start = list(a = .1, b = .1))\n\nLengths <- seq(min(Data2Fit$TotalLength),max(Data2Fit$TotalLength),len=200)\n\ncoef(PowFit)[\"a\"]\ncoef(PowFit)[\"b\"]\n\nPredic2PlotPow <- powMod(Lengths,coef(PowFit)[\"a\"],coef(PowFit)[\"b\"])\n\nplot(Data2Fit$TotalLength, Data2Fit$BodyWeight)\nlines(Lengths, Predic2PlotPow, col = 'blue', lwd = 2.5)\n\nsummary(PowFit)\n\nprint(confint(PowFit))\n\nhist(residuals(PowFit))\n\nQuaFit <- lm(BodyWeight ~ poly(TotalLength,2), data = Data2Fit)\n\nPredic2PlotQua <- predict.lm(QuaFit, data.frame(TotalLength = Lengths))\n\nplot(Data2Fit$TotalLength, Data2Fit$BodyWeight)\nlines(Lengths, Predic2PlotPow, col = 'blue', lwd = 2.5)\nlines(Lengths, Predic2PlotQua, col = 'red', lwd = 2.5)\n\nRSS_Pow <- sum(residuals(PowFit)^2) # Residual sum of squares\nTSS_Pow <- sum((Data2Fit$BodyWeight - mean(Data2Fit$BodyWeight))^2) # Total sum of squares\nRSq_Pow <- 1 - (RSS_Pow/TSS_Pow) # R-squared value\n\nRSS_Qua <- sum(residuals(QuaFit)^2) # Residual sum of squares\nTSS_Qua <- sum((Data2Fit$BodyWeight - mean(Data2Fit$BodyWeight))^2) # Total sum of squares\nRSq_Qua <- 1 - (RSS_Qua/TSS_Qua) # R-squared value\n\nRSq_Pow \nRSq_Qua\n\nn <- nrow(Data2Fit) #set sample size\npPow <- length(coef(PowFit)) # get number of parameters in power law model\npQua <- length(coef(QuaFit)) # get number of parameters in quadratic model\n\nAIC_Pow <- n + 2 + n * log((2 * pi) / n) + n * log(RSS_Pow) + 2 * pPow\nAIC_Qua <- n + 2 + n * log((2 * pi) / n) + n * log(RSS_Qua) + 2 * pQua\nAIC_Pow - AIC_Qua\n\nAIC(PowFit) - AIC(QuaFit)\n\nalb <- read.csv(file=\"../data/albatross_grow.csv\")\nalb <- subset(x=alb, !is.na(alb$wt))\nplot(alb$age, alb$wt, xlab=\"age (days)\", ylab=\"weight (g)\", xlim=c(0, 100))\n\nlogistic1 <- function(t, r, K, N0){\n N0 * K * exp(r * t)/(K+N0 * (exp(r * t)-1))\n}\n\nvonbert.w <- function(t, Winf, c, K){\n Winf * (1 - exp(-K * t) + c * exp(-K * t))^3\n}\n\nscale <- 4000\n\nalb.lin <- lm(wt/scale ~ age, data = alb)\n\nalb.log <- nlsLM(wt/scale~logistic1(age, r, K, N0), start=list(K=1, r=0.1, N0=0.1), data=alb)\n\nalb.vb <- nlsLM(wt/scale~vonbert.w(age, Winf, c, K), start=list(Winf=0.75, c=0.01, K=0.01), data=alb)\n\nages <- seq(0, 100, length=1000)\n\npred.lin <- predict(alb.lin, newdata = list(age=ages)) * scale\n\npred.log <- predict(alb.log, newdata = list(age=ages)) * scale\n\npred.vb <- predict(alb.vb, newdata = list(age=ages)) * scale\n\nplot(alb$age, alb$wt, xlab=\"age (days)\", ylab=\"weight (g)\", xlim=c(0,100))\nlines(ages, pred.lin, col=2, lwd=2)\nlines(ages, pred.log, col=3, lwd=2)\nlines(ages, pred.vb, col=4, lwd=2)\n\nlegend(\"topleft\", legend = c(\"linear\", \"logistic\", \"Von Bert\"), lwd=2, lty=1, col=2:4)\n\npar(mfrow=c(3,1), bty=\"n\")\nplot(alb$age, resid(alb.lin), main=\"LM resids\", xlim=c(0,100))\nplot(alb$age, resid(alb.log), main=\"Logisitic resids\", xlim=c(0,100))\nplot(alb$age, resid(alb.vb), main=\"VB resids\", xlim=c(0,100))\n\nn <- length(alb$wt)\nlist(lin=signif(sum(resid(alb.lin)^2)/(n-2 * 2), 3), \n log= signif(sum(resid(alb.log)^2)/(n-2 * 3), 3), \n vb= signif(sum(resid(alb.vb)^2)/(n-2 * 3), 3)) \n\naedes <- read.csv(file=\"../data/aedes_fecund.csv\")\n\nplot(aedes$T, aedes$EFD, xlab=\"temperature (C)\", ylab=\"Eggs/day\")\n\nquad1 <- function(T, T0, Tm, c){\n c * (T-T0) * (T-Tm) * as.numeric(TT0)\n}\n\nbriere <- function(T, T0, Tm, c){\n c * T * (T-T0) * (abs(Tm-T)^(1/2)) * as.numeric(TT0)\n}\n\nscale <- 20\n\naed.lin <- lm(EFD/scale ~ T, data=aedes)\n\naed.quad <- nlsLM(EFD/scale~quad1(T, T0, Tm, c), start=list(T0=10, Tm=40, c=0.01), data=aedes)\n\naed.br <- nlsLM(EFD/scale~briere(T, T0, Tm, c), start=list(T0=10, Tm=40, c=0.1), data=aedes)\n\nt <- seq(0, 22, 2)\nN <- c(32500, 33000, 38000, 105000, 445000, 1430000, 3020000, 4720000, 5670000, 5870000, 5930000, 5940000)\n\nset.seed(1234) # To ensure we always get the same random sequence in this example \"dataset\" \n\ndata <- data.frame(t, N * (1 + rnorm(length(t), sd = 0.1))) # add some random error\n\nnames(data) <- c(\"Time\", \"N\")\n\nhead(data)\n\nggplot(data, aes(x = Time, y = N)) + \n geom_point(size = 3) +\n labs(x = \"Time (Hours)\", y = \"Population size (cells)\")\n\ndata$LogN <- log(data$N)\n\n# visualise\nggplot(data, aes(x = t, y = LogN)) + \n geom_point(size = 3) +\n labs(x = \"Time (Hours)\", y = \"log(cell number)\")\n\n(data[data$Time == 10,]$LogN - data[data$Time == 6,]$LogN)/(10-6)\n\ndiff(data$LogN)\n\nmax(diff(data$LogN))/2 # 2 is the difference in any successive pair of timepoints\n\nlm_growth <- lm(LogN ~ Time, data = data[data$Time > 2 & data$Time < 12,])\nsummary(lm_growth)\n\nlogistic_model <- function(t, r_max, K, N_0){ # The classic logistic equation\n return(N_0 * K * exp(r_max * t)/(K + N_0 * (exp(r_max * t) - 1)))\n}\n\n# first we need some starting parameters for the model\nN_0_start <- min(data$N) # lowest population size\nK_start <- max(data$N) # highest population size\nr_max_start <- 0.62 # use our estimate from the OLS fitting from above\n\nfit_logistic <- nlsLM(N ~ logistic_model(t = Time, r_max, K, N_0), data,\n list(r_max=r_max_start, N_0 = N_0_start, K = K_start))\n\nsummary(fit_logistic)\n\ntimepoints <- seq(0, 22, 0.1)\n\nlogistic_points <- logistic_model(t = timepoints, \n r_max = coef(fit_logistic)[\"r_max\"], \n K = coef(fit_logistic)[\"K\"], \n N_0 = coef(fit_logistic)[\"N_0\"])\ndf1 <- data.frame(timepoints, logistic_points)\ndf1$model <- \"Logistic equation\"\nnames(df1) <- c(\"Time\", \"N\", \"model\")\n\nggplot(data, aes(x = Time, y = N)) +\n geom_point(size = 3) +\n geom_line(data = df1, aes(x = Time, y = N, col = model), size = 1) +\n theme(aspect.ratio=1)+ # make the plot square \n labs(x = \"Time\", y = \"Cell number\")\n\nggplot(data, aes(x = Time, y = LogN)) +\n geom_point(size = 3) +\n geom_line(data = df1, aes(x = Time, y = log(N), col = model), size = 1) +\n theme(aspect.ratio=1)+ \n labs(x = \"Time\", y = \"log(Cell number)\")\n\nggplot(data, aes(x = N, y = LogN)) +\n geom_point(size = 3) +\n theme(aspect.ratio = 1)+ \n labs(x = \"N\", y = \"log(N)\")\n\ngompertz_model <- function(t, r_max, K, N_0, t_lag){ # Modified gompertz growth model (Zwietering 1990)\n return(N_0 + (K - N_0) * exp(-exp(r_max * exp(1) * (t_lag - t)/((K - N_0) * log(10)) + 1)))\n} \n\nN_0_start <- min(data$LogN) # lowest population size, note log scale\nK_start <- max(data$LogN) # highest population size, note log scale\nr_max_start <- 0.62 # use our previous estimate from the OLS fitting from above\nt_lag_start <- data$Time[which.max(diff(diff(data$LogN)))] # find last timepoint of lag phase\n\ndiff(data$LogN) # same as what we did above - get differentials\n\ndiff(diff(data$LogN)) # get the differentials of the differentials (approx 2nd order derivatives)\n\nwhich.max(diff(diff(data$LogN))) # find the timepoint where this 2nd order derivative really takes off \n\ndata$Time[which.max(diff(diff(data$LogN)))] # This then is a good guess for the last timepoint of the lag phase\n\nfit_gompertz <- nlsLM(LogN ~ gompertz_model(t = Time, r_max, K, N_0, t_lag), data,\n list(t_lag=t_lag_start, r_max=r_max_start, N_0 = N_0_start, K = K_start))\n\nsummary(fit_gompertz)\n\ntimepoints <- seq(0, 24, 0.1)\n\nlogistic_points <- log(logistic_model(t = timepoints, \n r_max = coef(fit_logistic)[\"r_max\"], \n K = coef(fit_logistic)[\"K\"], \n N_0 = coef(fit_logistic)[\"N_0\"]))\n\ngompertz_points <- gompertz_model(t = timepoints, \n r_max = coef(fit_gompertz)[\"r_max\"], \n K = coef(fit_gompertz)[\"K\"], \n N_0 = coef(fit_gompertz)[\"N_0\"], \n t_lag = coef(fit_gompertz)[\"t_lag\"])\n\ndf1 <- data.frame(timepoints, logistic_points)\ndf1$model <- \"Logistic model\"\nnames(df1) <- c(\"Time\", \"LogN\", \"model\")\n\ndf2 <- data.frame(timepoints, gompertz_points)\ndf2$model <- \"Gompertz model\"\nnames(df2) <- c(\"Time\", \"LogN\", \"model\")\n\nmodel_frame <- rbind(df1, df2)\n\nggplot(data, aes(x = Time, y = LogN)) +\n geom_point(size = 3) +\n geom_line(data = model_frame, aes(x = Time, y = LogN, col = model), size = 1) +\n theme_bw() + # make the background white\n theme(aspect.ratio=1)+ # make the plot square \n labs(x = \"Time\", y = \"log(Abundance)\")\n", "meta": {"hexsha": "d171056e0458e9ddd2022f1f1252e0f5046c908d", "size": 11661, "ext": "r", "lang": "R", "max_stars_repo_path": "content/_build/jupyter_execute/notebooks/20-ModelFitting-NLLS.r", "max_stars_repo_name": "mhasoba/TheMulQuaBio", "max_stars_repo_head_hexsha": "78b5b65fd910f077df347eb8e9da9f7ff3539a9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-10-03T08:48:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T21:26:35.000Z", "max_issues_repo_path": "content/_build/jupyter_execute/notebooks/20-ModelFitting-NLLS.r", "max_issues_repo_name": "mhasoba/TheMulQuaBio", "max_issues_repo_head_hexsha": "78b5b65fd910f077df347eb8e9da9f7ff3539a9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2020-10-02T05:33:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T11:44:01.000Z", "max_forks_repo_path": "content/_build/jupyter_execute/notebooks/20-ModelFitting-NLLS.r", "max_forks_repo_name": "mhasoba/TheMulQuaBio", "max_forks_repo_head_hexsha": "78b5b65fd910f077df347eb8e9da9f7ff3539a9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63, "max_forks_repo_forks_event_min_datetime": "2017-12-04T14:08:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T11:37:36.000Z", "avg_line_length": 33.898255814, "max_line_length": 193, "alphanum_fraction": 0.6588628763, "num_tokens": 4181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.8558511396138366, "lm_q1q2_score": 0.8073650927627171}} {"text": "library(deSolve)\nlibrary(simecol)\nlibrary(reshape2)\nlibrary(ggplot2)\n\n\nsirforcedode <- new(\"odeModel\",\n main = function(time, init, parms, ...){\n with(as.list(c(init,parms)),{\n # ODEs\n N <- S+I+R\n dS <- mu*N-beta(beta0,beta1,omega,time)*S*I/N-mu*S\n dI <- beta(beta0,beta1,omega,time)*S*I/N-gamma*I-mu*I\n dR <- gamma*I-mu*R\n list(c(dS,dI,dR))\n })},\n equations = list(\n beta = function(beta0,beta1,omega,time){beta0*(1+beta1*sin(omega*time))}\n ),\n parms = c(beta0=10./7,beta1=0.05,omega=2*pi/365,gamma=1./7,mu=1./(70*365)),\n times = c(from=0,to=100*365,by=1),\n init = c(S=99999,I=1,R=0),\n solver = \"lsoda\"\n)\n\n# Simulate until equilibrium\nsirforcedode <- sim(sirforcedode)\n# Reset initial values\ninit(sirforcedode) <- unlist(out(sirforcedode)[100*365,2:4])\n# Look at 10 years\ntimes(sirforcedode) <- c(from=0,to=10*365,by=1)\n# Simulate\nsirforcedode <- sim(sirforcedode)\n\nsirforced_out <- out(sirforcedode)\nsirforced_out_long <- melt(sirforced_out,\"time\")\n\n# Plot\nggplot(sirforced_out_long[sirforced_out_long$variable==\"I\",],aes(x=time,y=value,colour=variable,group=variable)) +\n geom_line(lwd=2) + xlab(\"Time\")+ylab(\"Number\") + theme(legend.position=\"none\")\n", "meta": {"hexsha": "901d383bb9d06a6c0f34598f357f3d7931e4cd75", "size": 1201, "ext": "r", "lang": "R", "max_stars_repo_path": "models/time_varying_parameters/seasonally_forced_deterministic.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/time_varying_parameters/seasonally_forced_deterministic.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/time_varying_parameters/seasonally_forced_deterministic.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.2926829268, "max_line_length": 114, "alphanum_fraction": 0.6669442132, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.8072989198629338}} {"text": "## 2. Fitting a Bivariate Linear Regression Model ##\n\nlibrary(readr)\nwilliamsburg_north <- suppressMessages(read_csv(\"williamsburg_north.csv\"))\ncondos_lm_fit <- lm(sale_price ~ gross_square_feet, data = williamsburg_north)\nsummary(condos_lm_fit)\n\n## 3. Estimating the Slope ##\n\nslope <- function(predictor, response){\n mean_predictor <- mean(predictor)\n mean_response <- mean(response)\n numerator <- sum((predictor - mean_predictor) * (response - mean_response))\n denominator <- sum((predictor - mean_predictor)^2)\n beta_1 <- numerator / denominator\n beta_1\n}\n\ncondos_slope <- slope(predictor = williamsburg_north$gross_square_feet, \n response = williamsburg_north$sale_price)\n\nslope_equal <- dplyr::near(condos_slope, coef(condos_lm_fit)[[2]])\n\n## 4. Estimating the Intercept ##\n\ncondos_slope <- slope(predictor = williamsburg_north$gross_square_feet, \n response = williamsburg_north$sale_price)\nintercept <- function(predictor, response, slope){\n beta_0 <- mean(response) - (slope * mean(predictor))\n beta_0\n}\n\ncondos_intercept <- intercept(predictor = williamsburg_north$gross_square_feet, \n response = williamsburg_north$sale_price, \n slope = condos_slope)\n\nintercept_equal <- dplyr::near(condos_intercept, coef(condos_lm_fit)[[1]])\n\n## 5. Visualizing Model Fit ##\n\nlibrary(ggplot2)\nggplot(data = williamsburg_north, \n aes(x = gross_square_feet, y = sale_price)) +\n geom_point() +\n scale_y_continuous(labels = scales::comma) +\n geom_smooth(method = \"lm\", se = FALSE) + \n geom_abline(aes(intercept = coef(condos_lm_fit)[[1]], \n slope = coef(condos_lm_fit)[[2]]), \n color = \"black\", \n linetype = \"dashed\",\n size = 1)\n\n## 6. Estimating the Predictions ##\n\nlibrary(dplyr)\ncondos_lm_fit <- lm(sale_price ~ gross_square_feet, data = williamsburg_north)\n\nwilliamsburg_north <- williamsburg_north %>% \n mutate(predictions = coef(condos_lm_fit)[[1]] + \n coef(condos_lm_fit)[[2]] * gross_square_feet)\n\nnear <- dplyr::near(williamsburg_north$predictions, fitted(condos_lm_fit))\n\n## 7. Estimating the Residuals ##\n\nwilliamsburg_north <- williamsburg_north %>%\n mutate(residuals = sale_price - predictions)\n\nnear <- dplyr::near(williamsburg_north$residuals, resid(condos_lm_fit))\n\n## 8. Estimating the Residual Sum of Squares ##\n\nwilliamsburg_north <- williamsburg_north %>% \n mutate(resid_squared = residuals^2)\n\nRSS <- williamsburg_north %>% \n summarise(RSS = sum(resid_squared)) %>% \n pull()\n\nRSS_from_lm <- deviance(condos_lm_fit)", "meta": {"hexsha": "21f6df625b164a84e6ace2a8205af1817ddf4354", "size": 2614, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 6 - Predictive Modeling and Machine Learning in R/1. Linear Regression Modeling in R/3. Estimating the Coefficients and Fitting Linear Models.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 6 - Predictive Modeling and Machine Learning in R/1. Linear Regression Modeling in R/3. Estimating the Coefficients and Fitting Linear Models.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 6 - Predictive Modeling and Machine Learning in R/1. Linear Regression Modeling in R/3. Estimating the Coefficients and Fitting Linear Models.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": 32.675, "max_line_length": 80, "alphanum_fraction": 0.6947207345, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693723881865, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.80719160015302}} {"text": "### クラスタ分析の例\n### - Violent Crime Rates by US State\n\n## データの読み込み (\"datasets::USArrests\"を用いる)\ndata(USArrests) # データの読み込み\n\n## データの内容を確認\nhelp(USArrests) # 内容の詳細を表示\n## print(USArrests) # 全データの表示\nhead(USArrests,n=5) # 最初の5個を表示\n## tail(USArrests,n=5) # 最後の5個を表示\n\n## 距離の計算\nd <- dist(USArrests) # 標準はユークリッド距離\nclass(d) # オブジェクトクラスの確認\n## print(d) # 計算した距離行列の表示\n## dist class から行列への変換\ndmat <- as.matrix(d)\ndmat[1:5,1:5] # 一部のみ表示\n## 行列から dist class への変換 (下三角行列)\nas.dist(dmat[1:5,1:5]) \n\n## マンハッタン距離の計算\ndm <- dist(USArrests,method='manhattan')\nas.matrix(dm)[1:5,1:5]\n\n## 正規化(平均0,分散1)したユークリッド距離の計算\nds <- dist(scale(USArrests))\nas.matrix(ds)[1:5,1:5]\n\n## 最長距離法による階層的クラスタリング: 図(a)\nhc <- hclust(ds) # クラスタリング\npar(family=\"HiraMaruProN-W4\") # 日本語フォントの指定\nplot(hc,main=\"最長距離法によるデンドログラム\") # デンドログラムの表示\n## デンドログラムの表示変更: 図(b)\nplot(hc,hang=-1,main=\"表示の変更\")\n\n## ウォード法による階層的クラスタリング: 図(c)\nhc <- hclust(ds,method=\"ward.D2\") # method の指定\nplot(hc,hang=-1,main=\"ウォード法によるデンドログラム\")\n## デンドログラムに基づくグループ分け\nrect.hclust(hc,k=10,border='red') # 10個のグループに分ける\n(grp <- cutree(hc, k=10)) # 各データの属するグループ\n\n## グループごとのデンドログラム: 図(d)\ncl <- NULL # 空の配列を用意する\nfor(k in 1:10){\n cl <- rbind(cl, colMeans(scale(USArrests)[grp==k,,drop=F]))\n}\ncl # 10グループのデータ(平均値)にまとめたもの\nplot(hclust(dist(cl),method=\"ward.D2\",\n members=table(grp))) # グループ内の個数を指定\n", "meta": {"hexsha": "ac3ceb1bbd936792ccbe6a1a524529d990555955", "size": 1349, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/code/c-usarrests.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/c-usarrests.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/c-usarrests.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": 25.4528301887, "max_line_length": 63, "alphanum_fraction": 0.6612305411, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.8069694299590129}} {"text": "#' Linear correlated data generator\n#'\n#' @description Simulates linear correlated data\n#'\n#' @param n number of observations\n#' @param p_sim pearson linear correlation coefficient\n#' @param tol tolerance between the simulated and estimated correlation\n#'\n#' @return data.frame with 2 numeric correlated series and both the simulated and estimated pearson linear coefficient\n#' @export\n#'\n#' @examples\n#'\n#' df <- r_pearson(n = 100, p_sim = .8, mean = 3)\n#'\n#' head(df)\n#'\n#' plot(df)\n#'\n\nr_pearson <-\n function(\n n = 25,\n p_sim = 0.50,\n tol = 0.10,\n ...){\n\n if(!is.numeric(n)){\n stop(\"n must be numeric.\")\n }\n\n if(!is.numeric(p_sim)){\n stop(\"p_sim must be numeric.\")\n }\n\n if(!is.numeric(tol)){\n stop(\"tol must be numeric.\")\n }\n\n if(n <= 0){\n stop(\"n must be > 0.\")\n }\n\n if((n%%1)!= 0 ){\n stop(\"n must be a integer.\")\n }\n\n if((tol <= 0) | (tol >= 1)){\n stop(\"tol must be (0,1).\")\n }\n\n if((tol > 0) & (tol < .05)){\n warning(\"A low tolerance may cause a infinite loop or a long loading time.\")\n }\n\n if((p_sim > 1) | (p_sim < -1)){\n stop(\"p_sim must be [-1;1].\")\n }\n\n p_stop <- 1\n\n while (p_stop > tol) {\n\n x <- rnorm(n,...)\n\n y <- rnorm(length(x), p_sim*x, sqrt(1-p_sim^2))\n\n p_est <- cor(x,y)\n\n p_stop <- abs(p_sim - p_est)\n\n }\n\n out <-\n dplyr::tibble(\n x = x,\n y = y,\n p_sim = p_sim,\n p_est = p_est\n )\n\n return(out)\n\n}\n", "meta": {"hexsha": "58d6b7a0bc06d1d32c2ad4c4361551127445e334", "size": 1417, "ext": "r", "lang": "R", "max_stars_repo_path": "R/r_pearson.r", "max_stars_repo_name": "vbfelix/relper", "max_stars_repo_head_hexsha": "edb2f21087857eb4a3f44cf2af9292db632fe210", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-09T23:13:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T00:45:50.000Z", "max_issues_repo_path": "R/r_pearson.r", "max_issues_repo_name": "vbfelix/relper", "max_issues_repo_head_hexsha": "edb2f21087857eb4a3f44cf2af9292db632fe210", "max_issues_repo_licenses": ["MIT"], "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_pearson.r", "max_forks_repo_name": "vbfelix/relper", "max_forks_repo_head_hexsha": "edb2f21087857eb4a3f44cf2af9292db632fe210", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-17T12:27:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T12:50:55.000Z", "avg_line_length": 16.6705882353, "max_line_length": 118, "alphanum_fraction": 0.5539872971, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.8067489420956894}} {"text": "###############\r\n## Section 3 ##\r\n###############\r\n\r\nlibrary(MASS) \r\n\r\nsetwd(\"C:\\\\dc_book\\\\Replication_Files_Element\")\r\n\r\nITN.data <- read.csv(\"ITN_data.csv\", header=TRUE)\r\n\r\n###############\r\n## Table 3.1 ##\r\n###############\r\n\r\nITN.logit <- glm(useditn ~ malariamessage+education+richest+poorest+pregnant+altitude, family=binomial(link=\"logit\"), data=ITN.data, x=TRUE)\r\nbeta <- ITN.logit$coefficients\r\ncovmat.beta <- vcov(ITN.logit)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nbaseline.x <- apply(ITN.logit$x, 2, min)\r\nbaseline.x[\"altitude\"] <- median(ITN.data$altitude)\r\nbaseline.x[\"education\"] <- median(ITN.data$education)\r\nbaseline.x[\"poorest\"] <- 1\r\n\r\nhypo.case.A0 <- baseline.x\r\nsimprob.A0 <- plogis(betadraw%*%hypo.case.A0)\r\n\r\nhypo.case.B0 <- baseline.x\r\nhypo.case.B0[\"malariamessage\"] <- 1\r\nsimprob.B0 <- plogis(betadraw%*%hypo.case.B0)\r\n\r\nsimprob.diff0 <- simprob.B0 - simprob.A0\r\n\r\n## Varying Altitude, Rural = 1\r\n\r\nhypo.case.A1 <- hypo.case.A0\r\nhypo.case.A1[\"poorest\"] <- 0\r\nhypo.case.A1[\"richest\"] <- 1\r\nsimprob.A1 <- plogis(betadraw%*%hypo.case.A1)\r\n\r\nhypo.case.B1 <- hypo.case.B0\r\nhypo.case.B1[\"poorest\"] <- 0\r\nhypo.case.B1[\"richest\"] <- 1\r\nsimprob.B1 <- plogis(betadraw%*%hypo.case.B1)\r\n\r\nsimprob.diff1 <- simprob.B1 - simprob.A1\r\n\r\n## Difference in Differences\r\n\r\nsimprob.dd <- simprob.diff1 - simprob.diff0\r\n\r\n## summarize results\r\n\r\nresults.A0 <- append(quantile(simprob.A0, probs=c(0.5, 0.025, 0.975)), sd(simprob.A0))\r\nresults.B0 <- append(quantile(simprob.B0, probs=c(0.5, 0.025, 0.975)), sd(simprob.B0))\r\nresults.diff0 <- append(quantile(simprob.diff0, probs=c(0.5, 0.025, 0.975)), sd(simprob.diff0))\r\n\r\nresults.A1 <- append(quantile(simprob.A1, probs=c(0.5, 0.025, 0.975)), sd(simprob.A1))\r\nresults.B1 <- append(quantile(simprob.B1, probs=c(0.5, 0.025, 0.975)), sd(simprob.B1))\r\nresults.diff1 <- append(quantile(simprob.diff1, probs=c(0.5, 0.025, 0.975)), sd(simprob.diff1))\r\n\r\nresults.dd <- append(quantile(simprob.dd, probs=c(0.5, 0.025, 0.975)), sd(simprob.dd))\r\n\r\nfirst.differences <- rbind(results.A0, results.B0, results.diff0, results.A1, results.B1, results.diff1, results.dd)\r\ncolnames(first.differences) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(first.differences) <- c(\"No Message:Poor\", \"Message:Poor\", \"Difference:Poor\", \"No Message:Rich\", \"Message:Rich\", \"Difference:Rich\", \"Difference:(Rich-Poor)\")\r\nprint(round(first.differences, digits=3))\r\n\r\n################\r\n## Figure 3.1 ##\r\n################\r\n\r\nbeta <- ITN.logit$coefficients\r\ncovmat.beta <- vcov(ITN.logit)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\naltitude <- seq(0,2.5,0.01)\r\n\r\nmean.x <- colMeans(ITN.logit$x)\r\nsimcoef.mean <- matrix(NA, length(altitude), 4)\r\nsimprob.all <- matrix(NA, ndraws, length(altitude))\r\n\r\nfor (i in 1:length(altitude)) {\r\n\tmean.x[\"altitude\"] <- altitude[i]\r\n\tsimprob <- plogis(betadraw%*%mean.x)\r\n\tsimcoef.mean[i,] <- append(altitude[i], quantile(simprob, probs=c(0.025, 0.5, 0.975)))\r\n\tsimprob.all[,i] <- simprob\r\n}\r\n\r\nci.bottom <- cbind(simcoef.mean[,1], simcoef.mean[,2])\r\nci.top <- cbind(simcoef.mean[,1], simcoef.mean[,4])\r\nci.top <- ci.top[order(ci.top[,1], decreasing=TRUE),]\r\nci <- rbind(ci.bottom, ci.top)\r\n\r\n\r\npdf(\"fig31a.pdf\")\r\npar(mar=c(5.1, 4.1, 4.1, 3.1), mgp=c(2.5, 1, 0), cex.lab=1.5)\r\nplot(simcoef.mean[,3]~simcoef.mean[,1], xlim=c(0.5,2.1), ylim=c(0.5,1), type=\"n\", xlab=\"Altitude (1000s of meters)\", ylab=\"Probability\", xaxt=\"n\", las=1)\r\naxis(1, at=c(0.5, 1, 1.5, 2))\r\npolygon(ci[,1], ci[,2], col=\"grey75\", border=NA)\r\nlines(simcoef.mean[,3]~simcoef.mean[,1], lwd=2, lty=1)\r\nbox(lty=1) \r\ndev.off()\r\n\r\npdf(\"fig31b.pdf\")\r\npar(mar=c(5.1, 4.1, 4.1, 3.1), mgp=c(2.5, 1, 0), cex.lab=1.5)\r\nplot(simcoef.mean[,3]~simcoef.mean[,1], xlim=c(0.5,2.1), ylim=c(0.5,1), type=\"n\", xlab=\"Altitude (1000s of meters)\", ylab=\"Probability\", xaxt=\"n\", las=1)\r\naxis(1, at=c(0.5, 1, 1.5, 2))\r\nfor (i in 1:length(altitude)){\r\n\tpoints(simprob.all[i,] ~ altitude, type=\"l\", col=rgb(0,0,0,alpha=0.2), lwd=1)\r\n}\r\ndev.off()\r\n\r\n\r\n###############\r\n## Table 3.2 ##\r\n###############\r\n\r\n## aggregate shares \r\n\r\none <- 1\r\nXall <- as.data.frame(na.omit(cbind(one, subset(ITN.data, select=c(malariamessage, education, richest, poorest, pregnant, altitude, sample_weight, useditn)))))\r\nX <- subset(Xall, select=c(one, malariamessage, education, richest, poorest, pregnant, altitude))\r\ny <- Xall$useditn\r\nw <- 1/Xall$sample_weight\r\n\r\nX2 <- X\r\nX2$malariamessage <- 1\r\n\r\nbeta <- ITN.logit$coefficients\r\ncovmat.beta <- vcov(ITN.logit)\r\n\r\n\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\naggdraw <- matrix(NA,ndraws,1)\r\naggdraw2 <- matrix(NA,ndraws,1)\r\n\r\n\r\n\r\nfor (j in 1:ndraws) { \r\n proby1 <- plogis(betadraw[j,]%*%t(X))\r\n aggshare <- sum(proby1*w)/sum(w)\r\n aggdraw[j] <- aggshare*100\r\n proby1.2 <- plogis(betadraw[j,]%*%t(X2))\r\n aggshare2 <- sum(proby1.2*w)/sum(w)\r\n aggdraw2[j] <- aggshare2*100\r\n }\r\n\r\naggdraw.diff <- aggdraw2 - aggdraw\r\n\r\nsummary.aggshare <- append(quantile(aggdraw, probs=c(0.5, 0.025, 0.975)), sd(aggdraw)) \r\nsummary.aggshare2 <- append(quantile(aggdraw2, probs=c(0.5, 0.025, 0.975)), sd(aggdraw2)) \r\nsummary.aggshare.diff <- append(quantile(aggdraw.diff, probs=c(0.5, 0.025, 0.975)), sd(aggdraw.diff)) \r\n\r\n\r\naggregate.prediction <- rbind(summary.aggshare, summary.aggshare2, summary.aggshare.diff)\r\ncolnames(aggregate.prediction) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(aggregate.prediction) <- c(\"Current Message\", \"Complete Message\", \"Difference\")\r\nprint(round(aggregate.prediction, digits=3))\r\n\r\n###############\r\n## Table 3.3 ##\r\n###############\r\n\r\nbeta <- ITN.logit$coefficients\r\ncovmat.beta <- vcov(ITN.logit)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nw <- ITN.data$sample_weight \r\n\r\n# AME\r\n\r\npredprobs <- plogis(betadraw %*% t(ITN.logit$x))\r\n\r\nmarginal.ame.matrix <- predprobs * (1 - predprobs) * betadraw[,\"altitude\"]\r\n\r\nmarginal.ame <- apply(marginal.ame.matrix, 1, function(x) {sum(x * w)/sum(w)})\r\n\r\nelasticity.ame.matrix <- marginal.ame.matrix * t(ITN.logit$x[,\"altitude\"] / t(predprobs))\r\n\r\nelasticity.ame <- apply(elasticity.ame.matrix, 1, function(x) {sum(x * w)/sum(w)})\r\n\r\n# MEM\r\n\r\nmean.x <- colMeans(ITN.logit$x)\r\nbeta <- ITN.logit$coefficients\r\ncovmat.beta <- vcov(ITN.logit)\r\n\r\nndraws <- 1000\r\n\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\npredprob <- plogis(betadraw%*%mean.x)\r\n\r\nmarginal.mem <- predprob * (1 - predprob) * betadraw[,\"altitude\"]\r\n\r\nelasticity.mem <- marginal.mem * (mean.x[\"altitude\"] / predprob)\r\n\r\n## combine results\r\n\r\nsummary.marginal.ame <- append(quantile(marginal.ame, probs=c(0.5, 0.025, 0.975)), sd(marginal.ame))\r\nsummary.marginal.mem <- append(quantile(marginal.mem, probs=c(0.5, 0.025, 0.975)), sd(marginal.mem))\r\nsummary.elasticity.ame <- append(quantile(elasticity.ame, probs=c(0.5, 0.025, 0.975)), sd(elasticity.ame))\r\nsummary.elasticity.mem <- append(quantile(elasticity.mem, probs=c(0.5, 0.025, 0.975)), sd(elasticity.mem))\r\n\r\nmarginal.effects.elasticities <- rbind(summary.marginal.ame, summary.marginal.mem, summary.elasticity.ame, summary.elasticity.mem)\r\ncolnames(marginal.effects.elasticities) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(marginal.effects.elasticities) <- c(\"Marginal Effect (AME)\", \"Marginal Effect (MEM)\", \"Elasticity (AME)\", \"Elasticity (MEM)\")\r\nprint(round(marginal.effects.elasticities, digits=3))\r\n\r\n\r\n## additional example: MEM by brute force --- note this is actually a first difference\r\n\r\nmean.x2 <- mean.x\r\nmean.x2[\"altitude\"] <- mean.x2[\"altitude\"] + 0.0001\r\nprobs1 <- plogis(betadraw %*% mean.x)\r\nprobs2 <- plogis(betadraw %*% mean.x2)\r\nprobs.diff <- (probs2 - probs1) * 10000 # for a 1-unit change\r\nquantile(probs.diff, probs=c(0.5, 0.025, 0.975))\r\n\r\n\r\n## Elasticity at the mean by brute force\r\nelast.mem <- probs.diff * (mean.x2[\"altitude\"] / probs1)\r\nquantile(elast.mem, probs=c(0.5, 0.025, 0.975))\r\n\r\n## coefficient ratios\r\n\r\nmalariamessage.altitude.ratio <- betadraw[,\"malariamessage\"]/betadraw[,\"altitude\"]\r\nratio.results <- quantile(malariamessage.altitude.ratio, probs=c(0.5, 0.025, 0.975))\r\nprint(ratio.results)\r\n\r\n\r\n###############\r\n## Table 3.4 ##\r\n###############\r\n\r\nN <- length(ITN.logit$fitted.values)\r\n\r\nbeta <- ITN.logit$coefficients\r\ncovmat.beta <- vcov(ITN.logit)\r\nndraws <- 1000\r\n\r\n# calculating confidence intervals and standard error via simulation\r\n\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\nexp.betadraw <- exp(betadraw)\r\nquantiles <- apply(exp.betadraw, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(exp.betadraw, 2, sd)\r\nodds.ratios <- cbind(t(quantiles), sds)\r\ncolnames(odds.ratios) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(odds.ratios) <- names(beta) \r\nprint(round(odds.ratios, digits=3))\r\nprint(N)\r\n\r\n# alternative calculation exponentiating endpoints of coefficient CI and using delta method for standard errors\r\n\r\nbeta.OR <- exp(ITN.logit$coefficients)\r\nse.OR <- exp(ITN.logit$coefficients) * sqrt(diag(vcov(ITN.logit)))\r\nCI.OR <- exp(confint.default(ITN.logit, level=0.95))\r\n\r\nITN.logit.results.OR <- cbind(beta.OR, CI.OR, se.OR)\r\nN <- length(ITN.logit$fitted.values)\r\ncolnames(ITN.logit.results.OR) <- c(\"Coeff\", \"2.5%\", \"97.5%\", \"(se)\")\r\nprint((round(ITN.logit.results.OR, digits=3)))\r\n\r\n", "meta": {"hexsha": "d265e30a37267e7ee4b752a046027c2dfa653f48", "size": 9209, "ext": "r", "lang": "R", "max_stars_repo_path": "R Code/Section3.r", "max_stars_repo_name": "GarrettGlasgow/interpreting-discrete-choice-models", "max_stars_repo_head_hexsha": "918a5cc6ee3b291c8ae849f7caa474849b451b22", "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 Code/Section3.r", "max_issues_repo_name": "GarrettGlasgow/interpreting-discrete-choice-models", "max_issues_repo_head_hexsha": "918a5cc6ee3b291c8ae849f7caa474849b451b22", "max_issues_repo_licenses": ["MIT"], "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 Code/Section3.r", "max_forks_repo_name": "GarrettGlasgow/interpreting-discrete-choice-models", "max_forks_repo_head_hexsha": "918a5cc6ee3b291c8ae849f7caa474849b451b22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-21T12:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T12:26:06.000Z", "avg_line_length": 33.9815498155, "max_line_length": 167, "alphanum_fraction": 0.6528396134, "num_tokens": 3199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.8058580650159964}} {"text": "#' Tong et al. (2012)'s Lindley-type Shrunken Mean Estimator\n#'\n#' An implementation of the Lindley-type shrunken mean estimator utilized in\n#' shrinkage-mean-based diagonal linear discriminant analysis (SmDLDA).\n#'\n#' @export\n#' @importFrom stats var\n#' @references Tong, T., Chen, L., and Zhao, H. (2012), \"Improved Mean\n#' Estimation and Its Application to Diagonal Discriminant Analysis,\"\n#' Bioinformatics, 28, 4, 531-537.\n#' \\url{http://bioinformatics.oxfordjournals.org/content/28/4/531.long}\n#' @param x a matrix with `n` rows and `p` columns.\n#' @param r_opt the shrinkage coefficient. If `NULL` (default), we calculate\n#' the shrinkage coefficient with the formula given just above Equation 5 on page\n#' 533 and denoted by \\eqn{\\hat{r}_{opt}}. We allow the user to specify an\n#' alternative value to investigate better approximations.\n#' @return vector of length `p` with the shrunken mean estimator\ntong_mean_shrinkage <- function(x, r_opt = NULL) {\n n <- nrow(x)\n p <- ncol(x)\n\n # Here, we calculate the approximate \"optimal\" shrinkage coefficient, r.\n # The formula is given just above Equation 5 and is denoted \\hat{r}_{opt}.\n if (is.null(r_opt)) {\n r_opt <- (n - 1) * (p - 2) / n / (n - 3)\n } else {\n r_opt <- as.numeric(r_opt)\n }\n\n # The sample means of each feature vector.\n xbar <- colMeans(x)\n \n # Tong et al. calculate the mean of the entire matrix, x.\n grand_mean <- mean(x)\n \n # The authors then center the sample mean for each feature vector.\n centered_xbars <- xbar - grand_mean\n\n # The MLE of the covariance matrix under the assumpton of a multivariate\n # normal population with a diagonal covariance matrix.\n diag_S <- (n - 1) / n * apply(x, 2, var)\n\n # The term in Equation (6) denoted by:\n # || \\bar{x} - \\bar{x}_{\\dot\\dot} ||^2_S\n shrinkage_norm <- sum(centered_xbars^2 / diag_S)\n\n # Finally, we calculate the shrunken mean given in Equation 6.\n if (shrinkage_norm == 0) {\n shrunken_mean <- xbar\n } else {\n shrunken_mean <- grand_mean + (1 - r_opt / shrinkage_norm) * centered_xbars\n }\n\n shrunken_mean\n}\n\n \n \n", "meta": {"hexsha": "3ed1be950c8d4a5f9b029d007f10d1a9bf726397", "size": 2078, "ext": "r", "lang": "R", "max_stars_repo_path": "R/tong-shrinkage.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/tong-shrinkage.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/tong-shrinkage.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": 35.2203389831, "max_line_length": 81, "alphanum_fraction": 0.6881616939, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527684, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.8058367633873307}} {"text": "#' Generates data from `K` multivariate normal data populations, where each\n#' population (class) has an intraclass covariance matrix.\n#'\n#' This function generates `K` multivariate normal data sets, where each\n#' class is generated with a constant mean vector and an intraclass covariance\n#' matrix. The data are returned as a single matrix `x` along with a vector\n#' of class labels `y` that indicates class membership.\n#' \n#' For simplicity, we assume that a class mean vector is constant for each\n#' feature. That is, we assume that the mean vector of the \\eqn{k}th class is\n#' \\eqn{c_k * j_p}, where \\eqn{j_p} is a \\eqn{p \\times 1} vector of ones and\n#' \\eqn{c_k} is a real scalar.\n#' \n#' The intraclass covariance matrix for the \\eqn{k}th class is defined as:\n#' \\deqn{\\sigma_k^2 * (\\rho_k * J_p + (1 - \\rho_k) * I_p),}\n#' where \\eqn{J_p} is the \\eqn{p \\times p} matrix of ones and \\eqn{I_p} is the\n#' \\eqn{p \\times p} identity matrix.\n#'\n#' By default, with \\eqn{\\sigma_k^2 = 1}, the diagonal elements of the intraclass\n#' covariance matrix are all 1, while the off-diagonal elements of the matrix\n#' are all `rho`.\n#' \n#' The values of `rho` must be between \\eqn{1 / (1 - p)} and 1,\n#' exclusively, to ensure that the covariance matrix is positive definite.\n#'\n#' The number of classes `K` is determined with lazy evaluation as the\n#' length of `n`.\n#'\n#' @importFrom mvtnorm rmvnorm\n#' @export\n#' @param n vector of the sample sizes of each class. The length of `n`\n#' determines the number of classes `K`.\n#' @param p the number of features (variables) in the data\n#' @param rho vector of the values of the off-diagonal elements for each\n#' intraclass covariance matrix. Must equal the length of `n`.\n#' @param mu vector containing the mean for each class. Must equal the length of\n#' `n` (i.e., equal to `K`).\n#' @param sigma2 vector of variances for each class. Must equal the length of\n#' `n`. Default is 1 for each class.\n#' @return named list with elements:\n#' \\itemize{\n#' \\item `x`: matrix of observations with `n` rows and `p`\n#' columns\n#' \\item `y`: vector of class labels that indicates class membership for\n#' each observation (row) in `x`.\n#' }\n#' @examples\n#' # Generates data from K = 3 classes.\n#' data <- generate_intraclass(n = 3:5, p = 5, rho = seq(.1, .9, length = 3),\n#' mu = c(0, 3, -2))\n#' data$x\n#' data$y\n#' \n#' # Generates data from K = 4 classes. Notice that we use specify a variance.\n#' data <- generate_intraclass(n = 3:6, p = 4, rho = seq(0, .9, length = 4),\n#' mu = c(0, 3, -2, 6), sigma2 = 1:4)\n#' data$x\n#' data$y\ngenerate_intraclass <- function(n, p, rho, mu, sigma2 = rep(1, K)) {\n p <- as.integer(p)\n rho <- as.numeric(rho)\n n <- as.integer(n)\n mu <- as.numeric(mu)\n\n K <- length(n)\n\n if (length(rho) != K) {\n rlang::abort(\"The length of 'rho' must equal the length of 'n'.\")\n } else if(length(mu) != K) {\n rlang::abort(\"The length of 'mu' must equal the length of 'n'.\")\n } else if(length(sigma2) != K) {\n rlang::abort(\"The length of 'sigma2' must equal the length of 'n'.\")\n }\n\n x <- lapply(seq_len(K), function(k) {\n rmvnorm(n = n[k], mean = rep(mu[k], p),\n sigma = cov_intraclass(p = p, rho = rho[k], sigma2 = sigma2[k]))\n })\n x <- do.call(rbind, x)\n y <- factor(rep(seq_along(n), n))\n \n list(x = x, y = y)\n}\n\n#' Generates a \\eqn{p \\times p} intraclass covariance matrix\n#'\n#' This function generates a \\eqn{p \\times p} intraclass covariance matrix with\n#' correlation `rho`. The variance `sigma2` is constant for each\n#' feature and defaulted to 1.\n#'\n#' The intraclass covariance matrix is defined as:\n#' \\deqn{\\sigma^2 * (\\rho * J_p + (1 - \\rho) * I_p),}\n#' where \\eqn{J_p} is the \\eqn{p \\times p} matrix of ones and \\eqn{I_p} is the\n#' \\eqn{p \\times p} identity matrix.\n#'\n#' By default, with `sigma2 = 1`, the diagonal elements of the intraclass\n#' covariance matrix are all 1, while the off-diagonal elements of the matrix\n#' are all `rho`.\n#' \n#' The value of `rho` must be between \\eqn{1 / (1 - p)} and 1,\n#' exclusively, to ensure that the covariance matrix is positive definite.\n#'\n#' @param p the size of the covariance matrix\n#' @param rho the value of the off-diagonal elements\n#' @param sigma2 the variance of each feature\n#' @return intraclass covariance matrix\ncov_intraclass <- function(p, rho, sigma2 = 1) {\n p <- as.integer(p)\n rho <- as.numeric(rho)\n \n if (rho <= (1 - p)^(-1) || rho >= 1) {\n rlang::abort(\"The value of 'rho' must be between (1 - p)^(-1) and 1, exclusively.\")\n }\n if (sigma2 <= 0) {\n rlang::abort(\"The value of 'sigma2' must be positive.\")\n }\n sigma2 * (rho * matrix(1, nrow = p, ncol = p) + (1 - rho) * diag(p))\n}\n", "meta": {"hexsha": "88f8be88d0650deb8fdfba2fefc03c03afb746af", "size": 4716, "ext": "r", "lang": "R", "max_stars_repo_path": "R/data-intraclass.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/data-intraclass.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/data-intraclass.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.6302521008, "max_line_length": 87, "alphanum_fraction": 0.645250212, "num_tokens": 1441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104865, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.8056861486559584}} {"text": "library(repr) ; options(repr.plot.width = 5, repr.plot.height = 6) # Change plot sizes (in cm)\n\nrm(list = ls())\ngraphics.off()\n\nset.seed(54321)\n\n## 50 draws with each p \npp <- c(0.1, 0.5, 0.8)\nN <- 20\nreps <- 50 \n\n## histograms + density here\nx <- seq(0, 50, by=1)\npar(mfrow=c(1,3), bty=\"n\")\n\n# Write more code here\n\n## MOM estimators for 3 simulated sets\n\n\n## MoM estimates, histogram \n\npp <- .25\nN <- 10\nreps <- 10\n## Make one set of data\n\n## the likelihood is always exactly zero\n## at p=0,1, so I skip those values\nps <- seq(0.01, 0.99, by=0.01) \n\n## Likelihood\n\n\n## MLE/MoM estimators \n\n## now plot the negative log likelihood profile\n\n\nWL.data <- read.csv(\"../data/MidgeWingLength.csv\")\nY <- WL.data$WingLength\nn <- length(Y)\n\nhist(Y,breaks=10,xlab=\"Wing Length (mm)\") \n\nm <- sum(Y)/n\ns2 <- sum((Y-m)^2)/(n-1)\nround(c(m, s2), 3)\n\nx <- seq(1.4,2.2, length=50)\nhist(Y,breaks=10,xlab=\"Wing Length (mm)\", xlim=c(1.4, 2.2), freq=FALSE) \nlines(x, dnorm(x, mean=m, sd=sqrt(s2)), col=2)\n\ntau.post <- function(tau, tau0, n){n * tau + tau0}\nmu.post <- function(Ybar, mu0, sig20, sig2, n){\n weight <- sig2+n * sig20\n \n return(n * sig20 * Ybar/weight + sig2 * mu0/weight)\n}\n\nmu0 <- 1.9\ns20 <- 0.8\ns2 <- 0.025 ## \"true\" variance\n\nmp <- mu.post(Ybar=m, mu0=mu0, sig20=s20, sig2=s2, n=n)\ntp <- tau.post(tau=1/s2, tau0=1/s20, n=n)\n\nx <- seq(1.3,2.3, length=1000)\nhist(Y,breaks=10,xlab=\"Wing Length (mm)\", xlim=c(1.3, 2.3),\n freq=FALSE, ylim=c(0,8)) \nlines(x, dnorm(x, mean=mu0, sd=sqrt(s20)), col=2, lty=2, lwd=2) ## prior\nlines(x, dnorm(x, mean=mp, sd=sqrt(1/tp)), col=4, lwd=2) ## posterior\nlegend(\"topleft\", legend=c(\"prior\", \"posterior\"), col=c(2,4), lty=c(2,1), lwd=2)\n\n# Load libraries\nrequire(rjags) # does the fitting\nrequire(coda) # makes diagnostic plots\n##require(mcmcplots) # another option for diagnostic plots\n\nmodel1 <- \"model{\n\n ## Likelihood\n for(i in 1:n){\n Y[i] ~ dnorm(mu,tau)\n }\n\n ## Prior for mu\n mu ~ dnorm(mu0,tau0)\n\n} ## close model \n\"\n\nmodel <- jags.model(textConnection(model1), \n n.chains = 1, ## usually do more\n data = list(Y=Y,n=n, ## data\n mu0=mu0, tau0=1/s20, ## hyperparams\n tau = 1/s2 ## known precision\n ),\n inits=list(mu=3) ## setting an starting val\n )\n\nsamp <- coda.samples(model, \n variable.names=c(\"mu\"), \n n.iter=1000, progress.bar=\"none\")\n\nplot(samp)\n\nupdate(model, 10000, progress.bar=\"none\") # Burnin for 10000 samples\n\nsamp <- coda.samples(model, \n variable.names=c(\"mu\"), \n n.iter=20000, progress.bar=\"none\")\n\nplot(samp)\n\nsummary(samp)\n\nx <- seq(1.3,2.3, length=1000)\nhist(samp[[1]], xlab=\"mu\", xlim=c(1.3, 2.3),\n freq=FALSE, ylim=c(0,8), main =\"posterior samples\") \nlines(x, dnorm(x, mean=mu0, sd=sqrt(s20)), col=2, lty=2, lwd=2) ## prior\nlines(x, dnorm(x, mean=mp, sd=sqrt(1/tp)), col=4, lwd=2) ## posterior\nlegend(\"topleft\", legend=c(\"prior\", \"analytic posterior\"), col=c(2,4), lty=c(2,1), lwd=2)\n\nmodel2 <- \"model{\n\n # Likelihood\n for(i in 1:n){\n Y[i] ~ dnorm(mu,tau) T(0,) ## truncates at 0\n }\n\n # Prior for mu\n mu ~ dnorm(mu0,tau0)\n\n # Prior for the precision\n tau ~ dgamma(a, b)\n\n # Compute the variance\n s2 <- 1/tau\n}\"\n\n## hyperparams for tau\na <- 0.01\nb <- 0.01\n\nm2 <- jags.model(textConnection(model2), \n n.chains = 1,\n data = list(Y=Y, n=n,\n mu0=mu0, tau0=1/s20, ## mu hyperparams\n a=a, b=b ## tau hyperparams\n ),\n inits=list(mu=3, tau=10) ## starting vals\n )\n\nsamp <- coda.samples(m2, \n variable.names=c(\"mu\",\"s2\"), \n n.iter=1000, progress.bar=\"none\")\n\nplot(samp)\n\nsummary(samp)\n\npar(mfrow=c(1,2), bty=\"n\")\n\nhist(samp[[1]][,1], xlab=\"samples of mu\", main=\"mu\")\nlines(x, dnorm(x, mean=mu0, sd=sqrt(s20)), \n col=2, lty=2, lwd=2) ## prior\n\nx2 <- seq(0, 200, length=1000)\nhist(1/samp[[1]][,2], xlab=\"samples of tau\", main=\"tau\")\nlines(x2, dgamma(x2, shape = a, rate = b), \n col=2, lty=2, lwd=2) ## prior\n\nplot(as.numeric(samp[[1]][,1]), samp[[1]][,2], xlab=\"mu\", ylab=\"s2\")\n\nrequire(R2jags) # fitting\nrequire(coda) # diagnostic plots\nset.seed(1234)\n\nAaeg.data <- read.csv(\"../data/AeaegyptiTraitData.csv\")\n\nhead(Aaeg.data)\n\nmu.data <- subset(Aaeg.data, trait.name == \"mu\")\nlf.data <- subset(Aaeg.data, trait.name == \"1/mu\")\npar(mfrow=c(1,2), bty=\"l\") \nplot(trait ~ T, data = mu.data, ylab=\"mu\")\nplot(trait ~ T, data = lf.data, ylab=\"1/mu\")\n\nmu.data.inv <- mu.data # make a copy of the mu data\nmu.data.inv$trait <- 1/mu.data$trait # take the inverse of the trait values to convert mu to lifespan\nlf.data.comb <- rbind(mu.data.inv, lf.data) # combine both lifespan data sets together \n \nplot(trait ~ T, data = lf.data.comb, ylab=\"1/mu\")\n\nsink(\"quad.txt\") # create a file\ncat(\"\n model{\n \n ## Priors\n cf.q ~ dunif(0, 1)\n cf.T0 ~ dunif(0, 24)\n cf.Tm ~ dunif(25, 45)\n cf.sigma ~ dunif(0, 1000)\n cf.tau <- 1 / (cf.sigma * cf.sigma)\n \n ## Likelihood\n for(i in 1:N.obs){\n trait.mu[i] <- -1 * cf.q * (temp[i] - cf.T0) * (temp[i] - cf.Tm) * (cf.Tm > temp[i]) * (cf.T0 < temp[i])\n trait[i] ~ dnorm(trait.mu[i], cf.tau)\n }\n \n ## Derived Quantities and Predictions\n for(i in 1:N.Temp.xs){\n z.trait.mu.pred[i] <- -1 * cf.q * (Temp.xs[i] - cf.T0) * (Temp.xs[i] - cf.Tm) * (cf.Tm > Temp.xs[i]) * (cf.T0 < Temp.xs[i])\n }\n } # close model\n\",fill=T)\nsink()\n\n# Parameters to Estimate\nparameters <- c(\"cf.q\", \"cf.T0\", \"cf.Tm\",\"cf.sigma\", \"z.trait.mu.pred\")\n\n# Initial values for the parameters\ninits <- function(){list(\n cf.q = 0.01,\n cf.Tm = 35,\n cf.T0 = 5,\n cf.sigma = rlnorm(1))}\n\n# MCMC Settings: number of posterior dist elements = [(ni - nb) / nt ] * nc\nni <- 25000 # number of iterations in each chain\nnb <- 5000 # number of 'burn in' iterations to discard\nnt <- 8 # thinning rate - jags saves every nt iterations in each chain\nnc <- 3 # number of chains\n\n# Temperature sequence for derived quantity calculations\nTemp.xs <- seq(0, 45, 0.2)\nN.Temp.xs <- length(Temp.xs)\n\n### Fitting the trait thermal response; Pull out data columns as vectors\ndata <- lf.data.comb # this lets us reuse the same generic code: we only change this first line\ntrait <- data$trait\nN.obs <- length(trait)\ntemp <- data$T\n\n# Bundle all data in a list for JAGS\njag.data <- list(trait = trait, N.obs = N.obs, temp = temp, Temp.xs = Temp.xs, N.Temp.xs = N.Temp.xs)\n\nlf.fit <- jags(data=jag.data, inits=inits, parameters.to.save=parameters, \n model.file=\"quad.txt\", n.thin=nt, n.chains=nc, n.burnin=nb, \n n.iter=ni, DIC=T, working.directory=getwd())\n\nlf.fit.mcmc <- as.mcmc(lf.fit)\n\nlf.fit$BUGSoutput$summary[1:5,]\n\nplot(lf.fit.mcmc[,c(1,3,4)])\n\nplot(trait ~ T, xlim = c(0, 45), ylim = c(0,42), data = lf.data.comb, ylab = \"Lifespan for Ae. aegypti\", xlab = \"Temperature\")\nlines(lf.fit$BUGSoutput$summary[6:(6 + N.Temp.xs - 1), \"2.5%\"] ~ Temp.xs, lty = 2)\nlines(lf.fit$BUGSoutput$summary[6:(6 + N.Temp.xs - 1), \"97.5%\"] ~ Temp.xs, lty = 2)\nlines(lf.fit$BUGSoutput$summary[6:(6 + N.Temp.xs - 1), \"mean\"] ~ Temp.xs)\n\nTemp.xs[which.max(as.vector(lf.fit$BUGSoutput$summary[6:(6 + N.Temp.xs - 1), \"mean\"]))]\n\nlf.grad <- lf.fit$BUGSoutput$sims.list$z.trait.mu.pred\ndim(lf.grad) # A matrix with 7500 iterations of the MCMC chains at 226 temperatures\n\nrequire(R2jags) # does the fitting\nrequire(coda) # makes diagnostic plots\nlibrary(IDPmisc) # makes nice colored pairs plots to look at joint posteriors\n\ndat <- read.csv(\"../data/lb_ab_temps.csv\")\nhead(dat)\n\nd2 <- dat[which(dat$EXP==2),2:8]\nd2 <- d2[which(d2$TEMP==12),]\nsummary(d2)\n\nTemps <- seq(0,max(d2$DAY)-1, by=0.05)\nmycol <- 1 \nmy.ylim <- c(0, 0.5)\nmy.title <- \"LB-AB isolate, T=12C\"\n\nplot(d2$DAY-1, d2$OD, xlim=c(0,max(Temps)), ylim=my.ylim,\n pch=(mycol+20),\n xlab=\"time (days)\", ylab=\"\",\n main=my.title,\n col=mycol+1, cex=1.5)\n\nsink(\"jags-logistic.bug\")\ncat(\"\n model {\n \n ## Likelihood\n for (i in 1:N) {\n Y[i] ~ dlnorm(log(mu[i]), tau)\n mu[i] <- K * Y0/(Y0+(K-Y0) * exp(-r * t[i]))\n }\n\n ## Priors\n r~dexp(1000)\n K ~ dunif(0.01, 0.6)\n Y0 ~ dunif(0.09, 0.15)\n tau <- 1/sigma^2\n sigma ~ dexp(0.1)\n\n } # close model\n \",fill=T)\nsink()\n\n# Parameters to Estimate\nparameters <- c('Y0', 'K', 'r', 'sigma')\n\n# Initial values for the parameters\ninits <- function(){list(\n Y0 = 0.1,\n K = 0.4,\n r = 0.1,\n sigma = rlnorm(1))}\n\n# MCMC Settings: number of posterior dist elements = [(ni - nb) / nt ] * nc\nni <- 6000 # number of iterations in each chain\nnb <- 1000 # number of 'burn in' iterations to discard\nnt <- 1 # thinning rate - jags saves every nt iterations in each chain\nnc <- 5 # number of chains\n\n# Pull out data columns as vectors\ndata <- d2 # this lets us reuse the same generic code: we only change this first line\nY <- data$OD\nN <- length(Y)\nt <- data$DAY\n\n# Bundle all data in a list for JAGS\njag.data <- list(Y = Y, N = N, t = t)\n\n# Run JAGS\nOD.12C <- jags(data=jag.data, inits=inits, parameters.to.save=parameters, \n model.file=\"jags-logistic.bug\", n.thin=nt, n.chains=nc, n.burnin=nb, \n n.iter=ni, DIC=T, working.directory=getwd())\n\nOD.12C.mcmc <- as.mcmc(OD.12C)\n\nOD.12C$BUGSoutput$summary\n\nplot(OD.12C.mcmc[,c(1,2,4)])\n\ns1 <- as.data.frame(OD.12C.mcmc[[1]])\npar(mfrow=c(2,2))\nfor(i in 2:5) acf(s1[,i], lag.max=20)\n\nsource(\"../code/mcmc_utils.R\")\n\nsamps <- NULL\nfor(i in 1:nc){\n samps <- rbind(samps, as.data.frame(OD.12C.mcmc[[i]]))\n}\n\nsamps <- samps[,c(5,2,3,4)]\n\npriors <- list()\npriors$names <- c(\"Y0\", \"K\", \"r\",\"sigma\")\npriors$fun <- c(\"uniform\", \"uniform\", \"exp\",\"exp\")\npriors$hyper <- matrix(NA, ncol=4, nrow=3)\npriors$hyper[,1] <- c(0.09, 0.15, NA)\npriors$hyper[,2] <- c(0.01, 0.6, NA)\npriors$hyper[,3] <- c(1000, NA, NA) \npriors$hyper[,4] <- c(0.1, NA, NA)\n\nplot.hists(samps, my.par=c(2,2), n.hists=4, priors=priors, mai=c(0.5, 0.5, 0.25, 0.2))\n\nipairs(s1[,2:5], ztransf = function(x){x[x<1] <- 1; log2(x)})\n\nmy.logistic <- function(t, Y0, K, r){\n return(K * Y0/(Y0+(K-Y0) * exp(-r * t)))\n}\n\nts <- seq(0, 40, length=100)\nss <- seq(1, dim(samps)[1], by=10)\nmy.curves <- matrix(NA, nrow=length(ss), ncol=length(ts))\n\nfor(i in 1:length(ss)){\n my.curves[i,] <- my.logistic(t=ts, Y0=samps$Y0[i], K=samps$K[i], r=samps$r[i])\n}\n\nplot(ts, my.curves[1,], col=1, type=\"l\", ylim=c(0.09, 0.36), \n ylab=\"predicted OD\", xlab=\"time (days)\")\nfor(i in 2:length(ss)) lines(ts, my.curves[i,], col=i)\n\nm.log <- apply(my.curves, 2, mean)\nl.log <- apply(my.curves, 2, quantile, probs=0.025)\nu.log <- apply(my.curves, 2, quantile, probs=0.975)\n\nhpd.log <- NULL\nfor(i in 1:length(ts)){\n hpd.log <- cbind(hpd.log, as.numeric(HPDinterval(mcmc(my.curves[,i]))))\n}\n\nmy.ylim <- c(0.09, 0.45)\nmy.title <- \"LB-AB isolate, T=12C\"\n\nplot(d2$DAY-1, d2$OD, xlim=c(0,max(Temps)), ylim=my.ylim,\n pch=(mycol+20),\n xlab=\"time (days)\", ylab=\"\",\n main=my.title,\n col=\"grey\", cex=1.5)\nlines(ts, m.log, col=1, lwd=2)\nlines(ts, l.log, col=2, lwd=2, lty=2)\nlines(ts, u.log, col=2, lwd=2, lty=2)\n\nlines(ts, hpd.log[1,], col=3, lwd=2, lty=3)\nlines(ts, hpd.log[2,], col=3, lwd=2, lty=3)\n", "meta": {"hexsha": "54d1cf7587ddfe11234775e8f5f23cb27779a5e7", "size": 10703, "ext": "r", "lang": "R", "max_stars_repo_path": "content/_build/jupyter_execute/notebooks/22-ModelFitting-Bayesian.r", "max_stars_repo_name": "nesbitm/VBiTE_2021", "max_stars_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-10-03T08:48:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T21:26:35.000Z", "max_issues_repo_path": "content/_build/jupyter_execute/notebooks/22-ModelFitting-Bayesian.r", "max_issues_repo_name": "nesbitm/VBiTE_2021", "max_issues_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2020-10-02T05:33:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T11:44:01.000Z", "max_forks_repo_path": "content/_build/jupyter_execute/notebooks/22-ModelFitting-Bayesian.r", "max_forks_repo_name": "nesbitm/VBiTE_2021", "max_forks_repo_head_hexsha": "3c8e54d4878ff3f9b9272da73c3c8700902ddb21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63, "max_forks_repo_forks_event_min_datetime": "2017-12-04T14:08:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T11:37:36.000Z", "avg_line_length": 25.7903614458, "max_line_length": 126, "alphanum_fraction": 0.6225357376, "num_tokens": 4067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.8056861454634777}} {"text": "### 5.2-9\n\nhypMean <- 16\nexperData <- c(20, 24, 18, 16, 16, 19, 21, 23)\n\nexperMean <- mean(experData)\nexperSd <- sd(experData)\nnSamples <- length(experData)\n\nt <- (experMean - hypMean) / (experSd / sqrt(nSamples))\nprint(nSamples)\nprint(t)\n\n### df = r - k - 1 = 8 - 2 - 1 = 5\ntCrit <- qt(0.975, nSamples-2-1, ncp=0, lower.tail=TRUE, log.p=FALSE)\nprint(tCrit)\n\n### t = 3.448613 -> H0 is rejected (mu is not equal to 16)\n", "meta": {"hexsha": "8aafae48600f8711a3a05d3bc4fba705c7ba64fc", "size": 420, "ext": "r", "lang": "R", "max_stars_repo_path": "TASK3/sem3/hypTest2.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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": "TASK3/sem3/hypTest2.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TASK3/sem3/hypTest2.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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.1052631579, "max_line_length": 69, "alphanum_fraction": 0.6142857143, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321450147636, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.8056746921238614}} {"text": "# Example : 1 Chapter : 4.3 Page No: 218\r\n# Fit a straight line\r\nsolution<-function(A,b){\r\n ATA<-t(A)%*%A\r\n ATb<-t(A)%*%b\r\n xhat<-solve(ATA,ATb)\r\n return(xhat)\r\n}\r\nfit_line<-function(D){\r\n num_of_points<-nrow(D)\r\n t<-c()\r\n for(i in 1:num_of_points){\r\n t<-c(t,1)\r\n }\r\n t<-c(t,D[,1])\r\n A<-matrix(c(t),ncol=2)\r\n b<-D[,2]\r\n b<-matrix(c(b),ncol=1)\r\n x<-solution(A,b)# The system has no solution, we need to find the best solution \r\n return(x)\r\n}\r\nData<-matrix(c(0,6,1,0,2,0),ncol=2,byrow=T)\r\nx<-fit_line(Data)\r\nC<-x[1]\r\nD<-x[2]\r\nprint(paste(\"The best straight line is b= \",C,\" + \",D,\"t\"))\r\n\r\n", "meta": {"hexsha": "130179410cc366793ba2985e7da049df5b613b44", "size": 610, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.3.1/Ex4.3_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/CH4/EX4.3.1/Ex4.3_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/CH4/EX4.3.1/Ex4.3_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": 21.7857142857, "max_line_length": 83, "alphanum_fraction": 0.562295082, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474246069458, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.8056222806701274}} {"text": "## Vectorized operation continued...\n\n# Now we will compute the per 100k murder rate for each state and then store it in a object murder_rate\n# Then we will compute the average state murder rates for the US using the mean function\n\n# This is how you would display this average\n\n# You can use vectorization to calculate the rate.\n# If tot is the total number of murders and pop is the population per state\ntot/pop*100000 # Rate each state\n\n# Now you can calculate the average using mean\n\n# Stores per 100k the murder rates per state in the variable murder_rate\n# In order to calculate the average murder rate in the US you will \n\n\nlibrary(dslabs) # Load the data\ndata(murders)\n\nmurder_rate <- murders$total/murders$population*100000 # Store the per 100,000 murder rate for each state in murder_rate\nmean(murder_rate) # Calculate the average murder rate in the US\n", "meta": {"hexsha": "8fab22fe3c3eccfd71359cf948923f4a0b422622", "size": 862, "ext": "r", "lang": "R", "max_stars_repo_path": "Vectors/Vectorized Operations 3.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": "Vectors/Vectorized Operations 3.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": "Vectors/Vectorized Operations 3.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": 37.4782608696, "max_line_length": 120, "alphanum_fraction": 0.7795823666, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963779943094681, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.8052222797940759}} {"text": "library(deSolve)\n\n# Function to return derivatives of SEIR model\nseir_ode<-function(t,Y,par){\n S<-Y[1]\n E<-Y[2]\n I<-Y[3]\n R<-Y[4]\n \n beta<-par[1]\n sigma<-par[2]\n gamma<-par[3]\n mu<-par[4]\n \n dYdt<-vector(length=3)\n dYdt[1]=mu-beta*I*S-mu*S\n dYdt[2]=beta*I*S-(sigma+mu)*E\n dYdt[3]=sigma*E-(gamma+mu)*I\n \n return(list(dYdt))\n}\n\n# Set parameter values\nbeta<-520/365;\nsigma<-1/60;\ngamma<-1/30;\nmu<-774835/(65640000*365) # UK birth and population figures 2016\ninit<-c(0.8,0.1,0.1)\nt<-seq(0,365)\npar<-c(beta,sigma,gamma,mu)\n# Solve system using lsoda\nsol<-lsoda(init,t,seir_ode,par)\n\n# Plot\nplot(t,sol[,2],type=\"l\",col=\"blue\",ylim=c(0,1),ylab=\"Proportion\")\nlines(t,sol[,3],col=\"orange\")\nlines(t,sol[,4],col=\"red\") \nlines(t,1-rowSums(sol[,2:4]),col=\"green\")\nlegend(300,0.7,legend=c(\"S\",\"E\",\"I\",\"R\"),col=c(\"blue\",\"orange\",\"red\",\"green\"), lty=1, cex=0.8)\n", "meta": {"hexsha": "5a75f73626b85e01f9cf3233290a12e4b30add08", "size": 863, "ext": "r", "lang": "R", "max_stars_repo_path": "models/keeling_rohani_2008/program_2_6_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_2_6_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_2_6_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": 21.575, "max_line_length": 94, "alphanum_fraction": 0.6268829664, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105335255603, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.8049308674231702}} {"text": " # mean for interval data\r\nClassInterval <- c(\"16.25-18.75\", \"18.75-21.25\", \"21.25-23.75\",\"23.75-26.25\", \"26.25-28.75\", \" 28.75-31.25\", \" 31.25-33.75\", \"33.75-36.25\",\"36.25-38.75\", \" 38.75- 41.25\",\"41.25- 43.75\")\r\nfreq <- c( 2,7,7,14,17,24,11,11,3,3,1)\r\nmid_interval<- c(17.5,20.0,22.5,25.0,27.5,30.0,32.5,35.0,37.5,40.0,42.5)\r\nfmi<-freq*mid_interval\r\n \r\nList<- data.frame(ClassInterval, freq, mid_interval,fmi)\r\nprint(List)\r\nprint(\"mean is\")\r\nprint(sum(fmi)/sum(freq))\r\n\r\n \r\n\r\n", "meta": {"hexsha": "bb98a7a88475c6364fd4a5826061720800cc813f", "size": 478, "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.6/Ex3_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/CH3/EX3.6/Ex3_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/CH3/EX3.6/Ex3_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": 34.1428571429, "max_line_length": 186, "alphanum_fraction": 0.6066945607, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.8049166945993996}} {"text": "bisector <- function (P1, P2) {\n\tdelta <- P2 - P1\n\tmid <- (P1 + P2) / 2.0\n\tresult <- c(-delta[1] / delta[2], (t(delta) %*% mid) / delta[2])\n}\n\nplotb <- function (P1, P2, col = \"black\", x = c(-10, 10)) {\n\tb <- bisector(P1, P2)\n\ty <- b[1] * x + b[2]\n\tlines(x, y, col = col)\n}\n\nplotbh <- function (P1, P2, col = \"black\", x = seq(-10, 10, by = 0.1)) {\n\tb <- bisector(P1, P2)\n\ty <- b[1] * x + b[2]\n\tdx <- x - P2[1]\n\tdy <- y - P2[2]\n\ty <- y + sqrt(dx * dx + dy * dy)\n\tlines(x, y, col=col)\n}\n\nplotl <- function (P, l, col = \"black\") {\n\ttext(t(P), l, col = col)\n}\n\nplotp <- function (P, l, col = \"black\", offset = c(0.4, 0)) {\n\tpoints(t(P), col = col)\n\tplotl(P + offset, l, col = col)\n}\n\nlineval <- function(x, line) {\n\tresult <- (line[3] - line[1] * x) / line[2]\n}\n\npsb <- function(P1, n1, P2, n2, x, color = \"black\") {\n\tb <- bisector(P1, P2)\n\ty <- b[2] + b[1] * x\n\tprint(sprintf(\"%02f * x + %02f\", b[1], b[2]))\n\toffset <- c(0.4, 0)\n\tlines(x, y, col=color)\n\tpoints(t(P1))\n\ttext(t(P1 + offset), n1)\n\tpoints(t(P2))\n\ttext(t(P2 + offset), n2)\n}\n\ndist <- function (P1, P2) {\n\treturn <- sqrt(sum((P2 - P1)^2))\n}\n\npsbh <- function (P1, n1, P2, n2, x, color= \"black\") {\n\tb <- bisector(P1, P2)\n\ty <- b[2] + b[1] * x\n\tdx <- x - P2[1]\n\tdy <- y - P2[2]\n\ty <- y + sqrt(dx * dx + dy * dy)\n\toffset <- c(0.4, -0.4)\n\tlines(x, y, col=color)\n\tpoints(t(P1))\n\ttext(t(P1 + offset), n1)\n\tpoints(t(P2))\n\ttext(t(P2 + offset), n2)\n}\n\nxlabel <- function (P1, P2, P3, label) {\n\tb1 <- bisector(P1, P2)\n\tb2 <- bisector(P2, P3)\n\txx <- (b1[2] - b2[2]) / (b1[1] - b2[1])\n\txy <- b1[1] * xx + b1[2]\n\ttext(xx, xy - 0.4, label)\n}\n\ncrossb <- function (P1, P2, P3) {\n\tb1 <- bisector(P1, P2)\n\tb2 <- bisector(P2, P3)\n\txx <- (b2[2] - b1[2]) / (b1[1] - b2[1])\n\txy <- b1[1] * xx + b1[2]\n\treturn <- c(xx, xy)\n}\n\ncrossbh <- function (P1, P2, P3) {\n\tcross <- crossb(P1, P2, P3)\n\treturn <- c(cross[1], cross[2] + dist(cross, P3))\n}\n\nwholeplot <- function (A, B, X, Y, Z, plotter = plotb, offset = c(0.4, 0)) {\n\tplotter(A, B)\n\tplotter(A, X, col = \"blue\")\n\tplotter(B, X, col = \"red\")\n\tplotter(A, Y, col = \"blue\")\n\tplotter(B, Y, col = \"red\")\n\tplotter(A, Z, col = \"blue\")\n\tplotter(B, Z, col = \"red\")\n\t\n\tplotp(A, \"A\", col = \"blue\", offset = offset)\n\tplotp(B, \"B\", col = \"red\", offset = offset)\n\tplotp(X, \"X\", offset = offset)\n\tplotp(Y, \"Y\", offset = offset)\n\tplotp(Z, \"Z\", offset = offset)\n}\n\ncrossplot <- function (A, B, X, Y, Z) {\t\n\toffset <- c(0, -0.4)\n\tplotl(crossb(A, B, X) + offset, \"X'\")\n\tplotl(crossb(A, B, Y) + offset, \"Y'\")\n\tplotl(crossb(A, B, Z) + offset, \"Z'\")\n}\n\nx <- seq(-10, 10, by = 0.1)\nA <- c(3, 0)\nB <- c(4, 1)\nX <- c(0, 6.5)\nY <- c(0, 9)\nZ <- c(0, 11.5)\n\npar(mfrow=c(1,1))\n\nplot('x', 'y', xlab='', ylab='', type=\"n\", ylim=c(-1, 12), xlim=c(-5, 5), asp=1)\nwholeplot(A, B, X, Y, Z)\ncrossplot(A, B, X, Y, Z)\nlines(c(0, 0), c(-0.5, 12), lty=\"dotted\")\n\nplot('x', 'y', xlab='', ylab='', type=\"n\", ylim=c(-1, 12), xlim=c(-5, 5), asp=1)\nwholeplot(A, B, X, Y, Z, plotter = plotbh, offset = c(0.3, 0.3))\nplotl(crossbh(A, B, X) + c(0.4, -0.2), \"X'\")\nplotl(crossbh(A, B, Y) + c(-0.3, -0.4), \"Y'\")\nplotl(crossbh(A, B, Z) + c(-0.2, -0.3), \"Z'\")\nlines(c(0, 0), c(-0.5, 12), lty=\"dotted\")\n\nplot('x', 'y', xlab='', ylab='', type=\"n\", ylim=c(-1, 12), xlim=c(-5, 5), asp=1)\nP1 <- c(-1.5, 0)\nP2 <- c(-0.5, 5)\nplotbh(P1, P2)\nplotp(P1, \"A\", col = \"blue\", offset = offset)\nplotp(P2, \"B\", col = \"red\", offset = offset)\nlines(c(-6, 6), c(7, 7), lty=\"dotted\")\ntext(-5, 6.5, \"R* of A\", col=\"blue\")\ntext(0, 6.5, \"R* of B\", col=\"red\")\ntext(5, 6.5, \"R* of A\", col=\"blue\")\n\n", "meta": {"hexsha": "114db77a4e8a4c5e5b80281e83e8a4401bec3d1b", "size": 3503, "ext": "r", "lang": "R", "max_stars_repo_path": "assets/code/voronoi.r", "max_stars_repo_name": "polettix/ETOOBUSY", "max_stars_repo_head_hexsha": "b370a59dbfa4dc04687e6fb53065bb47f1581188", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-07-30T06:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T13:50:30.000Z", "max_issues_repo_path": "assets/code/voronoi.r", "max_issues_repo_name": "polettix/ETOOBUSY", "max_issues_repo_head_hexsha": "b370a59dbfa4dc04687e6fb53065bb47f1581188", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2020-01-03T18:21:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T21:51:53.000Z", "max_forks_repo_path": "assets/code/voronoi.r", "max_forks_repo_name": "polettix/ETOOBUSY", "max_forks_repo_head_hexsha": "b370a59dbfa4dc04687e6fb53065bb47f1581188", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-29T12:44:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T12:44:18.000Z", "avg_line_length": 24.8439716312, "max_line_length": 80, "alphanum_fraction": 0.5072794747, "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.8048902798971446}} {"text": "library(DescTools)\r\nbrandA=c(211.4,204.4,202.0,201.9,202.4,202.0,202.4,207.1,203.6,216.0,208.9,208.7,213.8,201.6,201.8,200.3,201.8,201.5,212.1,203.4)\r\nbrandB=c(186.3,205.7,184.4,203.6,180.4,202.0,181.5,186.7,205.7,189.1,183.6,188.7,188.6,204.2,181.6,208.7,181.5,208.7,186.8,182.9)\r\ndifference=brandA-brandB\r\n \r\ny=rank(replace(abs(difference),abs(difference)==0,NA),na='keep');\r\ncbind(difference,y)\r\n# sum of positive and negative ranks are\r\nTminus=1+2+3+4+5+6\r\nTplus= 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 +15 + 16 +17.5 +18 + 19\r\nT=min(Tminus,Tplus)\r\nT\r\n# T<53, we reject H0 and conclude that brand A fertilizer tends to produce more grass than brand B\r\ndifference=difference[-6]\r\n \r\n \r\nMedianCI(difference,conf.level = 0.95,na.rm = FALSE, method = \"exact\",R = 999)\r\n \r\n", "meta": {"hexsha": "13b45bc22cd2e334c88c459d89dded98295a7006", "size": 768, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH6/EX6.9/Ex6_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/CH6/EX6.9/Ex6_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/CH6/EX6.9/Ex6_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": 40.4210526316, "max_line_length": 130, "alphanum_fraction": 0.671875, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.8048185117330524}} {"text": "library(tidyverse)\nlibrary(ggplot2)\n\n# Set for reproducibility\nset.seed(777)\nsampleSize <- 10000\n\n# Bernoulli\ndata <- tibble(Outcome = rbinom(sampleSize, 1, 0.5))\n\nggplot(data, aes(x = Outcome)) + geom_histogram()\n\n\n# Binomial\ndataBinom2 <- tibble(Outcome = rbinom(sampleSize, 2, 0.2), OutcomeNo=2)\ndataBinom4 <- tibble(Outcome = rbinom(sampleSize, 4, 0.2), OutcomeNo=4)\ndataBinom10 <- tibble(Outcome = rbinom(sampleSize, 10, 0.2), OutcomeNo=10)\ndataBinom50 <- tibble(Outcome = rbinom(sampleSize, 50, 0.2), OutcomeNo=50)\n\ndata <- bind_rows(dataBinom2, dataBinom4, dataBinom10, dataBinom50)\n\nggplot(data, aes(x = Outcome)) + \n geom_histogram(binwidth = .5) + \n facet_wrap(~OutcomeNo, scales = \"free\") +\n labs(\n title = \"Sampling distributions (10,000 samples) of the Binomial distribution\",\n subtitle = \"10,000 samples with 0.2 as the probability of success.\"\n ) \n\n\n# Discrete Uniform\ndata <- tibble(Outcome = rdunif(sampleSize, 1, 6))\n\nggplot(data, aes(x = Outcome)) + \n geom_histogram(binwidth = .5) +\n scale_x_continuous(breaks = seq(1,6,1)) +\n labs(\n title = \"Simulating dice rolling outcomes\",\n subtitle = \"10,000 samples\"\n )\n\n\n# Poisson \ndataPois1 <- tibble(dist = rpois(sampleSize, 1), lambda = 1)\ndataPois3 <- tibble(dist = rpois(sampleSize, 3), lambda = 3)\ndataPois10 <- tibble(dist = rpois(sampleSize, 10), lambda = 10)\ndataPois50 <- tibble(dist = rpois(sampleSize, 50), lambda = 50)\n\n\ndata <- bind_rows(dataPois1, dataPois3, dataPois10, dataPois50)\n\nggplot(data, aes(x = dist)) + \n geom_histogram(binwidth = .5) + \n facet_wrap(~lambda) +\n labs(\n title = \"Sampling distributions of the poisson distribution\",\n subtitle = \"10,000 samples, lambdas are specified at the top of each graph\"\n ) \n\n\n\n# Negative binomial\ndataNb2 <- tibble(dist = rnbinom(sampleSize, 2, .3), success = 2)\ndataNb3 <- tibble(dist = rnbinom(sampleSize, 3, .3), success = 3)\ndataNb4 <- tibble(dist = rnbinom(sampleSize, 4, .3), success = 4)\ndataNb5 <- tibble(dist = rnbinom(sampleSize, 5, .3), success = 5)\ndataNb6 <- tibble(dist = rnbinom(sampleSize, 6, .3), success = 6)\ndataNb7 <- tibble(dist = rnbinom(sampleSize, 7, .3), success = 7)\n\ndata <- bind_rows(dataNb2, dataNb3, dataNb4, dataNb5, dataNb6, dataNb7)\n\nggplot(data, aes(x = dist)) + \n geom_histogram(binwidth = .5) + \n facet_wrap(~success, ncol = 2) +\n labs(\n title = \"Sampling distributions of the negative binomial distribution\",\n subtitle = \"10,000 samples, target number of successful trials are specified at the top of each graph\",\n x = \"Number of trials occured before the kth success\"\n ) \n\n\n\n# Geometric\ndataGeom2 <- tibble(dist = rgeom(sampleSize, .2), prob = 0.2)\ndataGeom3 <- tibble(dist = rgeom(sampleSize, .3), prob = 0.3)\ndataGeom4 <- tibble(dist = rgeom(sampleSize, .4), prob = 0.4)\ndataGeom5 <- tibble(dist = rgeom(sampleSize, .5), prob = 0.5)\n\ndata <- bind_rows(dataGeom2, dataGeom3, dataGeom4, dataGeom5)\n\nggplot(data, aes(x = dist)) + \n geom_histogram(binwidth = .5) + \n facet_wrap(~prob) +\n labs(\n title = \"Sampling distributions of the geometric distribution\",\n subtitle = \"10,000 samples, probability of successes are specified at the top of each graph\"\n ) \n\n", "meta": {"hexsha": "6360d674bebf0dcc6227aecf68d598bb4c7b0eb8", "size": 3172, "ext": "r", "lang": "R", "max_stars_repo_path": "959957e9369cc6b8ded054c94b70e6b4/Discrete.r", "max_stars_repo_name": "researchdata-sheffield/dataviz-hub2-qa", "max_stars_repo_head_hexsha": "bd746b5859a1e26f732663eb288b3bad8212c1f2", "max_stars_repo_licenses": ["0BSD", "Apache-2.0", "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": "959957e9369cc6b8ded054c94b70e6b4/Discrete.r", "max_issues_repo_name": "researchdata-sheffield/dataviz-hub2-qa", "max_issues_repo_head_hexsha": "bd746b5859a1e26f732663eb288b3bad8212c1f2", "max_issues_repo_licenses": ["0BSD", "Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "959957e9369cc6b8ded054c94b70e6b4/Discrete.r", "max_forks_repo_name": "researchdata-sheffield/dataviz-hub2-qa", "max_forks_repo_head_hexsha": "bd746b5859a1e26f732663eb288b3bad8212c1f2", "max_forks_repo_licenses": ["0BSD", "Apache-2.0", "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.0404040404, "max_line_length": 107, "alphanum_fraction": 0.6923076923, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843811, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.8043914748403546}} {"text": "cat('###PyRInText2019###')\ncat(12)\ncat('###PyRInText2019###')\n\nmcPi <- function(points){ # This is R comment\n\tinR <- 0\n\tcols <- NULL\n\trange <- c(0,1)\n\tx <- runif(points,0,1)\n\ty <- runif(points,0,1)\n\tr <- x^2+y^2\n\tfor(i in r){\n\t\tif(i<=1){\n\t\t\tinR <- inR + 1\n\t\t\tcols <- c(cols,\"red\")\n\t\t}\n\t\telse\n\t\t cols <- c(cols,\"black\")\n\t}\n\treturn_data <- 4*inR/points\n\n\tpdf(\"mc_pi.pdf\") \n\tplot(x,y,col=cols,xlim=range,ylim=range,pch=20,\n\t\tmain=\"Estimate pi value with Monte Carlo method\",\n\t\tsub=sprintf(\"%s points. pi = %1.6f\",points, return_data))\n\tcurve(sqrt(1-x^2),xlim=c(0,1),ylim=c(0,1),add=T)\n\tlines(c(0,1),c(0,0))\n\tlines(c(0,0),c(1,0))\n\treturn(return_data)\n}\n\ncat('###PyRInText2019###')\ncat(57)\ncat('###PyRInText2019###')\npoints<-2003\ncat('###PyRInText2019###')\ncat(59)\ncat('###PyRInText2019###')\ncat(points)\ncat('###PyRInText2019###')\ncat(61)\ncat('###PyRInText2019###')\ncat(mcPi(points))\ncat('###PyRInText2019###')\ncat(66)\ncat('###PyRInText2019###')\nlibrary(knitr);data(iris);data<-iris[c(41:60),];kable(data, \"latex\")\n", "meta": {"hexsha": "f60429328c87c84e6fbce6d25bb1b8fd6d0c25ec", "size": 1011, "ext": "r", "lang": "R", "max_stars_repo_path": "tests/test01.r", "max_stars_repo_name": "AkiraHakuta/PyRInText", "max_stars_repo_head_hexsha": "5b22c3ee1f81133a7f44c4307bc5cd4354fda695", "max_stars_repo_licenses": ["MIT", "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": "tests/test01.r", "max_issues_repo_name": "AkiraHakuta/PyRInText", "max_issues_repo_head_hexsha": "5b22c3ee1f81133a7f44c4307bc5cd4354fda695", "max_issues_repo_licenses": ["MIT", "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": "tests/test01.r", "max_forks_repo_name": "AkiraHakuta/PyRInText", "max_forks_repo_head_hexsha": "5b22c3ee1f81133a7f44c4307bc5cd4354fda695", "max_forks_repo_licenses": ["MIT", "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": 21.0625, "max_line_length": 68, "alphanum_fraction": 0.6053412463, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8723473647220786, "lm_q1q2_score": 0.8042360793727743}} {"text": "#!/usr/bin/env Rscript\n\n#### matrix\n\n############################################################\n### Arrays\n############################################################\nz = 1:24\ndim(z) = c(3, 4, 2)\n\n## all data\nz[,,]\nz[1,,]\n\nx = array(1:20, dim = c(4,5))\n\n\n### 4x6 全填1\nX = matrix(1, 4, 6)\n\nrownames(X) = paste(\"S\", seq(1, dim(X)[1]), sep = \"\")\ncolnames(X) = paste(\"V\", seq(1, dim(X)[2]), sep = \"\")\n\n### outer product\na = 1:3\nb = 1:5\n### 外积的维度是由两个向量共同决定\nab1 = a %o% b\nab2 = outer(a, b, \"*\")\n## ?? ab3 == ab1 == ab2\nab3 = a %*% t(b)\n\n## 真正理解一下outer函数作用\nf = function(x, y) x + y\nab4 = outer(a, b, f)\n\n### 1到20, 矩阵以row下标跑的块(列元素是顺序的)\nY = matrix(1:20, 4, 5)\n# [,1] [,2] [,3] [,4] [,5]\n# [1,] 1 5 9 13 17\n# [2,] 2 6 10 14 18\n# [3,] 3 7 11 15 19\n# [4,] 4 8 12 16 20\n\n### 方阵才有逆\nA = c(c(0,1,4), c(1,0,-3), c(2,3,8))\ndim(A) = c(3,3)\nB = solve(A)\nA %*% B\n", "meta": {"hexsha": "2887ec8c2484251e33b93f4b5126bfd77af4f199", "size": 898, "ext": "r", "lang": "R", "max_stars_repo_path": "R/learn/Notes/matrix_array.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/Notes/matrix_array.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/Notes/matrix_array.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": 17.96, "max_line_length": 60, "alphanum_fraction": 0.3864142539, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094438, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.8036654660982762}} {"text": "#===============================================================\n# Vector products\n# R implementation\n#===============================================================\n\na <- c(3, 4, 5)\nb <- c(4, 3, 5)\nc <- c(-5, -12, -13)\n\n#---------------------------------------------------------------\n# Dot product\n#---------------------------------------------------------------\n\ndotp <- function(x, y) {\n if (length(x) == length(y)) {\n sum(x*y)\n }\n}\n\n#---------------------------------------------------------------\n# Cross product\n#---------------------------------------------------------------\n\ncrossp <- function(x, y) {\n if (length(x) == 3 && length(y) == 3) {\n c(x[2]*y[3] - x[3]*y[2], x[3]*y[1] - x[1]*y[3], x[1]*y[2] - x[2]*y[1])\n }\n}\n\n#---------------------------------------------------------------\n# Scalar triple product\n#---------------------------------------------------------------\n\nscalartriplep <- function(x, y, z) {\n if (length(x) == 3 && length(y) == 3 && length(z) == 3) {\n dotp(x, crossp(y, z))\n }\n}\n\n#---------------------------------------------------------------\n# Vector triple product\n#---------------------------------------------------------------\n\nvectortriplep <- function(x, y, z) {\n if (length(x) == 3 && length(y) == 3 && length(z) == 3) {\n crosssp(x, crossp(y, z))\n }\n}\n\n#---------------------------------------------------------------\n# Compute and print\n#---------------------------------------------------------------\n\ncat(\"a . b =\", dotp(a, b))\ncat(\"a x b =\", crossp(a, b))\ncat(\"a . (b x c) =\", scalartriplep(a, b, c))\ncat(\"a x (b x c) =\", vectortriplep(a, b, c))\n", "meta": {"hexsha": "c6740a1df24324423d3090b686c4b55b59dcc459", "size": 1612, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Vector-products/R/vector-products.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/Vector-products/R/vector-products.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/Vector-products/R/vector-products.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": 27.7931034483, "max_line_length": 74, "alphanum_fraction": 0.2580645161, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.803345661822326}} {"text": "n<-100000\n\ncleanup()\npar(mfrow=c(2,1))\nmeanlog<-3\nsdlog<-0.8\nm<-rlnorm(n, meanlog = meanlog, sdlog = sdlog)\nhist(m,freq=F,breaks=100,main=paste(\"input mean:\",round(exp(meanlog),2),\"mean:\",round(mean(m),2),\"median:\",round(median(m),3),\n \"\\n\",\"exp(mu+0.5sd^2):\",round(exp(meanlog+0.5*sdlog^2),2)))\nabline(v=mean(m),col=\"blue\",lwd=2)\nabline(v=median(m),col=\"red\",lwd=2)\n\n\nm<-rnorm(n, mean =meanlog, sd = sdlog)\nm<-exp(m)\n\nhist(m,freq=F,breaks=100,main=paste(\"input mean:\",round(exp(meanlog),2),\"mean:\",round(mean(m),2),\"median:\",round(median(m),3),\n \"\\n\",\"exp(mu+0.5sd^2):\",round(exp(meanlog+0.5*sdlog^2),2)))\nabline(v=mean(m),col=\"blue\",lwd=2)\nabline(v=median(m),col=\"red\",lwd=2)\n\n\n# the SMS way with truncated variance\nX11()\npar(mfrow=c(2,1))\n#mind<- -100; maxd<- 100\nmind<- -2; maxd<- 2\na<-data.frame(rn=rnorm(n*2, mean = 0, sd = 1))\na<-subset(a,rn> mind & rn5] # select elements greater than 5\nx[x%%2 == 0] # select even elements\n\n#example 2\nmymat = matrix(1:12,4,3)\nmymat = matrix(1:12,ncol=3,byrow=F)\n# reading from a data file\nm <- matrix(scan('matrix.dat'),nrow=3,byrow=TRUE); m\ncat(\"scanning the numbers from a file\\n\")\nnums = scan('matrix.dat'); nums\n######################################\na <- matrix(1:9, nrow = 3)\ncolnames(a) <- c(\"A\", \"B\", \"C\"); a\na[1:2, ]\n#> A B C\n#> [1,] 1 4 7\n#> [2,] 2 5 8\na[c(T, F, T), c(\"B\", \"A\")]\n# TFT will be recycled, first B will be read then A will be read\n#> B A\n#> [1,] 4 1\n#> [2,] 6 3\na[0, -2]\n#> A C\n\n#########################################################################################################\n# MATRIX MODIFICATION\n#########################################################################################################\ncat(\"\\nModifying a Matrix \\n\")\nx <- matrix(1:9, nrow = 3); x\nx[2,2] <- 10; x # modify a single element\nx[x<5] <- 0; x # modify elements less than 5\n\ncat(\"\\ntranspose a matrix \\n\")\nt(x)\ncat(\"\\nWe can add row or column using rbind() and cbind() function \\n\")\n\ncbind(x,c(1,2,3)) # add columns\nrbind(x,c(1,2,3)) # add row\nx <- x[1:2,]; x # remove last row\n\ncat(\"\\nDimension of matrix can be modified as well, using the dim() function. \\n\")\nx <- matrix(1:6, nrow = 2); x\ndim(x) <- c(3,2); x # change to 3X2 matrix\ndim(x) <- c(1,6); x # change to 1X6 matrix\n\ncat(\"\\nMatrix Mathematics \\n\")\nx <- matrix(1:9, nrow = 3,byrow=T); x\ny <- matrix(1:9, nrow = 3,byrow=T); y\nz <- x %*% y; z; \ndet(x)\nrowSums(x)\nrowMeans(x)\nz1 <- cbind(x,y); z1\n\n# finding xy' and x'y\ncat(\"\\nxy' is outer product and x'y is cross product\\n\")\na<- x %o% y ; a # xy'\na<- crossprod(x,y); a\n\n\ncat(\"\\nfinding inverse using solve\\n\")\nA=rbind(c(1, 2), c(3, 4)); A\nsolve(A) # inverse of A\n\n# find inverses using solve\nA =rbind(c(1:3),c(0,4,5),c(1,0,6))\ndet(A)\nsolve(A)* det(A)\n\n# inverse using ginv\ncat(\"\\ninverse of A using ginv is \\n\")\nlibrary(\tMASS)\nginv(A)*det(A)\n\n#1 2 3 inverse is 1/22 * 24 -12 -2\n#0 4 5 5 3 -5\n#1 0 6 -4 2 4\n\ncat(\"\\n \\n\")\ncat(\"\\n \\n\")\n\n# THE END\n############################################################################################\n#Matrix facilites\n#In the following examples, A and B are matrices and x and b are a vectors.\n#Operator or Function\tDescription\n\n#A * B\tElement-wise multiplication\n#A %*% B\tMatrix multiplication\n#A %o% B\tOuter product. AB'\n\n#crossprod(A,B)\n#crossprod(A)\tA'B and A'A respectively.\n\n#t(A)\tTranspose\n\n#diag(x)\tCreates diagonal matrix with elements of x in the principal diagonal\n\n#diag(A)\tReturns a vector containing the elements of the principal diagonal\n\n#diag(k)\tIf k is a scalar, this creates a k x k identity matrix. Go figure.\n\n#solve(A, b)\tReturns vector x in the equation b = Ax (i.e., A-1b)\n\n#solve(A)\tInverse of A where A is a square matrix.\n\n#ginv(A)\tMoore-Penrose Generalized Inverse of A. \n\n#ginv(A) requires loading the MASS package.\n\n#y<-eigen(A)\ty$val are the eigenvalues of A\n\n#y$vec are the eigenvectors of A\n\n#y<-svd(A)\tSingle value decomposition of A.\n\n#y$d = vector containing the singular values of A\n\n#y$u = matrix with columns contain the left singular vectors of A \n\n#y$v = matrix with columns contain the right singular vectors of A\n\n#R <- chol(A)\tCholeski factorization of A. Returns the upper triangular factor, such that R'R = A.\n\n#y <- qr(A)\tQR decomposition of A. \n\n#y$qr has an upper triangle that contains the decomposition and a lower triangle that contains information on the Q decomposition.\n\n#y$rank is the rank of A. \n\n#y$qraux a vector which contains additional information on Q. \n\n#y$pivot contains information on the pivoting strategy used.\n\n#cbind(A,B,...)\tCombine matrices(vectors) horizontally. Returns a matrix.\n\n#rbind(A,B,...)\tCombine matrices(vectors) vertically. Returns a matrix.\n\n#rowMeans(A)\tReturns vector of row means.\n\n#rowSums(A)\tReturns vector of row sums.\n\n#colMeans(A)\tReturns vector of column means.\n\n#colSums(A)\tReturns vector of column sums.\n\n\n\n\n\n\n", "meta": {"hexsha": "bc1633cb6903ef2e17d2a9d5aaff054c94791e9c", "size": 6714, "ext": "r", "lang": "R", "max_stars_repo_path": "AstroSeminar2019Spring/ModernStatistics_R/chap0/dataTypes/matrix1.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/chap0/dataTypes/matrix1.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/chap0/dataTypes/matrix1.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.1076233184, "max_line_length": 130, "alphanum_fraction": 0.582663092, "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8902942370375485, "lm_q1q2_score": 0.8029747711909018}} {"text": "######################################################################################\n# Fitting a univariate state-space model with MARSS and JAGS\n# x[1] = mu\n# x[t] = x[t-1] + u + w[t], w[t] ~ N(0, q)\n# y[t] = x[t] + v[t], v[t] ~ N(0, r)\n######################################################################################\n\n# load the needed packages\nrequire(coda)\nrequire(R2jags)\nrequire(MARSS)\n\n# Our univariate data\ny = log(graywhales[,2])\nn = length(y)\n\n# Fit with MARSS\n# MARSS specification for a random walk with drift, observed with error\nmod.list = list( \n B=matrix(1), U=matrix(\"u\"), Q=matrix(\"q\"),\n Z=matrix(1), A=matrix(0), R=matrix(\"r\"),\n x0=matrix(\"mu\"), tinitx=1 )\n\nfit.marss = MARSS(y, model=mod.list)\n\n# Fit with JAGS\n# jags model specification\njagsscript = cat(\"\n\tmodel { \n\t# priors on parameters\n\t# Make sure mu prior is scaled to the data\n\tmu ~ dnorm(Y1, 1/(Y1*100)); \n\ttau.q ~ dgamma(0.001,0.001); # This is inverse gamma\n\tsd.q <- 1/sqrt(tau.q); # sd is treated as derived parameter\n\ttau.r ~ dgamma(0.001,0.001); # This is inverse gamma\n\tsd.r <- 1/sqrt(tau.r); # sd is treated as derived parameter\n\tu ~ dnorm(0, 0.01);\n\n\t# If X[0] = mu instead of X[1]\n\t# X[1] ~ dnorm(mu+u, tau.q)\n\tX[1] <- mu;\n\tY[1] ~ dnorm(X[1], tau.r);\n\t# Jags is not vectorized, so we have to loop over observations\n\tfor(i in 2:N) {\n\tpredX[i] <- X[i-1]+u; \n\tX[i] ~ dnorm(predX[i],tau.q); # Process variation\n\tY[i] ~ dnorm(X[i], tau.r); # Observation variation\n\t\t}\n\t} \n\n\",file=\"ss_model.txt\")\n\n# The data (an any other input) we pass to jags\njags.data = list(\"Y\"=y, \"N\"=n, Y1=y[1])\n# The parameters that we are monitoring (must monitor at least 1)\njags.params=c(\"sd.q\",\"sd.r\",\"X\",\"mu\", \"u\")\nmodel.loc=(\"ss_model.txt\")\nmod_ss = jags(jags.data, parameters.to.save=jags.params, model.file=model.loc, n.chains = 3, \n n.burnin=5000, n.thin=1, n.iter=10000, DIC=TRUE) \n\n# Plot the posterior of mu, u, q and r with the MLE ests from MARSS on top\nattach.jags(mod_ss)\npar(mfrow=c(2,2))\n#you need to know that mu is in the x0 val in MARSS\nhist(mu)\nabline(v=coef(fit.marss)$x0, col=\"red\")\n#you need to know that u is in the U val in MARSS\nhist(u)\nabline(v=coef(fit.marss)$U, col=\"red\")\n#you need to know that q is in the Q val in MARSS\n#put on log scale\nhist(log(sd.q^2))\nabline(v=log(coef(fit.marss)$Q), col=\"red\")\n#you need to know that r is in the R val in MARSS\n#put on log scale\nhist(log(sd.r^2))\nabline(v=log(coef(fit.marss)$R), col=\"red\")\ndetach.jags()\n\n# Plotting the estimated states\n# We define a function to do this for us from the jags output\nplotModelOutput = function(jagsmodel, Y) {\n # attach the model\n attach.jags(jagsmodel)\n x = seq(1,length(Y))\n summaryPredictions = cbind(apply(X,2,quantile,0.025), apply(X,2,mean), \n apply(X,2,quantile,0.975))\n ylims = c(min(c(Y,summaryPredictions), na.rm=TRUE),max(c(Y,summaryPredictions), na.rm=TRUE))\n plot(Y, col=\"white\",ylim=ylims, \n xlab=\"\",ylab=\"95% CIs of predictions and data\")\n polygon(c(x,rev(x)), c(summaryPredictions[,1], rev(summaryPredictions[,3])), \n col=\"grey70\",border=NA)\n lines(summaryPredictions[,2])\n points(Y)\n detach.jags()\n}\n\npar(mfrow=c(1,1))\nplotModelOutput(mod_ss, y)\nlines(fit.marss$states[1,], col=\"red\")\nlines(1.96*fit.marss$states.se[1,]+fit.marss$states[1,], col=\"red\", lty=2)\nlines(-1.96*fit.marss$states.se[1,]+fit.marss$states[1,], col=\"red\", lty=2)\ntitle(\"State estimate and data from\\nJAGS (black) versus MARSS (red)\")", "meta": {"hexsha": "0345f0f2d83e013dfefcb5b29db65362a947e880", "size": 3466, "ext": "r", "lang": "R", "max_stars_repo_path": "Lab-fitting-uni-ss-models/Fitting univariate state-space models in JAGS.r", "max_stars_repo_name": "vishalbelsare/atsa-labs", "max_stars_repo_head_hexsha": "f1c745e7e23f91a2e90f9faafb01bfcfc023886a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-01-16T01:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T01:56:18.000Z", "max_issues_repo_path": "Lab-fitting-uni-ss-models/Fitting univariate state-space models in JAGS.r", "max_issues_repo_name": "vishalbelsare/atsa-labs", "max_issues_repo_head_hexsha": "f1c745e7e23f91a2e90f9faafb01bfcfc023886a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-01-14T15:41:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T21:50:47.000Z", "max_forks_repo_path": "Lab-fitting-uni-ss-models/Fitting univariate state-space models in JAGS.r", "max_forks_repo_name": "vishalbelsare/atsa-labs", "max_forks_repo_head_hexsha": "f1c745e7e23f91a2e90f9faafb01bfcfc023886a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-09-27T04:30:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T19:29:46.000Z", "avg_line_length": 33.6504854369, "max_line_length": 94, "alphanum_fraction": 0.6197345643, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593031, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.8029712492747416}} {"text": "#This scripts will simulate a single sample, and calculate the mean\n#The gold background illustrates the 95% prediction interval (PI), The orange background illustrates the 95% confidence interval\n#The black dotted line illustrates the true mean. 95% of the CI should contain the true mean\n#Then, a simulation is run. The simulations generates a large number of additional samples\n#The simulation returns the number of CI that contain the mean, and returns the % of means from future studies that fall within the 95% of the original study\n#This is known as the capture percentage. It differs from (and is lower than) the confidence interval \n\nif(!require(ggplot2)){install.packages('ggplot2')}\nlibrary(ggplot2)\nif(!require(Rcpp)){install.packages('Rcpp')}\nlibrary(Rcpp)\n\n# Set seed for random generator\nset.seed(1000)\n\nn=20 #set sample size\nnSims<-100000 #set number of simulations\n\nx<-rnorm(n = n, mean = 100, sd = 15) #create sample from normal distribution\n\n#95% Confidence Interval\nCIU<-mean(x)+qt(0.975, df = n-1)*sd(x)*sqrt(1/n)\nCIL<-mean(x)-qt(0.975, df = n-1)*sd(x)*sqrt(1/n)\n\n#95% Prediction Interval\nPIU<-mean(x)+qt(0.975, df = n-1)*sd(x)*sqrt(1+1/n)\nPIL<-mean(x)-qt(0.975, df = n-1)*sd(x)*sqrt(1+1/n)\n\n#plot data\n#png(file=\"CI_mean.png\",width=2000,height=2000, res = 300)\nggplot(as.data.frame(x), aes(x)) + \n geom_rect(aes(xmin=PIL, xmax=PIU, ymin=0, ymax=Inf), fill=\"gold\") + #draw orange CI area\n geom_rect(aes(xmin=CIL, xmax=CIU, ymin=0, ymax=Inf), fill=\"#E69F00\") + #draw orange CI area\n geom_histogram(colour=\"black\", fill=\"grey\", aes(y=..density..), binwidth=2) +\n xlab(\"IQ\") + ylab(\"number of people\") + ggtitle(\"Data\") + theme_bw(base_size=20) + \n theme(panel.grid.major.x = element_blank(), axis.text.y = element_blank(), panel.grid.minor.x = element_blank()) + \n geom_vline(xintercept=mean(x), colour=\"black\", linetype=\"dashed\", size=1) + \n coord_cartesian(xlim=c(50,150)) + scale_x_continuous(breaks=c(50,60,70,80,90,100,110,120,130,140,150)) +\n annotate(\"text\", x = mean(x), y = 0.02, label = paste(\"Mean = \",round(mean(x)),\"\\n\",\"SD = \",round(sd(x)),sep=\"\"), size=6.5)\n#dev.off()\n\n#Simulate Confidence Intervals\nCIU_sim<-numeric(nSims)\nCIL_sim<-numeric(nSims)\nmean_sim<-numeric(nSims)\n\nfor(i in 1:nSims){ #for each simulated experiment\n x<-rnorm(n = n, mean = 100, sd = 15) #create sample from normal distribution\n CIU_sim[i]<-mean(x)+qt(0.975, df = n-1)*sd(x)*sqrt(1/n)\n CIL_sim[i]<-mean(x)-qt(0.975, df = n-1)*sd(x)*sqrt(1/n)\n mean_sim[i]<-mean(x) #store means of each sample\n}\n\n#Save only those simulations where the true value was inside the 95% CI\nCIU_sim<-CIU_sim[CIU_sim<100]\nCIL_sim<-CIL_sim[CIL_sim>100]\n\ncat((100*(1-(length(CIU_sim)/nSims+length(CIL_sim)/nSims))),\"% of the 95% confidence intervals contained the true mean\")\n\n#Calculate how many times the observed mean fell within the 95% CI of the original study\nmean_sim<-mean_sim[mean_sim>CIL&mean_sim= 1) = 1 - P(x = 0)\n1 - dbinom(0, size = 5, prob = 0.07)\n\n#-------------------------------------------------\n# Binomial distribution\n# p = probability of a dichotomous outcome\n# size = number of trials\n# x = possible outcomes\n\n# use \"d\" binom for density function\nMyVec <- dbinom(x=seq(0,10),size=10,prob=0.5)\nnames(MyVec) <- seq(0,10)\nbarplot(height=MyVec)\n\nMyVec <- dbinom(x=seq(0,10),size=10,prob=0.95)\nnames(MyVec) <- seq(0,10)\nbarplot(height=MyVec)\n\n# use \"p\" binom for cumulative distribution\n\n# what is probability of getting 5 heads out of 10 tosses?\ndbinom(x=5,size=10,prob=0.5)\n\n# what is the probability of getting 5 \n# or fewer heads out of 10 tosses?\npbinom(q=5,size=10,prob=0.5)\npbinom(q=4,size=9,prob=0.5)\n\n\n# use \"q\" binom for quantiles\n\n# what minimum number of heads will be found \n# for 40% of 50 trials with p = 0.5?\n\nqbinom(p=0.4,size=50,prob=0.5)\n\n# what is a 95% confidence interval for 100 trials \n# of a coin with p = 0.7 for heads?\nqbinom(p=c(0.025,0.975),size=100,prob=0.7)", "meta": {"hexsha": "b0ba65cc3bf8c8bd03da894b960130715912f10e", "size": 1507, "ext": "r", "lang": "R", "max_stars_repo_path": "Distributions/d_bernulli_discret.r", "max_stars_repo_name": "gcvalderrama/sta_foundations", "max_stars_repo_head_hexsha": "98f48fad5463a7c1ec17aad37e580f207cdbf9cf", "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/d_bernulli_discret.r", "max_issues_repo_name": "gcvalderrama/sta_foundations", "max_issues_repo_head_hexsha": "98f48fad5463a7c1ec17aad37e580f207cdbf9cf", "max_issues_repo_licenses": ["MIT"], "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/d_bernulli_discret.r", "max_forks_repo_name": "gcvalderrama/sta_foundations", "max_forks_repo_head_hexsha": "98f48fad5463a7c1ec17aad37e580f207cdbf9cf", "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.7049180328, "max_line_length": 93, "alphanum_fraction": 0.6509621765, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813551535005, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.8027700125494627}} {"text": "moderate=c(15,32,18,5)\r\nmildly=c(8,29,23,18)\r\nsevere=c(1,20,25,22)\r\nall_ages=c(sum(moderate),sum(mildly),sum(severe))\r\nall_servetiles=c(24,81,66,45)\r\ngrand_total=216\r\n# For row 1,the estimated expected number of occurrences \r\nE11=(sum(moderate)*all_servetiles[1])/grand_total\r\nprint(E11)\r\nE12=(sum(moderate)*all_servetiles[2])/grand_total\r\nprint(E12)\r\nE13=(sum(moderate)*all_servetiles[3])/grand_total\r\nprint(E13)\r\nE14=(sum(moderate)*all_servetiles[4])/grand_total\r\nprint(E14)\r\n\r\n# For row 2,the estimated expected number of occurrences \r\nE21=(sum(mildly)*all_servetiles[1])/grand_total\r\nprint(E21)\r\nE22=(sum(mildly)*all_servetiles[2])/grand_total\r\nprint(E22)\r\nE23=(sum(mildly)*all_servetiles[3])/grand_total\r\nprint(E23)\r\nE24=(sum(mildly)*all_servetiles[4])/grand_total\r\nprint(E24)\r\n\r\n# For row 3,the estimated expected number of occurrences \r\nE31=(sum(severe)*all_servetiles[1])/grand_total\r\nprint(E31)\r\nE32=(sum(severe)*all_servetiles[2])/grand_total\r\nprint(E32)\r\nE33=(sum(severe)*all_servetiles[3])/grand_total\r\nprint(E33)\r\nE34=(sum(severe)*all_servetiles[4])/grand_total\r\nprint(E34)\r\n\r\ndt=data.frame(cbind(E11,E12,E13,E14),cbind(E21,E22,E23,E24),cbind(E31,E32,E33,E34))\r\ndt\r\n", "meta": {"hexsha": "3f6ff0b8369634e17ddd968150cfc59fbe54f482", "size": 1179, "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.12/Ex10_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/CH10/EX10.12/Ex10_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/CH10/EX10.12/Ex10_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": 30.2307692308, "max_line_length": 84, "alphanum_fraction": 0.7472434266, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983308, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.8027293773950633}} {"text": "# Un Antonio Banos\nN <- 1\n\n# una urna con 3030 papeletas numeradas\npapeletas <- 1:3030\n\n# Simula muchas, muchas asambleas\nM <- 100000\nasambleas <- data.frame(matrix(0,M,1))\nnames(asambleas) <- \"papeleta\"\nfor (i in 1:M){\n asambleas[i,] <- sample(papeletas, N)\n}\nhist(asambleas$papeleta, breaks = 100, probability=TRUE, \n xlab=\"Papeleta ganadora\", ylab=\"probabilidad (sobre 1)\", \n main=\"100000 asambleas de la CUP\")\n\n# probabilidad de empate\nempates <- sum(asambleas$papeleta==1515)\nprobabilidad_empate <- empates/M\ncat(\"Probabilidad de empate:\", probabilidad_empate*100)\n\n###################################################################################\n\n# N cupaires\nN <- 3030\n\n# con un debate muy ajustado\nprobabilitat_si <- 0.5\nprobabilitat_no <- 1 - probabilitat_si\n\n# Simula muchas, muchas asambleas\nM <- 100000\nasambleas <- data.frame(matrix(0,M,2))\nnames(asambleas) <- c(\"sies\", \"noes\")\nfor (i in 1:M){\n votos <- sample(c(\"si\", \"no\"), N, replace=TRUE, prob=c(probabilitat_si,probabilitat_no))\n sies <- sum(votos==\"si\")\n noes <- sum(votos==\"no\")\n asambleas[i,] <- c(sies, noes)\n}\nhist(asambleas$sies, breaks = 100)\nhist(asambleas$sies, breaks = 100, probability=TRUE, \n xlab=\"Numero de sies\", ylab=\"probabilidad (sobre 1)\", \n main=\"100000 asambleas de la CUP\")\n\n# probabilidad de empate\nempates <- sum(asambleas$sies==1515)\nprobabilidad_empate <- empates/M\ncat(\"Probabilidad de empate:\", probabilidad_empate*100)\n\n##################################################################################\n# N cupaires\nN <- 3030\n\n# 80% ya llegan con el voto decidido.\nsi_fijos <- 1212 # 3030*0.4\nno_fijos <- 1212 # 3030*0.4\n\nindecisos <- N - si_fijos - no_fijos\n\n# con un debate muy ajustado\nprobabilitat_si <- 0.5\nprobabilitat_no <- 1 - probabilitat_si\n\n# Simula muchas, muchas asambleas\nM <- 100000\nasambleas <- data.frame(matrix(0,M,2))\nnames(asambleas) <- c(\"sies\", \"noes\")\nfor (i in 1:M){\n votos <- sample(c(\"si\", \"no\"), indecisos, replace=TRUE, prob=c(probabilitat_si,probabilitat_no))\n sies <- sum(votos==\"si\") + si_fijos\n noes <- sum(votos==\"no\") + no_fijos\n asambleas[i,] <- c(sies, noes)\n}\nhist(asambleas$sies, breaks = 100)\nhist(asambleas$sies, breaks = 100, probability=TRUE, \n xlab=\"Numero de sies\", ylab=\"probabilidad (sobre 1)\", \n main=\"100000 asambleas de la CUP\")\n\n# probabilidad de empate\nempates <- sum(asambleas$sies==1515)\nprobabilidad_empate <- empates/M\ncat(\"Probabilidad de empate:\", probabilidad_empate*100)\n\n", "meta": {"hexsha": "3d0642497d293cb41cd111dc3831da54670898a4", "size": 2465, "ext": "r", "lang": "R", "max_stars_repo_path": "R_scripts/assemblea_cup.r", "max_stars_repo_name": "alumbreras/alumbreras.github.io.src", "max_stars_repo_head_hexsha": "97a8dc33ad73ba21700f4d04ee246b34ab4645ee", "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": "R_scripts/assemblea_cup.r", "max_issues_repo_name": "alumbreras/alumbreras.github.io.src", "max_issues_repo_head_hexsha": "97a8dc33ad73ba21700f4d04ee246b34ab4645ee", "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": "R_scripts/assemblea_cup.r", "max_forks_repo_name": "alumbreras/alumbreras.github.io.src", "max_forks_repo_head_hexsha": "97a8dc33ad73ba21700f4d04ee246b34ab4645ee", "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.6627906977, "max_line_length": 98, "alphanum_fraction": 0.6490872211, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.8026039914643264}} {"text": "# econ589univariateGarch.r\r\n#\r\n# R examples for lectures on univariate GARCH models\r\n#\r\n# Eric Zivot\r\n# April 2nd, 2012\r\n# update history\r\n# May 14, 2013\r\n# Changed \"compound\" to \"log\" in CalculateReturns()\r\n# April 17, 2013\r\n# Updated examples for spring 2013 class\r\n# April 19, 2012\r\n# Added GARCH estimation and forecasting\r\n\r\n# load libraries\r\nlibrary(PerformanceAnalytics)\r\nlibrary(quantmod)\r\nlibrary(rugarch)\r\nlibrary(car)\r\nlibrary(FinTS)\r\n\r\noptions(digits=4)\r\n#\r\n\r\n\r\n# download data\r\nsymbol.vec = c(\"MSFT\", \"^GSPC\")\r\ngetSymbols(symbol.vec, from =\"2000-01-03\", to = \"2012-04-03\")\r\ncolnames(MSFT)\r\nstart(MSFT)\r\nend(MSFT)\r\n\r\n# extract adjusted closing prices\r\nMSFT = MSFT[, \"MSFT.Adjusted\", drop=F]\r\nGSPC = GSPC[, \"GSPC.Adjusted\", drop=F]\r\n\r\n# plot prices\r\nplot(MSFT)\r\nplot(GSPC)\r\n\r\n# calculate log-returns for GARCH analysis\r\nMSFT.ret = CalculateReturns(MSFT, method=\"log\")\r\nGSPC.ret = CalculateReturns(GSPC, method=\"log\")\r\n\r\n\r\n# remove first NA observation\r\nMSFT.ret = MSFT.ret[-1,]\r\nGSPC.ret = GSPC.ret[-1,]\r\ncolnames(MSFT.ret) =\"MSFT\"\r\ncolnames(GSPC.ret) = \"GSPC\"\r\n\r\n# create combined data series\r\nMSFT.GSPC.ret = cbind(MSFT.ret,GSPC.ret)\r\n\r\n# plot returns\r\nplot(MSFT.ret)\r\nplot(GSPC.ret)\r\n\r\n# plot returns with squared and absolute returns\r\ndataToPlot = cbind(MSFT.ret, MSFT.ret^2, abs(MSFT.ret))\r\ncolnames(dataToPlot) = c(\"Returns\", \"Returns^2\", \"abs(Returns)\")\r\nplot.zoo(dataToPlot, main=\"MSFT Daily Returns\", col=\"blue\")\r\n\r\ndataToPlot = cbind(GSPC.ret, GSPC.ret^2, abs(GSPC.ret))\r\ncolnames(dataToPlot) = c(\"Returns\", \"Returns^2\", \"abs(Returns)\")\r\nplot.zoo(dataToPlot, main=\"GSPC Daily Returns\", col=\"blue\")\r\n\r\n# plot autocorrelations of returns, returns^2 and abs(returns)\r\npar(mfrow=c(3,2))\r\n acf(MSFT.ret, main=\"MSFT Returns\")\r\n acf(GSPC.ret, main=\"GSPC Returns\")\r\n acf(MSFT.ret^2, main=\"MSFT Returns^2\")\r\n acf(GSPC.ret^2, main=\"GSPC Returns^2\")\r\n acf(abs(MSFT.ret), main=\"MSFT abs(Returns)\")\r\n acf(abs(GSPC.ret), main=\"GSPC abs(Returns)\")\r\npar(mfrow=c(1,1)) \r\n\r\n# compute summary statistics\r\ntable.Stats(MSFT.GSPC.ret)\r\n\r\n#\r\n# simulate ARCH(1) process\r\n#\r\n\r\n# use rugarch function ugarchsim\r\n?ugarchspec\r\n?ugarchpath\r\n\r\n# specify arch(1) model\r\narch1.spec = ugarchspec(variance.model = list(garchOrder=c(1,0)), \r\n mean.model = list(armaOrder=c(0,0)),\r\n fixed.pars=list(mu = 0, omega=0.1, alpha1=0.8))\r\nclass(arch1.spec)\r\narch1.spec\r\n\r\nset.seed(123)\r\narch1.sim = ugarchpath(arch1.spec, n.sim=1000)\r\n# result is an S4 object\r\nclass(arch1.sim)\r\n# [1] \"uGARCHpath\"\r\n# attr(,\"package\")\r\n# [1] \"rugarch\"\r\nslotNames(arch1.sim)\r\n# [1] \"path\" \"model\" \"seed\"\r\nnames(arch1.sim@path)\r\n# [1] \"sigmaSim\" \"seriesSim\" \"residSim\" \r\n\r\n# use the plot method to plot simulated series and conditional volatilities\r\npar(mfrow=c(2,1))\r\nplot(arch1.sim, which=2)\r\nplot(arch1.sim, which=1)\r\npar(mfrow=c(1,1))\r\n\r\npar(mfrow=c(3,1))\r\n acf(arch1.sim@path$seriesSim, main=\"Returns\")\r\n acf(arch1.sim@path$seriesSim^2, main=\"Returns^2\")\r\n acf(abs(arch1.sim@path$seriesSim), main=\"abs(Returns)\")\r\npar(mfrow=c(1,1))\r\n\r\n# use qqPlot() function from car package\r\nqqPlot(arch1.sim@path$seriesSim, ylab=\"ARCH(1) Returns\")\r\n\r\n#\r\n# simulate GARCH(1,1) process\r\n#\r\n\r\n# specify GARCH(1,1) model\r\ngarch11.spec = ugarchspec(variance.model = list(garchOrder=c(1,1)), \r\n mean.model = list(armaOrder=c(0,0)),\r\n fixed.pars=list(mu = 0, omega=0.1, alpha1=0.1,\r\n beta1 = 0.7))\r\nset.seed(123)\r\ngarch11.sim = ugarchpath(garch11.spec, n.sim=1000)\r\n\r\n# use the plot method to plot simulated series and conditional volatilities\r\npar(mfrow=c(2,1))\r\n plot(garch11.sim, which=2)\r\n plot(garch11.sim, which=1)\r\npar(mfrow=c(1,1))\r\n\r\npar(mfrow=c(3,1))\r\n acf(garch11.sim@path$seriesSim, main=\"Returns\")\r\n acf(garch11.sim@path$seriesSim^2, main=\"Returns^2\")\r\n acf(abs(garch11.sim@path$seriesSim), main=\"abs(Returns)\")\r\npar(mfrow=c(1,1))\r\n\r\n# use qqPlot() function from car package\r\nqqPlot(garch11.sim@path$seriesSim, ylab=\"GARCH(1,1) Returns\")\r\n\r\n#\r\n# Testing for ARCH/GARCH effects in returns\r\n#\r\n\r\n# use Box.test from stats package\r\nBox.test(coredata(MSFT.ret^2), type=\"Ljung-Box\", lag = 12)\r\nBox.test(coredata(GSPC.ret^2), type=\"Ljung-Box\", lag = 12)\r\n\r\n# use ArchTest() function from FinTS package for Engle's LM test\r\nArchTest(MSFT.ret)\r\nArchTest(GSPC.ret)\r\n\r\n#\r\n# Estimate GARCH(1,1)\r\n#\r\n# specify GARCH(1,1) model with only constant in mean equation\r\ngarch11.spec = ugarchspec(variance.model = list(garchOrder=c(1,1)), \r\n mean.model = list(armaOrder=c(0,0)))\r\nMSFT.garch11.fit = ugarchfit(spec=garch11.spec, data=MSFT.ret,\r\n solver.control=list(trace = 1)) \r\nclass(MSFT.garch11.fit)\r\nslotNames(MSFT.garch11.fit)\r\nnames(MSFT.garch11.fit@fit)\r\nnames(MSFT.garch11.fit@model)\r\n\r\n# show garch fit\r\nMSFT.garch11.fit\r\n\r\n# use extractor functions\r\n\r\n# estimated coefficients\r\ncoef(MSFT.garch11.fit)\r\n# unconditional mean in mean equation\r\nuncmean(MSFT.garch11.fit)\r\n# unconditional variance: omega/(alpha1 + beta1)\r\nuncvariance(MSFT.garch11.fit)\r\n# persistence: alpha1 + beta1\r\npersistence(MSFT.garch11.fit)\r\n# half-life:\r\nhalflife(MSFT.garch11.fit)\r\n\r\n# residuals: e(t)\r\nplot.ts(residuals(MSFT.garch11.fit), ylab=\"e(t)\", col=\"blue\")\r\nabline(h=0)\r\n\r\n# sigma(t) = conditional volatility\r\nplot.ts(sigma(MSFT.garch11.fit), ylab=\"sigma(t)\", col=\"blue\")\r\n\r\n# illustrate plot method\r\nplot(MSFT.garch11.fit)\r\nplot(MSFT.garch11.fit, which=1)\r\nplot(MSFT.garch11.fit, which=\"all\")\r\nplot(MSFT.garch11.fit, which=9)\r\n#\r\n# simulate from fitted model\r\n#\r\n\r\nMSFT.garch11.sim = ugarchsim(MSFT.garch11.fit,\r\n n.sim=nrow(MSFT.ret),\r\n rseed=123,\r\n startMethod=\"unconditional\")\r\nclass(MSFT.garch11.sim)\r\nslotNames(MSFT.garch11.sim)\r\n\r\n# plot actual returns and simulated returns\r\npar(mfrow=c(2,1))\r\n plot(MSFT.ret, main=\"Actual MSFT returns\")\r\n plot(as.xts(MSFT.garch11.sim@simulation$seriesSim, \r\n order.by=index(MSFT.ret)),\r\n main=\"Simulated GARCH(1,1) Returns\")\r\npar(mfrow=c(1,1))\r\n\r\n#\r\n# fit ARCH(1) using \"cleaned data\"\r\n#\r\n\r\n# convergence problems with ARCH(1) fit to MSFT\r\narch1.spec = ugarchspec(variance.model = list(garchOrder=c(1,0)), \r\n mean.model = list(armaOrder=c(0,0)))\r\nMSFT.arch1.fit = ugarchfit(spec=arch1.spec, data=MSFT.ret,\r\n solver.control=list(trace = 1))\r\n\r\nMSFT.ret.clean = Return.clean(MSFT.ret, method=\"boudt\")\r\npar(mfrow=c(2,1))\r\nplot(MSFT.ret, main=\"Raw MSFT Returns\", ylab=\"MSFT\")\r\nplot(MSFT.ret.clean, main=\"Cleaned MSFT Returns\", ylab=\"MSFT\")\r\npar(mfrow=c(1,1))\r\n\r\nMSFT.clean.arch1.fit = ugarchfit(spec=arch1.spec, data=MSFT.ret.clean,\r\n solver.control=list(trace = 1))\r\nMSFT.clean.arch1.fit\r\n\r\n\r\n#\r\n# model selection on GARCH(p,q) models\r\n#\r\n\r\narch.order = 1:5\r\narch.names = paste(\"arch\", arch.order, sep=\"\")\r\n\r\n# fit all arch models with p <= 5\r\narch.list = list()\r\nfor (p in arch.order) {\r\n arch.spec = ugarchspec(variance.model = list(garchOrder=c(p,0)), \r\n mean.model = list(armaOrder=c(0,0)))\r\n arch.fit = ugarchfit(spec=arch.spec, data=MSFT.ret.clean,\r\n solver.control=list(trace = 0))\r\n arch.list[[p]] = arch.fit\r\n}\r\nnames(arch.list) = arch.names\r\n\r\n# refit GARCH(1,1) to cleaned data\r\ngarch11.fit = ugarchfit(spec=garch11.spec, data=MSFT.ret.clean,\r\n solver.control=list(trace = 0))\r\narch.list$garch11 = garch11.fit\r\n\r\n# extract information criteria for all models\r\ninfo.mat = sapply(arch.list, infocriteria)\r\nrownames(info.mat) = rownames(infocriteria(arch.list[[1]]))\r\ninfo.mat\r\n\r\n\r\n# \r\n# compare arch(5) to garch(1,1)\r\n#\r\n\r\npar(mfrow=c(2,1))\r\nplot.ts(sigma(garch11.fit), main=\"GARCH(1,1) conditional vol\",\r\n ylab=\"vol\", col=\"blue\")\r\nplot.ts(sigma(arch.list$arch5), main=\"ARCH(5) conditional vol\",\r\n ylab=\"vol\", col=\"blue\")\r\npar(mfrow=c(1,1))\r\n\r\n#\r\n# forecasting\r\n#\r\n\r\n\r\nMSFT.garch11.fcst = ugarchforecast(MSFT.garch11.fit, n.ahead=100)\r\nclass(MSFT.garch11.fcst)\r\nslotNames(MSFT.garch11.fcst)\r\nnames(MSFT.garch11.fcst@forecast)\r\n\r\nMSFT.garch11.fcst\r\nplot(MSFT.garch11.fcst)\r\n\r\npar(mfrow=c(2,1))\r\n plot(MSFT.garch11.fcst, which=1)\r\n plot(MSFT.garch11.fcst, which=3)\r\npar(mfrow=c(1,1))\r\n\r\n# \r\n# forecast from ARCH(5)\r\n# \r\nMSFT.arch5.fcst = ugarchforecast(arch.list$arch5, n.ahead=100)\r\nplot(MSFT.arch5.fcst)\r\npar(mfrow=c(2,1))\r\n plot(MSFT.arch5.fcst, which=1)\r\n plot(MSFT.arch5.fcst, which=3)\r\npar(mfrow=c(1,1))\r\n\r\n\r\n#\r\n# compute h-day variance forecast = sum of h-day ahead variance forecasts\r\n#\r\n\r\nMSFT.fcst.df = as.data.frame(MSFT.garch11.fcst)\r\nhead(MSFT.fcst.df)\r\n# h-day return variance forecast = sum of h-day ahead variance forecasts\r\nMSFT.fcst.var.hDay = cumsum(MSFT.fcst.df$sigma^2)\r\nMSFT.fcst.vol.hDay = sqrt(MSFT.fcst.var.hDay)\r\n\r\n# plot h-day vol forecasts\r\nfcst.vol.hDay.zoo = zoo(MSFT.fcst.vol.hDay, as.Date(rownames(MSFT.fcst.df)))\r\nchart.TimeSeries(fcst.vol.hDay.zoo, main=\"GARCH(1,1) Forecast of h-day Return Vol\",\r\n colorset=\"blue\", ylab=\"h-day vol forecast\")\r\n\r\n\r\n\r\n#\r\n# computing VaR Forecasts\r\n#\r\n\r\n\r\n# h step-ahead conditional normal GARCH(1,1) VaR\r\nVaR.95.garch11 = MSFT.fcst.df$series[1] + MSFT.fcst.df$sigma[1]*qnorm(0.05)\r\nVaR.95.garch11\r\n\r\n# compute 20-day vol forecast from fitted GARCH(1,1)\r\nsigma.20day = sqrt(sum(MSFT.fcst.df$sigma[1:20]^2))\r\nVaR.95.garch11.20day = 20*MSFT.fcst.df$series[1] + sigma.20day*qnorm(0.05)\r\nVaR.95.garch11.20day\r\n\r\n\r\n\r\n?VaRTest\r\n# look at example to see how to implement test\r\nplot(MSFT.garch11.fit, which=\"2\")\r\n\r\n\r\n#\r\n# bootstrap forecast densities\r\n#\r\n\r\nMSFT.garch11.boot = ugarchboot(MSFT.garch11.fit, method=\"Partial\", \r\n n.ahead=100, n.bootpred=2000)\r\nclass(MSFT.garch11.boot)\r\nMSFT.garch11.boot\r\nplot(MSFT.garch11.boot)\r\n#\r\n# rolling estimation of GARCH(1,1)\r\n#\r\n\r\nMSFT.garch11.roll = ugarchroll(garch11.spec, MSFT.ret, n.ahead=1,\r\n forecast.length = 1000,\r\n refit.every=20, refit.window=\"moving\")\r\nclass(MSFT.garch11.roll)\r\n\r\nplot(MSFT.garch11.roll)\r\n# VaR plot\r\nplot(MSFT.garch11.roll, which=4)\r\n# Coef plot`\r\nplot(MSFT.garch11.roll, which=5)\r\n# show backtesting report\r\n?report\r\nreport(MSFT.garch11.roll, type=\"VaR\")\r\nreport(MSFT.garch11.roll, type=\"fpm\")\r\n\r\n\r\n", "meta": {"hexsha": "3ea907a3ed58479d40415a74ceadf8e771eadf97", "size": 10414, "ext": "r", "lang": "R", "max_stars_repo_path": "Time_Series_with_R_Track/7_GARCH_Models_in_R/univariateGarch.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": "Time_Series_with_R_Track/7_GARCH_Models_in_R/univariateGarch.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": "Time_Series_with_R_Track/7_GARCH_Models_in_R/univariateGarch.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": 27.4775725594, "max_line_length": 87, "alphanum_fraction": 0.6524870367, "num_tokens": 3316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8791467564270271, "lm_q1q2_score": 0.8021652993033737}} {"text": "# Imitate Wiener process on [0;1]\n\nlibrary(ggplot2)\n\nWiener <- function(length, sigma = 1)\n{\n # according to definition\n initValue <- 0\n # sd = sigma / length, as (t-s) = const\n return(c(initValue, cumsum(rnorm(n = (length-1), mean = 0, sd = sigma / length))))\n}\n\nTimeline <- seq(from = 0, to = 1, by = 0.001)\nN <- Wiener(length(Timeline))\n\nggplot() + geom_path(aes(x = Timeline, y = N)) + ggtitle(\"Wiener process\") + xlab('t') + ylab('N(t)')", "meta": {"hexsha": "c8c919d386781dd925b2f4c17a770becd8258bc8", "size": 446, "ext": "r", "lang": "R", "max_stars_repo_path": "lab5.r", "max_stars_repo_name": "alexgulyi/randimitation", "max_stars_repo_head_hexsha": "f2840fe8fec1ba7439b936c81851558864d1cba1", "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": "lab5.r", "max_issues_repo_name": "alexgulyi/randimitation", "max_issues_repo_head_hexsha": "f2840fe8fec1ba7439b936c81851558864d1cba1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab5.r", "max_forks_repo_name": "alexgulyi/randimitation", "max_forks_repo_head_hexsha": "f2840fe8fec1ba7439b936c81851558864d1cba1", "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.875, "max_line_length": 101, "alphanum_fraction": 0.6188340807, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.8021129324952332}} {"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 02\n#\n#\n\nrm(list = ls())\n\nlibrary(ggplot2)\nlibrary(ca)\n#\n# 1) Importar los datos a R desde el fichero salud by edad.csv\n#\n\nN <- data.matrix(read.csv(\n './../../../datasets/salud-by-edad.csv',\n header=TRUE,\n row.names = 1))\nprint(N)\n\nF <- N / sum(N)\nprint(F)\n\n\nD_r <- diag(rowSums(N) / sum(N))\nD_c <- diag(colSums(N) / sum(N))\n\nprint(D_r)\nprint(D_c)\n\nP_r <- solve(D_r) %*% F\nP_c <- solve(D_c) %*% t(F)\n\nprint(P_r)\nprint(P_c)\n\n#\n# 2) Revisar el test chi-cuadrado, su interpretación, las tablas que llevan a\n# la generación de sus valores y los perfiles fila y columna\n#\n\nchi_value <- sum(\n (N - (rowSums(N) %*% t(colSums(N))) / sum(N)) ^ 2 /\n ((rowSums(N) %*% t(colSums(N))) / sum(N))\n)\nprint(chi_value)\n\npval <- pchisq(chi_value,\n df = (dim(N)[1] - 1) * (dim(N)[2] - 2), lower.tail=FALSE)\nprint(pval)\n\n#\n# 3) Tomar decisiones sobre el número de componentes a extraer basadas en los\n# autovalores. ¿Cuántos autovalores hay en este análisis?\n#\n\n\nX <- t(F) %*% solve(D_r) %*% F %*% solve(D_c)\n\nX_eigen <- eigen(X)\nX_eigenval <- X_eigen$values\nX_eigenvec_1 <- X_eigen$vectors\n\nX_eigenvec_norm <- diag(t(X_eigenvec_1) %*% solve(D_c) %*% X_eigenvec_1)\n\nX_eigenvec <- t(t(X_eigenvec_1) / sqrt(X_eigenvec_norm))\n\n\nprint(X_eigenval)\nprint(X_eigenvec)\n\nfact <- solve(D_c) %*% X_eigenvec\n\nProyec_r <- P_r %*% fact\nProyec_c <- t(sqrt(X_eigenval) * t(fact))\n\nDF = as.data.frame(rbind(Proyec_r, Proyec_c))\n\nggplot(data=DF, aes(x=V2, y=V3)) +\n geom_point() +\n geom_text(label=c(rownames(N),colnames(N)))\n\n#\n# 4) Inspeccionar las tablas de coordenadas de filas y columnas. ¿Dónde aparece\n# la calidad de la representación de los puntos sobre el plano definido por\n# los dos primeros factores? ¿Cuánto vale esa calidad para la observación\n# correspondiente a los individuos entre 45 y 54 años?\n#\n\nsummary(ca(N))\n\n\n#\n# 5) Buscar posibles puntos de influencia en alguno de los dos primeros\n# factores. Rehacer el análisis si es necesario e interpretar el primer\n# plano factorial\n#\n\nN[-4,]\n\nsummary(ca(N[-4,]))\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(ca(N[-4,]))\n\n#\n# 7) ¿Puede decirse, a la vista del gráfico, que entre los individuos entre 16\n# y 24 años predomina la percepción de salud propia como MB? ¿Puede decirse,\n# a la vista del gráfico, que entre los de percepción de salud M predominan\n# los individuos de 75 o más años? Revisar los perfiles fila y perfiles\n# columna.\n#\n\nP_r\nP_c\n", "meta": {"hexsha": "9857df0d0257f441755b648fd9aa6eff196e511d", "size": 2775, "ext": "r", "lang": "R", "max_stars_repo_path": "data-analysis/correspondence-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/correspondence-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/correspondence-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": 22.0238095238, "max_line_length": 79, "alphanum_fraction": 0.689009009, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452442, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.8020841624466335}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Non parametric Tests - Exercise 09\n\nrm(list = ls())\n\nx.f <- c(5, 7, 16, 12)\ny.f <- c(7, 9, 15, 9)\n\nx <- rep(1:length(x.f), x.f)\n\n(n.x <- length(x))\n# 40\n\ny <- rep(1:length(y.f), y.f)\n\n(n.y <- length(y))\n# 40\n\n(n <- n.x + n.y)\n# 80\n\n(W.y <- sum(rank(c(y, x))[1:n.y]))\n# 1520\n\n(W.yx <- W.y - n.y * (n.y + 1) / 2)\n# 700\n\n(W.yx.mean <- n.y * n.x / 2)\n# 800\n\n(W.yx.var <- n.y * n.x * (n + 1) / 12)\n# 10800\n\n## Asymptotic pvalue (with continuity correction, without tie correction)\n1 - pnorm(W.yx - 0.5, mean = W.yx.mean, sd = sqrt(W.yx.var))\n# 0.830827188754516\n\n## Asymptotic pvalue (with continuity correction, with tie correction)\n# W.xy.var.corrected <- TODO\n#\n# 1 - pnorm(W.yx + 0.5, mean = W.yx.mean, sd = sqrt(W.xy.var.corrected))\n#\n\n## Exact pvalue (not valid with ties)\n1 - pwilcox(W.yx - 1, n.y, n.x)\n# 0.832293774410869\n\nwilcox.test(y, x, alternative = \"greater\", exact = FALSE)\n# Wilcoxon rank sum test with continuity correction\n#\n# data: y and x\n# W = 700, p-value = 0.8443\n# alternative hypothesis: true location shift is greater than 0\n\n## We can't reject H0, so we assume that treatment is less or equal than\n## control cases. pvalues are different due to ties correction.\n\n\n\n\n", "meta": {"hexsha": "e92373bb93ea1e172aac803dbac05d47d0c3ce8f", "size": 1255, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/non-parametric/exercise-09.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-09.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-09.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.5737704918, "max_line_length": 73, "alphanum_fraction": 0.6199203187, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8688267813328977, "lm_q1q2_score": 0.8019611498452041}} {"text": "x = c(46000, 45000, 35000, 32000, 42000, 36000, 41000, 56000, 73000, 53000)\ny = c(34000, 27000, 30000, 26000, 30000, 28000, 34000, 34000, 43000, 36000)\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\n#png('disp_diagram.png')\nplot(x, y)\n\n#png('line_diagram.png')\nplot(x, y)\nabline(B0, B1)\n\n#dev.off()\n\nB0\nB1\n\nprint('Pendiente: ')\nprint(B1)\n\nprint('Estime el costo de un vehículo “semejante” comparable a uno de lujo de $60 000.')\nprint(B1 * 60000 + B0)\n\nprint('Estime el costo de un vehículo “semejante” comparable a uno de lujo de $40 000')\nprint(B1 * 40000 + B0)", "meta": {"hexsha": "01d72f4a20c5e689ffad10d12844809e1c5f44c4", "size": 660, "ext": "r", "lang": "R", "max_stars_repo_path": "Tasks/CP6-Ex8/CP6-Ex8.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-Ex8/CP6-Ex8.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-Ex8/CP6-Ex8.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": 21.2903225806, "max_line_length": 88, "alphanum_fraction": 0.6303030303, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075711974104, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.8017479083885162}} {"text": "# 1. Simulate phi_i from Beta(2,2)\n# 2. Simulate y_i from Binom(10, phi_i)\n\nm = 1e5\n\ny = numeric(m)\nphi = numeric(m)\n\n#avoid using loops if possible\nfor (i in 1:m){\n phi[i] = rbeta(1, shape1=2.0, shape2=2.0)\n y[i] = rbinom(1, size=10, prob=phi[i])\n}\n\n#conditional on phi, y follows a binomial dist \nphi = rbeta(m, shape1=2.0, shape2=2.0)\ny = rbinom(m, size=10, prob=phi)\n\ntable(y) / m\n#approximation of marginal distribution of y = beta binomial \nplot(table(y)/m)\n\n#estimation of the expectation\nmean(y)\n", "meta": {"hexsha": "ea2b84c3a4403c25746bafd999e644fd2e2d557c", "size": 510, "ext": "r", "lang": "R", "max_stars_repo_path": "montyCarlo/mMHierarchicalModel.r", "max_stars_repo_name": "CharlieShelbourne/algos_practice", "max_stars_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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": "montyCarlo/mMHierarchicalModel.r", "max_issues_repo_name": "CharlieShelbourne/algos_practice", "max_issues_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "montyCarlo/mMHierarchicalModel.r", "max_forks_repo_name": "CharlieShelbourne/algos_practice", "max_forks_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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.4, "max_line_length": 61, "alphanum_fraction": 0.6666666667, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553806, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.8016498660901371}} {"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\nt5.sd <- sqrt(5/3) # scaling factor to standardize t_5 distribution\ndesired.sd <- 0.02\nscale.true <- desired.sd/t5.sd # scaling factor to get the desired sd\n\n# left.frac of the random numbers will come from the left distribution\n# the rest will come from the right distribution\nleft.frac <- 3/5\nn.obs <- 50\nx.obs <- c(rt(n.obs*left.frac, df=5)*scale.true-0.05,\n rt(n.obs*(1-left.frac), df=5)*scale.true+0.05)\n\n# create values of the true density\nx <- seq(-0.15, 0.15, by=0.001)\ntrue.density <- left.frac*dt((x+0.05)/scale.true,df=5)/scale.true +\n (1-left.frac)*dt((x-0.05)/scale.true, df=5)/scale.true\ny.max = max(true.density)\n\n# plot the kernel density estimator; then add the true density\nplot(density(x.obs, kernel=\"gaussian\", bw=\"SJ\"), main=\"\",\n xlim=c(-0.15,0.15), ylim=c(0,y.max), lwd=2, col=\"red\")\nlines(x, true.density, lty=2, lwd=2)\nrug(x.obs) # show the observations as ticks at plot bottom\n", "meta": {"hexsha": "5011e5bc6d63b72fc50dfa7af08dd62ca003f732", "size": 1217, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch8-kernel-density-estimate.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-kernel-density-estimate.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-kernel-density-estimate.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.5666666667, "max_line_length": 73, "alphanum_fraction": 0.6943303205, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.8016498633447366}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Non parametric Tests - Exercise 07\n\nrm(list = ls())\n\nx1 <- c(26, 28, 34, 48, 21, 22, 34)\nx2 <- c(28, 27, 42, 44, 17, 6, 16)\n\n\n(s <- (x1 - x2)[x1 != x2])\n# -2 1 -8 4 4 16 18\n\n(n <- length(s))\n# 7\n\n(V <- sum((s > 0) * rank(abs(s))))\n# 21\n\n(V.mean <- n * (n + 1) / 4)\n# 14\n\n(V.var <- n * (n + 1) * (2 * n + 1) / 24)\n# 35\n\n## Asymptotic pvalue (with continuity correction, without tie correction)\npnorm(V + 0.5, mean = V.mean, sd = sqrt(V.var))\n# 0.897553053091811\n\n## Asymptotic pvalue (with continuity correction, with tie correction)\n\n(ties <- table(abs(s)))\n# 1 2 4 8 16 18\n# 1 1 2 1 1 1\n\n(V.var.corrected <- V.var - sum(ties ^ 3 - ties) / 48)\n# 34.875\n\npnorm((V + 0.5 - V.mean) / sqrt(V.var.corrected))\n# 0.897957911117213\n\n## Exact pvalue (not valid with ties)\npsignrank(V, n)\n# 0.890625\n\nwilcox.test(x1, x2, paired = TRUE, alternative = \"less\", exact = FALSE)\n# Wilcoxon signed rank test with continuity correction\n#\n# data: x1 and x2\n# V = 21, p-value = 0.898\n# alternative hypothesis: true location shift is less than 0\n", "meta": {"hexsha": "1b2d3d7d0bdb9a0ead34e7353b5ed5e2e0119712", "size": 1101, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/non-parametric/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/non-parametric/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/non-parametric/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.5882352941, "max_line_length": 73, "alphanum_fraction": 0.6058128974, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.8016253460342653}} {"text": "# \n# Don't complain; just work harder! Dan Stanford\n# \n# Our responsibility is to do what we can, learn what we can, improve the solutions, and pass them on. RF\n# \n# @author: me@andreagirardi.it\n# @since: Wed Jan 8 19:11:27 CET 2020\n# @project: RExercises\n# @module: Matrix lesson\n# @desc: \n#\n#\n# Exercises\n\nA <- c(1, 2, 3)\nB <- c(4, 5, 6)\n\n> m <- rbind(A, B)\n> m\n [,1] [,2] [,3]\nA 1 2 3\nB 4 5 6\n\n> n <- cbind(A, B)\n> n\n A B\n[1,] 1 4\n[2,] 2 5\n[3,] 3 6\n\n> j <- matrix(1:9, byrow = T, nrow = 3)\n> j\n [,1] [,2] [,3]\n[1,] 1 2 3\n[2,] 4 5 6\n[3,] 7 8 9\n\n> j <- matrix(1:9, byrow = F, nrow = 3)\n> j\n [,1] [,2] [,3]\n[1,] 1 4 7\n[2,] 2 5 8\n[3,] 3 6 9\n\n> is.matrix(j)\n[1] TRUE\n\n> l <- matrix(1:25, by-km row = T, nrow = 5)\n> l\n [,1] [,2] [,3] [,4] [,5]\n[1,] 1 2 3 4 5\n[2,] 6 7 8 9 10\n[3,] 11 12 13 14 15\n[4,] 16 17 18 19 20\n[5,] 21 22 23 24 25\n\n# From row 2 to 3, from colum 2 to 3\n> z <- l[2:3, 2:3]\n> z\n [,1] [,2]\n[1,] 7 8\n[2,] 12 13\n\n# Sum of all elements\n> sum(l)\n[1] 325", "meta": {"hexsha": "19f17aeb6f851835b699fd952aea0759455bc8dc", "size": 1127, "ext": "r", "lang": "R", "max_stars_repo_path": "BootcampWithR/Matrix.r", "max_stars_repo_name": "giandrea77/RExercises", "max_stars_repo_head_hexsha": "d435e303775b154d4cbbc25f990eb4b23272039d", "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": "BootcampWithR/Matrix.r", "max_issues_repo_name": "giandrea77/RExercises", "max_issues_repo_head_hexsha": "d435e303775b154d4cbbc25f990eb4b23272039d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BootcampWithR/Matrix.r", "max_forks_repo_name": "giandrea77/RExercises", "max_forks_repo_head_hexsha": "d435e303775b154d4cbbc25f990eb4b23272039d", "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.0757575758, "max_line_length": 105, "alphanum_fraction": 0.4338952972, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8807970858005139, "lm_q1q2_score": 0.8014434371159234}} {"text": "aVar=0\n\nintegrate.rect <- function(f, a, b, n, k=0) {\n #k = 0 for left, 1 for right, 0.5 for midpoint\n h <- (b-a)/n\n x <- seq(a, b, len=n+1)\n sum(f(x[-1]-h*(1-k)))*h\n}\n\nintegrate.trapezoid <- function(f, a, b, n) {\n h <- (b-a)/n\n x <- seq(a, b, len=n+1)\n fx <- f(x)\n sum(fx[-1] + fx[-length(x)])*h/2 \n}\n\nintegrate.simpsons <- function(f, a, b, n) {\n h <- (b-a)/n\n x <- seq(a, b, len=n+1)\n fx <- f(x)\n sum(fx[-length(x)] + 4*f(x[-1]-h/2) + fx[-1]) * h/6\n}\n\nf1 <- (function(x) {(x^3)+aVar})\nf2 <- (function(x) {1/(x+aVar)})\nf3 <- (function(x) {x+aVar})\nf4 <- (function(x) {x+aVar})\n\nexecuteTask <- function(i) {\n\n integrate.rect(f1,0,1,100,0) #TopLeft 0.245025\n integrate.rect(f1,0,1,100,0.5) #Mid 0.2499875\n integrate.rect(f1,0,1,100,1) #TopRight 0.255025\n integrate.trapezoid(f1,0,1,100) # 0.250025\n integrate.simpsons(f1,0,1,100) #0.25\n\n integrate.rect(f2,1,100,1000,0) #TopLeft 0.245025\n integrate.rect(f2,1,100,1000,0.5) #Mid 0.2499875\n integrate.rect(f2,1,100,1000,1) #TopRight 0.255025\n integrate.trapezoid(f2,1,100,1000) # 0.250025\n integrate.simpsons(f2,1,100,1000) #0.25\n\n integrate.rect(f3,0,5000,5000000,0) #TopLeft 0.245025\n integrate.rect(f3,0,5000,5000000,0.5) #Mid 0.2499875\n integrate.rect(f3,0,5000,5000000,1) #TopRight 0.255025\n integrate.trapezoid(f3,0,5000,5000000) # 0.250025\n integrate.simpsons(f3,0,5000,5000000) #0.25\n\n integrate.rect(f3,0,6000,6000000,0) #TopLeft 0.245025\n integrate.rect(f3,0,6000,6000000,0.5) #Mid 0.2499875\n integrate.rect(f3,0,6000,6000000,1) #TopRight 0.255025\n integrate.trapezoid(f3,0,6000,6000000) # 0.250025\n integrate.simpsons(f3,0,6000,6000000) #0.25\n\treturn(i+1)\n}\n\nr=1\n\nfor (aVar in 0:100) {\n\tr = executeTask(aVar)\n}\n", "meta": {"hexsha": "0781a54c5e617bd1eea8a5908db1d627c460cdba", "size": 1703, "ext": "r", "lang": "R", "max_stars_repo_path": "tasks/numerical-integration/r/numerical-integration.r", "max_stars_repo_name": "stefanos1316/Rosetta_Code_Data_Set", "max_stars_repo_head_hexsha": "8120b14cce6cb76ba26353a7dd4012bc99bd65cb", "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": "tasks/numerical-integration/r/numerical-integration.r", "max_issues_repo_name": "stefanos1316/Rosetta_Code_Data_Set", "max_issues_repo_head_hexsha": "8120b14cce6cb76ba26353a7dd4012bc99bd65cb", "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": "tasks/numerical-integration/r/numerical-integration.r", "max_forks_repo_name": "stefanos1316/Rosetta_Code_Data_Set", "max_forks_repo_head_hexsha": "8120b14cce6cb76ba26353a7dd4012bc99bd65cb", "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.4677419355, "max_line_length": 56, "alphanum_fraction": 0.6382853787, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.8013250554380023}} {"text": "#' Check whether partitions of the figuration matrix are unimodular \r\n#'\r\n#' Check whether partitions of the figuration matrix are unimodular. For partitions A=[A1 A2], the function um_partition computes the determinants of A1 for all possible (unique) combinations of rows. Function um_partition_sample coputes determinants of A1 for a sample of those partitions.\r\n#' @param A Configuration matrix with ncol(A) >= nrow(A)\r\n#' @return A list comprising a table of determinants and the number of rows (n) and columns (r) of the matrix A\r\n#' @export\r\n#' @examples\r\n#' data(YangNetwork)\r\n#' set.seed(2020)\r\n#' um_partition_sample(YangNetwork$A)\r\n\r\num_partition <- function(A){\r\n\trequire(gtools)\r\n\tn <- qr(t(A))$rank\r\n\tA <- t( t(A)[,qr(t(A))$pivot[1:n]] )\r\n\tr <- ncol(A)\r\n\tcombs <- combinations(r,n,1:r)\r\n\tdets <- numeric(nrow(combs))\r\n\tfor (i in 1:nrow(combs)){\r\n\t\tif (i/100000 == round(i/100000)) cat(i,\"\\n\")\r\n\t\tdets[i] <- det(A[,combs[i,1:n]])\r\n\t}\r\n\tlist(dets=table(dets),r=r,n=n)\r\n}\r\n\r\num_partition_sample <- function(A,nsample=1e6){\r\n\tr <- ncol(A)\r\n\tn <- nrow(A)\r\n\tdets <- numeric(nsample)\r\n\tfor (i in 1:nsample){\r\n\t\tsample.rows <- sample(1:r,n,replace=F)\r\n\t\tdets[i] <- det(A[,sample.rows])\r\n\t}\r\n\tlist(dets=table(dets),r=r,n=n)\r\n}", "meta": {"hexsha": "468a1b52c42e81f963ccf1c64aaf643bf955974d", "size": 1231, "ext": "r", "lang": "R", "max_stars_repo_path": "R/um-partition.r", "max_stars_repo_name": "MartinLHazelton/DynamicLatticeBasis", "max_stars_repo_head_hexsha": "6c9a134acf398c4e80f06f8e837d4298efedca4c", "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/um-partition.r", "max_issues_repo_name": "MartinLHazelton/DynamicLatticeBasis", "max_issues_repo_head_hexsha": "6c9a134acf398c4e80f06f8e837d4298efedca4c", "max_issues_repo_licenses": ["MIT"], "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/um-partition.r", "max_forks_repo_name": "MartinLHazelton/DynamicLatticeBasis", "max_forks_repo_head_hexsha": "6c9a134acf398c4e80f06f8e837d4298efedca4c", "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.1714285714, "max_line_length": 291, "alphanum_fraction": 0.6677497969, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.80126402023388}} {"text": "HaversineDistance=function(lat1,lon1,lat2,lon2)\n{\n\n\t#returns the distance in km\n\tREarth<-6371\n\tlat<-abs(lat1-lat2)*pi/180\n\tlon<-abs(lon1-lon2)*pi/180\n\tlat1<-lat1*pi/180\n\tlat2<-lat2*pi/180\n\ta<-sin(lat/2)*sin(lat/2)+cos(lat1)*cos(lat2)*sin(lon/2)*sin(lon/2)\n\td<-2*atan2(sqrt(a),sqrt(1-a))\n\td<-REarth*d\n\n\treturn(d)\n\t\n}\n\nRMSE<-function(pre,real)\n{\n\treturn(sqrt(mean((pre-real)*(pre-real))))\n}\n\nmeanHaversineDistance<-function(lat1,lon1,lat2,lon2)\n{\n\treturn(mean(HaversineDistance(lat1,lon1,lat2,lon2)))\n}\n\n#USAGE\n#\n#FUNCTION PARAMETERS: @submission,@answers\n#@submission: path+filename containing the answers to submit in CSV format\n#@answers: path+filename containing the answers to evaluate the submission in CSV format\ntravelTime.PredictionEvaluation<-function(submission,answers)\n{\n\tdt<-read.csv(submission)\n\ttt_sub<-dt[,2]\n\tdt<-read.csv(answers)\n\ttt_real<-dt[,2]\n\treturn (RMSE(tt_sub,tt_real))\n}\n\n#USAGE\n#\n#FUNCTION PARAMETERS: @submission,@answers\n#@submission: path+filename containing the answers to submit in CSV format\n#@answers: path+filename containing the answers to evaluate the submission in CSV format\ndestinationMining.Evaluation<-function(submission,answers)\n{\n\tdt<-read.csv(submission)\n\tlat_sub<-dt[,2]\n\tlon_sub<-dt[,3]\n\tdt<-read.csv(answers)\n\tlat_real<-dt[,2]\n\tlon_real<-dt[,3]\n\treturn (meanHaversineDistance(lat_sub,lon_sub,lat_real,lon_real))\n}", "meta": {"hexsha": "f95093fb90f322c97b411233bf997e5a901967c4", "size": 1362, "ext": "r", "lang": "R", "max_stars_repo_path": "datasets/evaluation_script.r", "max_stars_repo_name": "vanshc98/CE4032", "max_stars_repo_head_hexsha": "c57c0f84254484c4fcc91ae817c9d650d26ec64b", "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": "datasets/evaluation_script.r", "max_issues_repo_name": "vanshc98/CE4032", "max_issues_repo_head_hexsha": "c57c0f84254484c4fcc91ae817c9d650d26ec64b", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2019-11-14T15:06:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T01:27:41.000Z", "max_forks_repo_path": "datasets/evaluation_script.r", "max_forks_repo_name": "vanshc98/CE4032", "max_forks_repo_head_hexsha": "c57c0f84254484c4fcc91ae817c9d650d26ec64b", "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": 24.3214285714, "max_line_length": 88, "alphanum_fraction": 0.7444933921, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.8011035476741524}} {"text": "## Vamos ilustrar o exemplo da proporção de itens defeitusos dado em De Groot, seção 7.4\n\nn <- 100 #! Dica: mude o tamanho de amostra e veja o que acontece\ny <- 10 #! Dica: mude o número de itens defeituosos e veja o que acontece com as posterioris\n\nprior1 <- function(theta) dbeta(x = theta, shape1 = 1, shape2 = 1)\nprior2 <- function(theta) dbeta(x = theta, shape1 = 1, shape2 = 2)\n\nposterior1 <- function(theta) dbeta(x = theta, shape1 = 1 + y, shape2 = 1 + (n - y))\nposterior2 <- function(theta) dbeta(x = theta, shape1 = 1 + y, shape2 = 2 + (n -y))\n\ncurve(prior1, xlab = expression(theta), ylab = \"Density\", lwd = 3, lty = 1, ylim = c(0, 15))\ncurve(prior2, lwd = 3, lty = 2, col = \"red\", add = TRUE)\ncurve(posterior1, lwd = 3, add = TRUE)\ncurve(posterior2, lwd = 3, col = \"red\", lty = 2, add = TRUE)\nabline(v = y/n, lty = 3, lwd = 3)\nlegend(x = \"topright\", legend = c(\"Prior/Posterior 1\", \"Prior/Posterior 2\"),\n col = c(\"black\", \"red\"), lty = 1:2, bty = 'n')", "meta": {"hexsha": "7e4789e4577d6b721b5b1f5cadef4ab273f9d0c0", "size": 970, "ext": "r", "lang": "R", "max_stars_repo_path": "code/exemplo_grandes_amostras.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_grandes_amostras.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_grandes_amostras.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": 53.8888888889, "max_line_length": 93, "alphanum_fraction": 0.6340206186, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.8008424947686699}} {"text": "# the 99% confidence level would imply the 99.5th percentile of the normal distribution at the upper tail\r\nzstar <- qnorm(0.995)\r\nwidth_interval<-0.50\r\nE<-width_interval/2\r\nsd<-0.75\r\nsample_size<- zstar^2 * sd * sd/ E^2\r\nprint(ceiling(sample_size))\r\n# the federal agency must obtain a random sample of 60 cereal cartons to estimate .", "meta": {"hexsha": "167cdf0574afceb3ed17143822958f071f1a56da", "size": 334, "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.4/Ex5_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/CH5/EX5.4/Ex5_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/CH5/EX5.4/Ex5_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": 41.75, "max_line_length": 107, "alphanum_fraction": 0.745508982, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.8007490615115738}} {"text": "library(data.table)\nlibrary(ggplot2)\n\nN <- 1000\nXbar <- numeric(N) # space for results\n\nfor( i in 1:n)\n{\n x <- rexp(100, rate = 1/15) # draw random sample of size 100\n Xbar[i] <- mean(x)\n}\n\nhist(Xbar)\n\nqqnorm(Xbar)\nqqline(Xbar)\n\nmean(Xbar)\nsd(Xbar)\n\nmaxY <- numeric(N)\n\nfor( i in 1:N)\n{\n y <- runif(12) # draw random sample of size 12\n maxY[i] <- max(y)\n}\n\nhist(maxY)\n\nX <- rpois(10^4, 5) # Draw 10^4 values from Pois(5)\nY <- rpois(10^4, 12) # Draw 10^4 values from Pois(12)\n\nW <- X + Y\n\nhist(W, prob = T) # prob = T, scales hist to 1\nlines(2:35, dpois(2:35, 17), type = \"b\")\n\nmean(W)\nvar(W)\n\nsd(W) / sqrt(N)\n\nXbar <- numeric(N)\n\nfor( i in 1:N )\n{\n x <- rgamma(30, shape = 5, rate = 2)\n Xbar[i] <- mean(x)\n}\n\nhist(Xbar)\n\nqqnorm(Xbar)\nqqline(Xbar)\n\nmean(Xbar)\nsd(Xbar)\n\nmean(Xbar > 3)\n\n# work\n\np <- c(3, 4, 6, 6)\n\nsample.size <- 2\nperm <- permutations( length(p), sample.size, repeats.allowed = T)\n\nd <- data.table( c1 = p[perm[, 1]], c2 = p[perm[, 2]])\nd[, m := (c1 + c2) / 2]\n\n( 3 - 5/2 ) / (sqrt(5/2^2) / sqrt(30))\n\npnorm(2.44949, lower.tail = F)\n\n\nz <- (0.53333 - 0.5) / 0.0289\npbinom(z, prob = .5, size = 300, lower.tail = T)\n\npbinom(160, size = 300, prob = .5, lower.tail = T)\n\n\n", "meta": {"hexsha": "073775ab18ca1d99dc3b110323836b691084bab7", "size": 1190, "ext": "r", "lang": "R", "max_stars_repo_path": "Mathematical Statistics/04_sampling_distributions.r", "max_stars_repo_name": "bmoretz/Statistical-Computing", "max_stars_repo_head_hexsha": "606e6bb222013c38867c1aee7e79fae762e7a445", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-27T08:18:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-09T09:20:49.000Z", "max_issues_repo_path": "Mathematical Statistics/04_sampling_distributions.r", "max_issues_repo_name": "bmoretz/Statistical-Computing", "max_issues_repo_head_hexsha": "606e6bb222013c38867c1aee7e79fae762e7a445", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mathematical Statistics/04_sampling_distributions.r", "max_forks_repo_name": "bmoretz/Statistical-Computing", "max_forks_repo_head_hexsha": "606e6bb222013c38867c1aee7e79fae762e7a445", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-27T08:18:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-02T11:31:27.000Z", "avg_line_length": 14.3373493976, "max_line_length": 66, "alphanum_fraction": 0.5731092437, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.8007484196849375}} {"text": "\r\n\r\n# Goal: Utilise matrix notation\r\n# We use the problems of portfolio analysis as an example.\r\n\r\n# Prices of 4 firms to play with, at weekly frequency (for calendar 2004) --\r\np <- structure(c(300.403, 294.604, 291.038, 283.805, 270.773, 275.506, 292.271, 292.837, 284.872, 295.037, 280.939, 259.574, 250.608, 268.84, 266.507, 263.94, 273.173, 238.609, 230.677, 192.847, 219.078, 201.846, 210.279, 193.281, 186.748, 197.314, 202.813, 204.08, 226.044, 242.442, 261.274, 269.173, 256.05, 259.75, 243, 250.3, 263.45, 279.5, 289.55, 291.95, 302.1, 284.4, 283.5, 287.8, 298.3, 307.6, 307.65, 311.9, 327.7, 318.1, 333.6, 358.9, 385.1, 53.6, 51.95, 47.65, 44.8, 44.85, 44.3, 47.1, 44.2, 41.8, 41.9, 41, 35.3, 33.35, 35.6, 34.55, 35.55, 40.05, 35, 34.85, 28.95, 31, 29.25, 29.05, 28.95, 24.95, 26.15, 28.35, 29.4, 32.55, 37.2, 39.85, 40.8, 38.2, 40.35, 37.55, 39.4, 39.8, 43.25, 44.75, 47.25, 49.6, 47.6, 46.35, 49.4, 49.5, 50.05, 50.5, 51.85, 56.35, 54.15, 58, 60.7, 62.7, 293.687, 292.746, 283.222, 286.63, 259.774, 259.257, 270.898, 250.625, 242.401, 248.1, 244.942, 239.384, 237.926, 224.886, 243.959, 270.998, 265.557, 257.508, 258.266, 257.574, 251.917, 250.583, 250.783, 246.6, 252.475, 266.625, 263.85, 249.925, 262.9, 264.975, 273.425, 275.575, 267.2, 282.25, 284.25, 290.75, 295.625, 296.25, 291.375, 302.225, 318.95, 324.825, 320.55, 328.75, 344.05, 345.925, 356.5, 368.275, 374.825, 373.525, 378.325, 378.6, 374.4, 1416.7, 1455.15, 1380.97, 1365.31, 1303.2, 1389.64, 1344.05, 1266.29, 1265.61, 1312.17, 1259.25, 1297.3, 1327.38, 1250, 1328.03, 1347.46, 1326.79, 1286.54, 1304.84, 1272.44, 1227.53, 1264.44, 1304.34, 1277.65, 1316.12, 1370.97, 1423.35, 1382.5, 1477.75, 1455.15, 1553.5, 1526.8, 1479.85, 1546.8, 1565.3, 1606.6, 1654.05, 1689.7, 1613.95, 1703.25, 1708.05, 1786.75, 1779.75, 1906.35, 1976.6, 2027.2, 2057.85, 2029.6, 2051.35, 2033.4, 2089.1, 2065.2, 2091.7), .Dim = c(53, 4), .Dimnames = list(NULL, c(\"TISCO\", \"SAIL\", \"Wipro\", \"Infosys\")))\r\n# Shift from prices to returns --\r\nr <- 100*diff(log(p))\r\n\r\n# Historical expected returns --\r\ncolMeans(r)\r\n# Historical correlation matrix --\r\ncor(r)\r\n# Historical covariance matrix --\r\nS <- cov(r)\r\nS\r\n\r\n# Historical portfolio variance for a stated portfolio of 20%,20%,30%,30% --\r\nw <- c(.2, .2, .3, .3)\r\nt(w) %*% S %*% w\r\n\r\n# The portfolio optimisation function in tseries --\r\nlibrary(tseries)\r\noptimised <- portfolio.optim(r) # This uses the historical facts from r\r\noptimised$pw # Weights\r\noptimised$pm # Expected return using these weights\r\noptimised$ps # Standard deviation of optimised port.\r\n\r\n", "meta": {"hexsha": "b4072036c788ab7d285405a06f76b7f84f0f9982", "size": 2657, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/b9.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)/b9.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)/b9.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": 88.5666666667, "max_line_length": 1782, "alphanum_fraction": 0.6202484005, "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8633916064587, "lm_q1q2_score": 0.8006776873325133}} {"text": "N <- 100000\neigenValues <- matrix(nrow=N, ncol=2)\n\nfor (i in 1:N) {\n\trand <- runif(3, min=-1, max=1)\n\tm <- matrix(nrow=2, ncol=2)\n\tm[1,1] <- rand[1]\n\tm[1,2] <- rand[2]\n\tm[2,1] <- rand[2]\n\tm[2,2] <- rand[3]\n\te <- eigen(m)\n\te$values <- c(min(e$values), max(e$values))\n\teigenValues[i,] <- e$values\n}\n\nprint(eigenValues[,1])\n\nhist(eigenValues[,1], col=rgb(0.8, 0, 0, alpha=0.3), xlab=\"eigenvalue\", ylab=\"frequency\", main=\"frequency of eigenvalues\")\nhist(eigenValues[,2], col=rgb(0, 0.8, 0, alpha=0.5), add=T)\n\n\n# Wikipedia [Positive-definite matrix]\n# \"The following properties are equivalent to M being positive definite:\n# All its eigenvalues are positive.\"\n\nposdef <- length(eigenValues[eigenValues[,1] > 0,])\nprint(paste('Absolute # of positive-definite matrices:', posdef))\nprint(paste('Relative # of positive-definite matrices:', 100 * posdef / N, '%'))\n", "meta": {"hexsha": "f225fe07bf227daa50c93fef7237185c0b0f74b1", "size": 856, "ext": "r", "lang": "R", "max_stars_repo_path": "probability_theory_practicals/ex4/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/ex4/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/ex4/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": 29.5172413793, "max_line_length": 122, "alphanum_fraction": 0.6553738318, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.8006776836592259}} {"text": "# Example : 1 Chapter : 4.2 Page No: 208\r\n# Projection of the vector onto line\r\n\r\n#Answers to this problem are displayed in the form of x/y in textbook\r\n#Here the same answers are in decimal formats\r\n\r\nprojection<-function(b,a){\r\n xhat<-(sum(a*b))/(sum(a*a))\r\n p<-xhat*a\r\n return(p)\r\n}\r\nb<-c(1,1,1)\r\na<-c(1,2,2)\r\np<-projection(b,a)\r\nprint(\"The projection vector p i.e., b on a is \")\r\nprint(p)\r\ne<-b-p\r\nprint(\"The error vector is \")\r\nprint(e)\r\nif(sum(e*a)==0){\r\n print(\"Vector e is perpendicular to a\")\r\n}\r\n#The answer may slightly vary due to rounding off values", "meta": {"hexsha": "84b15c6d7c9b91023b4ec57df6b96a182d5adfea", "size": 574, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.2.1/Ex4.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/CH4/EX4.2.1/Ex4.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/CH4/EX4.2.1/Ex4.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": 24.9565217391, "max_line_length": 70, "alphanum_fraction": 0.6445993031, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.8006776801927035}} {"text": "rm(list = ls()) # clear console\n\n\n# ADETAYO ADEGOKE\n# WEEK 02 Homework - Foundations of probablity for finite sample spaces\n# Due: February 10, 2020\n# Mathematics E-23c, Spring 2020\n# Michael Liotti Office Hour Review\n\n\n# Questions 1 (a)\n\n# Creating two columns representing the quiz scores \n# Both quizes have 0.25 probablity of getting 100 and 0.75 probablity of getting 0\nQ1 <- c(100,0,0,0) \nQ2 <- Q1\n\n# create the dataframe with colmns Q1 and Q2. It should have 16 rows\nttbl <- expand.grid(Q1, Q2); ttbl \nQ1 < - ttbl$Var1; Q2 <- ttbl$Var2\nttbl <- data.frame(Q1, Q2); ttbl # rename the columns\n\n\n# Question 1 (b)\n\n# Column X is the random variable the average of the quiz scores: 100, 50 or 0\nX = (Q1 + Q2)/2\nttbl$X <- X; ttbl\n\n# Column Y is the improvement rating random variable\n# Y is 0 if Quiz 2 score is worse\n# Y is 1 if Quiz 1 and 2 scores are the same\n# Y is 2 if Quiz 2 score is better\nY <- ifelse(Q2 < Q1, 0, ifelse(Q2==Q1,1,2)); Y\nttbl$Y <- Y; ttbl\n\n\n# Question 1 (c)\n\n# X and Y are uncorrelated if E(XY) - E(X)E(Y) = 0\n# Check to see if this is true\n(mean(X*Y) - (mean(X) * mean(Y))) == 0 # True, hence X and Y random variables are uncorrelated\n\n\n# Question 1 (d)\n\n# X and Y are independent if E(X^2 * Y^2) - E(X^2)E(Y^2) = 0\n# Check to see if this is true\n(mean((X^2) * (Y^2)) - (mean(X^2) * mean(Y^2))) == 0 # False, hence X and Y random variables are not independent\n\n\n# Question 1 (e)\n\nA <- ifelse(X < Q2, 1, 0) # create an indicator random variable involving X\nB <- ifelse((Y == 0) | (Y == 1), 1, 0) # create an indicator random variable involving Y\nttbl$A <- A; ttbl$B <-B; ttbl # add these variables to the dataframe\nPAandB <- sum(A*B) / nrow(ttbl); PAandB\nPA <- sum(A) / nrow(ttbl); PA # find the probability of A\nPB <- sum(B) / nrow(ttbl); PB # find the probability of B\nPAandB == (PA * PB) # False, hence X and Y random variables are not independent\n\n\n# Question 2 (a)\n\nrm(list = ls()) # clear console\n\n# Checking question 4 in the pencil and paper homework (pnp hw)\n# m = 6, n = 20, k = 13\n\n# Checking P(X = 3) using dhyper() and comparing with our computation in pnp hw\ndhyper(3, 6, 20, 13) # result is 0.3552795\n(choose(6, 3) * choose(20, 10)) / choose(26, 13) # result is 0.3552795\n# We have a match!\n\n# Checking P(X = 2) using dhyper() and comparing with our computation in pnp hw\ndhyper(2, 6, 20, 13) # result is 0.242236\n(choose(6, 2) * choose(20, 11)) / choose(26, 13) # result is 0.242236\n# We have a match!\n\n# Checking P(X = 1) using dhyper() and comparing with our computation in pnp hw\ndhyper(1, 6, 20, 13) # result is 0.07267081\n(choose(6, 1) * choose(20, 12)) / choose(26, 13) # result is 0.07267081\n# We have a match!\n\n# Checking P(X = 0) using dhyper() and comparing with our computation in pnp hw\ndhyper(0, 6, 20, 13) # result is 0.007453416\n(choose(6, 0) * choose(20, 13)) / choose(26, 13) # result is 0.007453416\n# We have a match!\n\n\n# Question 2 (b)\n\nm <- 6 # number of trump cards - type 1 objects\nn <- 20 # number of non-trump cards - type 2 objects\nk <- 13 # number of cards in hand\n\nPlayer <- c(rep(\"EAST\", k), rep(\"WEST\", m + n - k)); Player # create the ownership column\nTrumps <- c(rep(TRUE, 6), rep(FALSE, 20)); Trumps\n\n# Set up key variables for running the simulation to estimate P(X = 3)\nN <- 10000 \nX <- numeric(N)\n\n# Execute the simulation\nfor (i in 1:N){\n scramble <- sample(Trumps, m + n, replace = FALSE) #permute the trumps\n X[i] <- sum((Player == \"EAST\") & scramble)\n}\n(table(X)[4])/N # 0.3562, which is really close to results computed earlier on of 0.3552795\n\n\n# Question 2 (c)\n\n# Setup the second column so that East has two trumps\nEast <- c(rep(TRUE, k), rep(FALSE, m + n - k)); East # create the ownership column\nTrumps <- c(rep(TRUE, 2), rep(FALSE, 20), rep(TRUE, 4))\n\n# Contigency Table\ntable(East, Trumps)\n\n# Running the Fisher exact testto find the probability that East has two or more trumps\nfisher.test(East, Trumps, alternative = \"g\")\n# The test has a p-value of 0.9199, which is the probablity that East has two or more trumps\n\n# Computing dhyper() to compare results above to\n# Note that P(X >= 2) = 1 - P(X < 2) = 1 - P(X <= 1) since X must be an integer\n1 - phyper(1, 6, 20, 13) # computest to 0.9198758 which is close to the the fisher.test results above of 0.9199\n\n\n# Question 3 (a)\n\nrm(list = ls()) # clear console\n\n# load the input file\nsetwd(\"/Users/adegade/OneDrive/Documents/Education/Harvard/Software Engineering/Spring-2020-MATH-E-23C/Homework\")\nNC <- read.csv(\"NCBirths2004.csv\"); head(NC) \n\nidx <- which(NC$Gender == \"Male\") # create an index for extracting gender from the data set\nmmbw <- mean(NC$Weight[idx]); mmbw # compute male babies mean birth weight - 3501.58\n\n# doing a similar exercise for female babies\n# another way to do this is fmbw <- mean(NC$Weight[-idx])\nidx <- which(NC$Gender == \"Female\") # create an index for extracting gender from the data set\nfmbw <- mean(NC$Weight[idx]); fmbw # compute female babies mean birth weight - 3398.317\n\nwdiff <- mmbw - fmbw; diff # mean birth weight difference is 103.2632, just over 100\n\n# Execute a permutation test to determine if the difference in mean shown above is statistically significant\nN <- 10000 # number of experiements to run\ndiff <- numeric(N) # empty vector to store results\n\nfor (i in 1:N) {\n gender <- sample(NC$Gender) # permute the gender labels\n mbavg <- sum(NC$Weight * (gender == \"Male\")) / sum(gender == \"Male\"); mbavg # average weight for males\n fbavg <- sum(NC$Weight * (gender == \"Female\")) / sum(gender == \"Female\"); fbavg # average weight for females\n diff[i] <- mbavg - fbavg # store the average weight difference in the vector\n}\n\nmean(diff) # -0.06855603, which is close to 0\nhist(diff, breaks = \"FD\")\nabline(v= wdiff, col = \"red\") # observed difference is way out on the tail\n\npv1t <- (sum(diff >= wdiff) + 1) / (N + 1); pv1t # 1-tailed p-value is 0.00019998\npv2t <- pv1t * 2; pv2t # 2-tailed p value is 0.00039996\n\n# The two-tailed p-value indicates that there is a very low chance that we could come by the observed differnece\n# in mean birth weights by chance (only a probability of 0.00039996 which is a lot less than .05). As such, we \n# have sufficient evidence against the null hypothesis which is there no difference in the mean birth weights\n# and instead suggest that the alternative hypothesis is true which is that there is indeed a difference in the \n# mean birth weights. The one-tailed p-value suggests that male babies do have a larger mean baby weight than\n# female babies\n\n\n# Question 3 (b)\n\n# Determine whether tobacco use by the mother has a statisticallysignificant effect on birth weight\n\ntb <- NC$Tobacco # extract the tobacco column\nbw <- NC$Weight # extract the baby weight column\n\n# Compute the average weight of babies whose mothers used tobacco\nidxt <- which(NC$Tobacco == \"Yes\") # create an index for extracting tobacco use from the data set\nbwt <- mean(bw[idxt]); mmbwt # compute the babies mean birth weight whose mothers used tobacco - 3256.91\n\n# doing a similar exercise for female babies\n# another way to do this is bwnt <- mean(bw[-idxt])\nidxnt <- which(NC$Tobacco == \"No\") # create an index for extracting tobaco use from the data set\nbwnt <- mean(bw[idxnt]); bwnt # compute the babies mean birth weight whose mothers did not use tobacco - 3471.912\n\nwdifft <- bwnt - bwt; wdifft # mean birth weight difference is 215.0021\n\n# Execute a permutation test to determine if the difference in mean shown above is statistically significant\nN <- 10000 # number of experiements to run\ndifft <- numeric(N) # empty vector to store results\nfor (i in 1:N) {\n tobacco <- sample(tb) # permute the tobacco use labels\n tavg <- sum(bw * (tobacco == \"Yes\")) / sum(tobacco == \"Yes\"); tavg # average weight for babies whose mothers used tobacco\n ntavg <- sum(bw * (tobacco == \"No\")) / sum(tobacco == \"No\"); ntavg # average weight for babies whose mothers did not use tobacco\n difft[i] <- ntavg - tavg # store the average weight difference in the vector\n}\n\nmean(difft) # 0.6645301\nhist(difft, breaks = \"FD\")\nabline(v= wdifft, col = \"blue\") # observed difference is way out on the right tail\n\npv1tt <- (sum(difft >= wdifft) + 1) / (N + 1); pv1tt # 1-tailed p-value is 9.999e-05\npv2tt <- pv1tt * 2; pv2tt # 2-tailed p value is 0.00019998\n\n# The two-tailed p-value indicates that there is a very low chance that we could come by the observed differnece\n# in mean birth weights by chance (only a probability of 0.00019998 which is a lot less than .05). As such, we \n# have sufficient evidence against the null hypothesis which is there no difference in the mean birth weights\n# and instead suggest that the alternative hypothesis is true which is that there is indeed a difference in the \n# mean birth weights based on tobacco usage. The one-tailed p-value suggests that babies whose mothers do not use\n# tobacco have a mean baby weight that is larger than babies whose mothers do uses tobacco\n\n\n# Question 4\n\nrm(list = ls()) # clear console\n\n# load the input file\nsetwd(\"/Users/adegade/OneDrive/Documents/Education/Harvard/Software Engineering/Spring-2020-MATH-E-23C/Homework\")\nBattle <- read.csv(\"Battle.csv\"); head(Battle) \n\nchamps <- \"MEZU\"\nswords <- \"BRIG\"\nsset <- subset(Battle, (Battle$Abbr == champs | Battle$Abbr == swords))\nscore <- sset$Kills - sset$Lost\n\nidxchamps <- which(sset$Abbr == champs) # create an index for extracting MEZU aka champs rows from the data set\n\nmsdiff <- mean(score[idxchamps]) - mean(score[-idxchamps]); msdiff # -14.69173 - mean score difference between champs and swordsmen\n\n# Execute a permutation test to determine if the difference in mean shown above is statistically significant\nN <- 10000 # number of experiements to run\ndiffms <- numeric(N) # empty vector to store results\nnumchamps <- sum(sset$Abbr == champs); numchamps\n\nfor (i in 1:N) {\n idxchamps <- sample(nrow(sset), numchamps)\n diffms[i] <- mean(score[idxchamps]) - mean(score[-idxchamps])\n}\n\nmean(diffms) # -0.03305469 which is close to 0\nhist(diffms, breaks = \"FD\")\nabline(v= msdiff, col = \"purple\") \n\npv1ms <- (sum(diffms <= msdiff) + 1) / (N + 1); pv1ms # 1-tailed p-value is 0.01689831\npv2ms <- pv1ms * 2; pv2ms # 2-tailed p value is 0.03379662\n\n# The two-tailed p-value indicates that there is a low chance that we could come by the observed differnece\n# in mean score (a probability of 0.03379662 which is less than .05). As such, we have sufficient evidence \n# against the null hypothesis which is there no difference in the unit superiority and instead suggest that \n# the alternative hypothesis is true which is that there is indeed a difference in the # unit superiority. \n# The one-tailed p-value suggests that babies the swordsmen unit are more skilled than the champions unit in \n# terms of kills - losses\n", "meta": {"hexsha": "20b0baeee3b1516422ccbdda93209fbf4eaf89f1", "size": 10731, "ext": "r", "lang": "R", "max_stars_repo_path": "adetayo-adegoke-wk02-hw.r", "max_stars_repo_name": "adegade/math-e23c", "max_stars_repo_head_hexsha": "6343e13d7dfea44d4b6d24665b15afce88ebf8d0", "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": "adetayo-adegoke-wk02-hw.r", "max_issues_repo_name": "adegade/math-e23c", "max_issues_repo_head_hexsha": "6343e13d7dfea44d4b6d24665b15afce88ebf8d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adetayo-adegoke-wk02-hw.r", "max_forks_repo_name": "adegade/math-e23c", "max_forks_repo_head_hexsha": "6343e13d7dfea44d4b6d24665b15afce88ebf8d0", "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.7548638132, "max_line_length": 131, "alphanum_fraction": 0.7037554748, "num_tokens": 3309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.9073122132152183, "lm_q1q2_score": 0.8006375777102352}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Non parametric Tests - Exercise 05\n\nrm(list = ls())\n\n\nx <- c(\"B\", \"B\", \"B\", \"A\", \"A\", \"B\", \"A\", \"B\", \"B\", \"B\", \"B\", \"A\", \"B\", \"A\", \"A\", \"B\", \"A\", \"A\", \"A\")\n\n(n <- length(x))\n# 19\n\n(n.a <- sum(x == \"A\"))\n# 9\n\n(n.b <- n - n.a)\n# 10\n\n(W.a <- sum(which(x == \"A\")))\n# 111\n\n(W.ab <- W.a - n.a * (n.a + 1) / 2)\n# 66\n\n(W.ab.mean <- n.a * n.b / 2)\n# 45\n\n(W.ab.var <- n.a * n.b * (n + 1) / 12)\n# 150\n\n### H0: A(x) == B(x)\n### H1: A(x) != B(x)\n\n## Asymptotic pvalue (with continuity correction)\n2 * (1 - pnorm(abs(W.ab + 0.5 * sign(W.ab.mean - W.ab) - W.ab.mean) / sqrt(W.ab.var)))\n# 0.0941663754378799\n\n## Exact Pvalue\n2 * (1 - pwilcox(W.ab - (W.ab.mean < W.ab), n.a, n.b, lower.tail = W.ab.mean < W.ab))\n# 0.0947195219641039\n\nwilcox.test(which(x == \"A\"), which(x == \"B\"))\n# Wilcoxon rank sum test\n#\n# data: which(x == \"A\") and which(x == \"B\")\n# W = 66, p-value = 0.09472\n# alternative hypothesis: true location shift is not equal to 0\n\n## If we choose alpha = 0.05, we don't have enought evidences to reject\n## the hipothesis that both exam models takes same time to complete.\n", "meta": {"hexsha": "304a3b59701615830abfc5dcd14c75054d6ba1b8", "size": 1134, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/non-parametric/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/non-parametric/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/non-parametric/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": 22.68, "max_line_length": 101, "alphanum_fraction": 0.5405643739, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.8003788857608146}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Non parametric Tests - Exercise 04\n\nrm(list = ls())\n\nr <- c(1.1, -21.7, -16.3, -11.3, -10.4, -7.0, -2.0, 1.9, 6.2)\n\n(n.r <- length(r))\n# 9\n\nu <- c(-2.4, 9.9, 14.2, 18.4, 20.1, 23.1, 70.4)\n\n(n.u <- length(u))\n# 7\n\n(n <- n.u + n.r)\n# 16\n\n(W.u <- sum(rank(c(u, r))[1:length(u)]))\n# 87\n\n(W.ur <- W.u - n.u * (n.u + 1) / 2)\n# 59\n\n(W.ur.mean <- n.u * n.r / 2)\n# 31.5\n\n(W.ur.var <- n.u * n.r * (n + 1) / 12)\n# 89.25\n\n### a)\n###\n### H0: U <= R\n### H1: U > R\n\n## Asymptotic pvalue (with continuity correction)\n1 - pnorm((W.ur - 0.5 - W.ur.mean) / sqrt(W.ur.var))\n# 0.00213171569155368\n\n## Exact pvalue\n1 - pwilcox(W.ur - 1, n.u, n.r)\n# 0.00104895104895109\n\n## We reject H0 in favor of H1, so U > R\n\n### b)\n\nA <- matrix(rep(0, n.u * n.r), n.u, n.r)\nfor (i in 1:n.u) {\n for (j in 1:n.r) {\n A[i, j] <- u[i] - r[j]\n }\n}\nmedian(A)\n# 22.1\n\n\nwilcox.test(u, r, alternative = \"greater\", conf.int = TRUE)\n# Wilcoxon rank sum test\n#\n# data: u and r\n# W = 59, p-value = 0.001049\n# alternative hypothesis: true location shift is greater than 0\n# 95 percent confidence interval:\n# 13.9 Inf\n# sample estimates:\n# difference in location\n# 22.1\n\n\n### c)\n\n## TODO\n\n### d)\n\n## TODO\n", "meta": {"hexsha": "e56d0d308efc3c2d0ee058c421f1338a93166391", "size": 1245, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/non-parametric/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/non-parametric/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/non-parametric/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": 15.9615384615, "max_line_length": 68, "alphanum_fraction": 0.5317269076, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.80019437054143}} {"text": "#Series temporais e analises preditivas - Fernando Amaral\r\nlibrary(forecast)\r\nlibrary(ggplot2)\r\n\r\nautoplot(fdeaths)\r\n\r\n#calculando a media movel com ordem 5\r\nfdeaths2 = ma(fdeaths, order = 5 )\r\nautoplot(fdeaths2)\r\n\r\n#novamente, ordem 12\r\nfdeaths3 = ma(fdeaths,order=12)\r\nautoplot(fdeaths3)\r\n\r\n#limpeza dos dados\r\nfdeaths4 = tsclean(fdeaths)\r\nautoplot(fdeaths4)\r\n\r\n#comparando \r\nplot(fdeaths)\r\nlines(fdeaths2, col=\"red\")\r\nlines(fdeaths3, col=\"blue\")\r\nlines(fdeaths4, col=\"green\")\r\n\r\n#legenda\r\nlegend(\"topright\",legend=c(\"Orig.\",\"Ma5\",\"Ma12\",\"Tsc\"), col = c(\"black\",\"red\",\"blue\",\"green\"), lty=1:2, cex=0.8,)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "509dc3036dbdae08ad3ef46b183a951afc46d0f9", "size": 625, "ext": "r", "lang": "R", "max_stars_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/5.7.R Medias Moveis.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/5.7.R Medias Moveis.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/5.7.R Medias Moveis.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.3611111111, "max_line_length": 114, "alphanum_fraction": 0.6784, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.8000048304522906}}