{"text": "par(mfrow=c(1,2))\n# Option 2: inverse square\nx <- seq(1,5,0.1)\ny <- 1/(x^2)\nplot(y, main = \"Inverse Square\", type = \"l\")\n\n# negative exponential movement function (option 5 in CDPOP)\na <- 1\nb <- 1\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, main = \"Negative Exponential\", type = \"l\")\n\n\n\n\n# negative exponent comparing effects of parameters a and b\npar(mfrow=c(3,4))\na <- 1\nb <- 1\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=1 b=1')\n\na <- 2\nb <- 1\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=2 b=1')\n\na <- 4\nb <- 1\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=4 b=1')\n\na <- 8\nb <- 1\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=8 b=1')\n\na <- 1\nb <- 2\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=1 b=2')\n\na <- 1\nb <- 4\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=1 b=4')\n\na <- 1\nb <- 8\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=1 b=8')\n\na <- 2\nb <- 2\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=2 b=2')\n\na <- 4\nb <- 2\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=4 b=2')\n\na <- 8\nb <- 2\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=8 b=2')\n\na <- 2\nb <- 4\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=2 b=4')\n\na <- 2\nb <- 8\nx <- seq(1,5, 0.1)\ny <- a*10^(-b*x)\nplot(y, ylim=c(0,0.5), xlim=c(0,20), type = \"l\", main = 'a=2 b=8')\n\n", "meta": {"hexsha": "21e6793fc37b7bdd8aa4d02158fac83bc79dcb55", "size": 1782, "ext": "r", "lang": "R", "max_stars_repo_path": "Notes/neg_exp.r", "max_stars_repo_name": "karljarvis/MortSims", "max_stars_repo_head_hexsha": "d386c458d3ffdf5f5e20500fdb5e0737ab4a141a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notes/neg_exp.r", "max_issues_repo_name": "karljarvis/MortSims", "max_issues_repo_head_hexsha": "d386c458d3ffdf5f5e20500fdb5e0737ab4a141a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/neg_exp.r", "max_forks_repo_name": "karljarvis/MortSims", "max_forks_repo_head_hexsha": "d386c458d3ffdf5f5e20500fdb5e0737ab4a141a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5824175824, "max_line_length": 66, "alphanum_fraction": 0.4792368126, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011976, "lm_q2_score": 0.9161096135894201, "lm_q1q2_score": 0.8912196172208676}}
{"text": "'''\nIn this homework, you are supposed to learn how to simulate and estimate AR/MA models\nin R, and how to use ACF and PACF to identify models\n'''\n\n# 3.1\n'''\nConsider an AR(1) process f(t) = \u00f8*f(t-1) + z(t), z~N(0,4)   |\u00f8| < 1\nSimulate with \u00f8 = 0.7, t=1..n, n=10000=10^4\n\nNote: ACF of AR(1): y = \u00f8^h, h >= 1\npartial autocorrelation function alpha(h) = 1 if h=1 else 0\n'''\n\n#A: Plot the sample autocorrelation function \u03c1_hat sample partial autocorrelation function \u03b1_hat of the simulated process.\n#How are these consistent with an AR(1) process? Can you see the relation between \u00f8 and \u03c1_hat(1)\n\n\nset.seed(1234)\ny <- arima.sim(\n\tmodel = list(ar = 0.7),\n\tn = 10000,\n\tinnov = rnorm(10000, sd = 2)\n)\n\npar(mfrow=c(1,2)) #create a window with 1 row and 2 columns\nAutoCorrelation = acf(x, plot = FALSE)\nplot(AutoCorrelation, main = \"Auto Corr. Func. AR(1)\")\nPartialAutoCorr = pacf(x, plot=FALSE)\nplot(PartialAutoCorr, main=\"Partial Auto Corr. Func.\")\n\n#The ACF \"tails off\" to || x_n - x_m || < Epsilon after t>=10\n#The PACF \"cuts off\" at t=2\n\n'''\nf\\Mdl|      AR(P)     | MA(q)           | ARMA(p,q)\n----------------------------------------------\nACF  |Tails off       | cuts off at t=q | Tails off\nPACF |cuts off at t=p | Tails off       | Tails off\n'''\n\nalpha_1 =pacf(x, plot=FALSE)$acf[1]\n\n#[1] 0.7011247\n# alpha(1) approx \u00f8\n\n#B: Make a plot comparing the sample autocorrelation with the theoretical autocorrelation. Do the same for the partial autocorrelation\n\nphi = .7\nacf_theo = phi^(0:40) # Numerical Theoretical ACF with up to 40 lags - length 41 y(h) = \u00f8^h , h >= 1\npacf_theo = c(phi, rep(0,39)) # Theoretical PACF with up to 40 lags - length 40: p(h) = \u00f8^h , if h=1 else p(h)=0\n# Plotting ACF and PACF\npar(mfrow=c(1,2))\n\nacf_empirical = acf(x, plot=FALSE)$acf\npacf_empirical = pacf(x, plot=FALSE)$acf\n\n# length acf(x, plot=FALSE)$acf = 41\nplot(0:40, acf_empirical, type = \"h\", ylab = \"ACF\", xlab = \"h\")\nlines(0:40, acf_theo , col=2, type = \"l\", lty=2)\nlegend(\"topright\", col = 1:2, legend = c(expression(hat(rho)(h)),expression(rho(h))), lty=1:2)\n\n# length( pacf(x,plot=FALSE)$acf ) = 40\nplot(1:40, pacf_empirical, type = \"h\", ylab = \"PACF\", xlab =\"h\")\nlines(1:40, pacf_theo, col=2, type = \"l\",lty=2)\nlegend(\"topright\", col = 1:2, legend = c(expression(hat(alpha)(h)),expression(alpha(h))), lty=1:2)\n\n# length [acf = pacf +1]\n\n# The theoretical and empirical seem to agree.\n\n#C: Estimate an AR(1) and an AR(2) model for the simulated data using the arima function in R. \n#   Compare the two models. \n#   Is \u00f8_hat_2 signficantly different from zero? \n#   Compare the quality of \u00f8_1 for the two models in terms of bias and standard error.\n\narima(x, order =c(1,0,0), include.mean = FALSE) # AR(1) # order (p,d,q)(P,Q,D) - (non-seasonal) component\n\n'''\nCall:\narima(x = x, order = c(1, 0, 0), include.mean = FALSE)\n\nCoefficients:\n         ar1\n      0.7012 = \u00d8\ns.e.  0.0071 = standard error\n\nsigma^2 estimated as 3.901:  log likelihood = -20996.39,  aic = 41996.78\n'''\n\narima(x, order =c(2,0,0), include.mean = FALSE) # AR(2)\n\n'''\nCall:\narima(x = x, order = c(2, 0, 0), include.mean = FALSE)\n\nCoefficients:\n         ar1      ar2\n      0.7023  -0.0015\ns.e.  0.0100   0.0100\n\nsigma^2 estimated as 3.901:  log likelihood = -20996.38,  aic = 41998.76\n'''\n\n# Q:Is \u00f8_hat_2 signficantly different from zero? \n# A: \u00f8_hat_2 = -0.0015 - close to zero\n\n# Q: Compare the quality of \u00f8_hat_1 for the two models in terms of bias and standard error.\n# A: Coefficients for AR(1) -> \u00f8_hat_1=0.712, and AR(2) -> \u00f8_hat_1 =0.7023 There is a small difference\n#    Standard error - AR(1) -> s.e    =0.0071, and AR(2) ->s.e.    =0.01   There is a small difference\n\n#Note: \u00f8_hat_2 =0.01 and s.e for it is 0.01 so \u00f8_hat_2 is close to zero\n#\n# AR(1) =>  log likelihood = -20996.39\n# AR(2) =>  log likelihood = -20996.38\n\n# 3.2 \n# C:  Simulate the  process as an AR(1) model \n#     with \u03b8 = 0.7 for t = 1, . . . , n with n = 10000 by implementing MA(1)\n# Y_t = \u03b8 Z_t\u22121 + Z\n\ny = arima.sim(\n\tmodel = list(ma = c(.7)),\n\tn = 10000,\n\tinnov = rnorm(10000, sd = 2)\n)\n\n#D: Plot the sample ACF and PACF for the simulated data. How are these consistent with an MA(1) process\npar(mfrow=c(1,2))\nacf(y)\npacf(y)\n\n#ACF cuts off after one lag \n#PACF tails off - like MA(p) model\n\n# E: Fit an MA(a) and an AR(5) model to the simulated data. \n#    Compare the respective AR coefficients with the correspodning powers of \u03b8 in (2). \n#    How well does it fit?\n#    Will an AR(10) improve the result?\n\ntheta = 0.7\nma1 = arima(y, order = c(0,0,1), include.mean=FALSE) #MA(1)\n'''\nCall:\narima(x = y, order = c(0, 0, 1), include.mean = FALSE)\n\nCoefficients:\n         ma1\n      0.6987\ns.e.  0.0072\n\nsigma^2 estimated as 3.992:  log likelihood = -21111.36,  aic = 42226.73\n'''\n\nar5 = arima(y, order = c(5,0,0), include.mean=FALSE)\n'''\nCall:\narima(x = y, order = c(5, 0, 0), include.mean = FALSE)\n\nCoefficients:\n         ar1      ar2     ar3      ar4     ar5\n      0.6876  -0.4605  0.2956  -0.1814  0.0764\ns.e.  0.0100   0.0120  0.0125   0.0120  0.0100\n\nsigma^2 estimated as 4.028:  log likelihood = -21155.74,  aic = 42323.49\n'''\n\n# From (2) we should have:\n'''\n> -0.7^2\n[1] -0.49\n> 0.7^3\n[1] 0.343\n> -0.7^4\n[1] -0.2401\n> 0.7^5\n[1] 0.16807\n'''\n# For j=1..4 the terms match +-0.05 but is more for j=5.\n\nar10 = arima(y, order = c(10,0,0), include.mean=FALSE)\nrbind(ar10$coef,theta^(1:10)*(-1)^(2:11))\n\n#The terms match very well\n\n", "meta": {"hexsha": "a810310b0afa628bb3b170c3e0cfaad5c88a360b", "size": 5368, "ext": "r", "lang": "R", "max_stars_repo_path": "hw3/hw3.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": "hw3/hw3.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": "hw3/hw3.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": 28.8602150538, "max_line_length": 134, "alphanum_fraction": 0.631147541, "num_tokens": 2046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.9425067264481115, "lm_q1q2_score": 0.8906638751614178}}
{"text": "library(gtools)\n#install.packages(\"moments\")\nlibrary(moments)\n\n#Generate N=15 independent binomial random variables with n=5 trials and probability p=.6\nrbinom(15, 5,.6 ) ## this means that out of 5 trials we either get a success or we do not with a probability of 0.6\n\n#What if we up the probability to p=0.99 for getting a success?\n\nrbinom(15, 5,.99 )\n\n# Probability distribution\n#Generate a sample of N=10,000 with n=7 trials and a probability of success p=.3\nX=rbinom(10000,7, .3)\n\n#X\n# Barplot of the probability distribution \n## Why barplot and not a histogram??\n# If I sample 10,000 numbers from Bin(n=7, p=.3), what does the distribution look like?\nbarplot(table(X))\n\n\n##distribution: this gives you the probability of x=0,1,2,3,4,5,6,7\ndbinom(0:7, 7, .3)\n#note: these outputs are between 0 and 1 and are probabilities! ie) a single point/outcome has probability\n\n#check our assumption that the probabilities sum to 1!\nsum(dbinom(0:7, 7, .3))\n\n\n#Example: What is the probability of exactly 2 successes (P(X=2)) for a binomial distribution Bin(n=7, p=.3)? \ndbinom(2,7,.3) #calculate using R\n#choose(7,2)*(.3^2)*(.7^5) #calculate by hand\n\n#sample mean\nmean(X) \n7*.3\n#sample variance\nvar(X)\n7*.3*(1-.3)\n#sample standard deviation\nsd(X)\nsqrt(7*.3*(1-.3))\n\n#Sample of 10\nX_10=rbinom(10,7, .3)\n#sample mean\nmean(X_10)\n7*.3\n#sample variance\nvar(X_10)\n7*.3*(1-.3)\n#sample standard deviation\nsd(X_10)\nsqrt(7*.3*(1-.3))\n\n#Generate N=15 independent normal random variables with mean=20 and sd=8 \nN_15=rnorm(15, mean=20,sd=8 ) \nN_15\n\n#What is the mean of our sample?\nmean(N_15) #Is this close to E(x)=20?\n\n\n#What is the variance of our sample? The standard deviation?\nvar(N_15) \nsd(N_15) \n\n#What is the skewness and kurtosis of our sample?\nskewness(N_15) #skewness of normal distribution is 0!\n#negative indicates skewed left, positive indicates skewed right\nkurtosis(N_15) #kurtosis of normal distribution should be near 3\n\n#plot a histogram of the distribution of our sample\nh<-hist(N_15, breaks=5, col=\"blue\", xlab=\"Simulation\", \n  \tmain=\"Histogram with Normal Curve\") \nxfit<-seq(min(N_15),max(N_15),length=15) \nyfit<-dnorm(xfit,mean=20,sd=8) \nyfit <- yfit*diff(h$mids[1:2])*length(N_15) \nlines(xfit, yfit, col=\"green\", lwd=2) #normal curve\n\n\n\n#Now generate N=10000 independent normal random variables with mean=20 and sd=8\nN_big=rnorm(10000, mean=20, sd=8)\n\n\n#What is the mean of our sample?\nmean(N_big) #Is this close to E(x)=20?\n\n### This is called the law of large numbers!  \n#The average of the results obtained from a large number of \n#trials should be close to the expected value\n\n#What is the variance of our sample?\nvar(N_big)\nsd(N_big) \n\n#What is the skewness and kurtosis of our sample?\nskewness(N_big) #skewness of normal distribution is 0!\n#negative indicates skewed left, positive indicates skewed right\nkurtosis(N_big) #kurtosis of normal distribution is near 3\n\n#plot a histogram of the distribution of our sample\nh_big<-hist(N_big, breaks=50, col=\"blue\", xlab=\"Simulation\", \n  \tmain=\"Histogram with Normal Curve\") \n#xfit<-seq(min(N_big),max(N_big),length=10000) \n#yfit<-dnorm(xfit,mean=20,sd=8) \n#yfit <- yfit*diff(h$mids[1:2])*length(N_big) \n#lines(xfit, yfit, col=\"green\", lwd=2) #normal curve\n\nx=seq(2.5,4.5,0.001)\n\nplot(x,dnorm(x,mean=3.5,sd=0.34),type='l',main='The distribution of the sample mean using CLT')\n\nbarX=rep(0,1000)\nfor (i in 1:1000){barX[i]=mean(sample(1:6,30,replace=T))}\nmean(barX)\nvar(barX)\n\nhist(barX,freq=NULL, col=\"Green\")\npar(new=TRUE)\nplot(x,dnorm(x,mean=3.5,sd=0.34),type='l', xaxt=\"n\", yaxt=\"n\", xlab=\"\", ylab=\"\", col=\"purple\")\n", "meta": {"hexsha": "a42efcdde7b49ef1d720f3b48708c5b4d4babfd3", "size": 3572, "ext": "r", "lang": "R", "max_stars_repo_path": "RVDistSamp.r", "max_stars_repo_name": "sarahmul/BioStatsBasics", "max_stars_repo_head_hexsha": "4f6cf9ec23b14da48414c1f7d483be7a736b14b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RVDistSamp.r", "max_issues_repo_name": "sarahmul/BioStatsBasics", "max_issues_repo_head_hexsha": "4f6cf9ec23b14da48414c1f7d483be7a736b14b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RVDistSamp.r", "max_forks_repo_name": "sarahmul/BioStatsBasics", "max_forks_repo_head_hexsha": "4f6cf9ec23b14da48414c1f7d483be7a736b14b3", "max_forks_repo_licenses": ["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.8064516129, "max_line_length": 115, "alphanum_fraction": 0.7197648376, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924802053235, "lm_q2_score": 0.9149009480320036, "lm_q1q2_score": 0.889276841619829}}
{"text": " rnorm(10) #normal distribution of 10 numbers\nrnorm(10, mean=100, sd=20) \nrandNorm10 <- rnorm(10)\nrandNorm10\ndnorm(randNorm10) #probability of these numbers occuring\ndnorm(c(-1,0,1))\n\nrequire(ggplot2)\nrandNorm <- rnorm(30000)\nrandDensity <- dnorm(randNorm)\nggplot(data.frame(x=randNorm, y=randDensity)) + aes(x=x, y=y) + \n  geom_point() +\n  labs(x=\"Random Variables\", y=\"Density\")\n\npnorm(randNorm10)\npnorm(c(-3, 0, 3)) #left tail probability\npnorm(1) - pnorm(0)\n\nrandNorm10\npnorm(randNorm10)\nqnorm(pnorm(randNorm10))\n\nrbinom(n=1, size=10, prob=0.4)\nrbinom(n=5, size=10, prob=0.4)\nrbinom(n=10, size=10, prob=0.4)\nrbinom(n=1, size=1, prob=0.4)\n\nbinomData <- data.frame(Success=rbinom(n=10000, size=10, prob=0.3))\nggplot(binomData, aes(x=Success)) + geom_histogram(binwidth=1)\n\nbinom5 <- data.frame(Successes=rbinom(n=10000, size=5, prob=0.3), Size=5)\nhead(binom5)\nbinom10 <- data.frame(Successes=rbinom(n=10000, size=10, prob=0.3), Size=10)\nbinom100 <- data.frame(Successes=rbinom(n=10000, size=100, prob=0.3), Size=100)\nbinom1000 <- data.frame(Successes=rbinom(n=10000, size=1000, prob=0.3), Size=1000)\nbinomAll <- rbind(binom5, binom10, binom100, binom1000)\nhead(binomAll)\ntail(binomAll)\nggplot(binomAll, aes(x=Successes)) + geom_histogram() + facet_wrap(~Size, scales=\"free\")\n\ndbinom(x=3, size=10, prob=0.3)\npbinom(q=3, size=10, prob=0.3)\nqbinom(p=0.3, size=10, prob=0.3)\nqbinom(p=c(.3, .35, .4, .5, .6), size=10, prob=0.3)\n\npois1 <- rpois(n=10000, lambda=1)\npois2 <- rpois(n=10000, lambda=2)\npois5 <- rpois(n=10000, lambda=5)\npois10 <- rpois(n=10000, lambda=10)\npois20 <- rpois(n=10000, lambda=20)\n\npois <- data.frame(Lambda.1=pois1, Lambda.2=pois2, Lambda.5=pois5, Lambda.10=pois10, Lambda.20=pois20)\nhead(pois)\n\nrequire(reshape2)\npois <- melt(data=pois, variable.name=\"Lambda\", value.name=\"x\")\nhead(pois)\ntail(pois)\nrequire(stringr)\npois$Lambda <- str_extract(string=pois$Lambda, pattern=\"\\\\d+\")\nhead(pois)\nclass(pois$Lambda)\npois$Lambda <- as.factor(as.numeric(pois$Lambda))\ntail(pois)\n\nggplot(pois, aes(x=x)) + \n  geom_density(aes(group=Lambda, color=Lambda, fill=Lambda), adjust=4, alpha=1/2) + \n  scale_color_discrete() + scale_fill_discrete() +\n  ggtitle(\"Probability Mass function\")\n\nx <- sample(x=1:100, size=100, replace=TRUE)\nx\nmean(x)\n#removing nulls while calculating averages\ny<-x\ny[sample(x=1:100, size=20, replace=FALSE)] <- NA\nmean(y)\nmean(y,na.rm=TRUE)\n\n#weighted averages\ngrades <- c(95, 72, 87, 66)\nweights <- c(1/2, 1/4, 1/8, 1/8)\nmean(grades)\nweighted.mean(x=grades, w=weights)\n\n#variance: how spread out the data is? smaller variance, closer the values are to the center\nvar(x)\nmean(x)\nsum((x-mean(x))^2)/(length(x)-1)\nsqrt(var(x))\nsd(x)\nsd(y)\nsd(y,na.rm=TRUE)\n\nsummary(x)\nsummary(y)\n\nquantile(x, probs=c(.25,.75))\nquantile(x, probs=c(.1, .25, .5, .75, .92))\n\nrequire(ggplot2)\ncor(economics$pce, economics$psavert)\ncor(economics[, c(2, 4:6)])\neconCor <- cor(economics[, c(2, 4:6)])\nrequire(reshape2)\neconMelt <- melt(econCor, varnames=c(\"x\", \"y\"), value.name = \"Correlation\")\neconMelt <- econMelth[order(econMelt$Correlation), ]\neconMelt\nrequire(scales)\nggplot(econMelt, aes(x=x, y=y)) + \n  geom_tile(aes(fill=Correlation)) + \n  scale_fill_gradient2(low=muted(\"red\"), mid=\"white\", high=\"steelblue\", \n                       guide=guide_colorbar(ticks=FALSE, barheight=10),\n                       limits=c(-1,1)) + \n  theme_minimal() + labs(x=NULL, NULL)\n\n\nm <- c(9, 9, NA, 3, NA, 5, 8, 1, 10, 4)\nn <- c(2, NA, 1, 6, 6, 4, 1, 1, 6, 7)\np <- c(8, 4, 3, 9, 10, NA, 3, NA, 9, 9)\nq <- c(10, 10, 7, 8, 4, 2, 8, 5, 5, 2)\nr <- c(1, 9, 7, 6, 5, 6, 2, 7, 9, 10)\ntheMat <- cbind(m, n, p, q, r)\ntheMat\ncor(theMat)\ncor(theMat, use=\"everything\")\ncor(theMat, use=\"all.obs\")\ncor(theMat, use=\"complete.obs\")\ntheMat\ncor(theMat, use=\"na.or.complete\")\n", "meta": {"hexsha": "183b5a0730aeac1ec37f2103be6b6d34e0f8173c", "size": 3755, "ext": "r", "lang": "R", "max_stars_repo_path": "statistics/basics.r", "max_stars_repo_name": "thezorb/rBible", "max_stars_repo_head_hexsha": "19c5d1c8e3a4fc1a35ea7041f539b5c20587e6c3", "max_stars_repo_licenses": ["MIT"], "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/basics.r", "max_issues_repo_name": "thezorb/rBible", "max_issues_repo_head_hexsha": "19c5d1c8e3a4fc1a35ea7041f539b5c20587e6c3", "max_issues_repo_licenses": ["MIT"], "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/basics.r", "max_forks_repo_name": "thezorb/rBible", "max_forks_repo_head_hexsha": "19c5d1c8e3a4fc1a35ea7041f539b5c20587e6c3", "max_forks_repo_licenses": ["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.6641221374, "max_line_length": 102, "alphanum_fraction": 0.6740346205, "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140225647107, "lm_q2_score": 0.9149009526726544, "lm_q1q2_score": 0.8846305603970023}}
{"text": "# Example : 6.4B   Chapter : 6.4     Page No: 336\r\n# Eigen Values and Eigen vectors of given matrices\r\nA3<-matrix(c(2,-1,0,-1,2,-1,0,-1,2),ncol=3)\r\neigenvalues<-eigen(A3)$values\r\nx<-eigen(A3)$vectors\r\nprint(\"Eigen values of A3 are \")\r\nprint(eigenvalues)\r\nprint(\"Eigen vectors of A3 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]*(1/x[1,1])\r\nx[,2]<-x[,2]*(sqrt(2)/x[1,2])\r\nx[,3]<-x[,3]*(1/x[1,3])\r\nprint(\"Eigen vectors with respect to the above eigen values respectively are\")\r\nprint(x)\r\nB4<-matrix(c(1,-1,0,0,-1,2,-1,0,0,-1,2,-1,0,0,-1,1),ncol=4)\r\nB4eigenvalues<-eigen(B4)$values\r\nB4x<-eigen(B4)$vectors\r\nprint(\"Eigen values of B4 are \")\r\nprint(B4eigenvalues)\r\nprint(\"Eigen vectors of B4 in normalised form are\")\r\nprint(B4x)\r\n#to get eigen vectors in the textbook multiply normalised vectors by scalars\r\nB4x[,1]<-B4x[,1]*(1/B4x[1,1])\r\nB4x[,2]<-B4x[,2]*(1/B4x[1,2])\r\nB4x[,3]<-B4x[,3]*(1/B4x[1,3])\r\nB4x[,4]<-B4x[,4]*(1/B4x[1,4])\r\nprint(\"Eigen vectors with respect to the above eigen values respectively are\")\r\nprint(B4x)\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": "566bf02734b078f0ec247792dabd8fc2eabf7134", "size": 1345, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.4.b/Ex6_6.4B.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.b/Ex6_6.4B.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.b/Ex6_6.4B.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.7575757576, "max_line_length": 99, "alphanum_fraction": 0.6817843866, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.9230391648332472, "lm_q1q2_score": 0.880548074840793}}
{"text": "\n#Prices of Certain Items in Selected Cities vs New York\n\ncost <- read.table(\"Cost_of_Living_2013.txt\", sep = \"\\t\", header = TRUE)\nnames(cost)\n# [1] \"City\"                         \"Cost.of.Living.Index\"         \"Rent.Index\"                  \n# [4] \"Groceries.Index\"              \"Restaurant.Price.Index\"       \"Local.Purchasing.Power.Index\"\n\n# Produce scatterplot\nplot(cost$Rent.Index ~ cost$Cost.of.Living.Index, xlab = \"Cost of Living Index\", ylab = \"Cost of Rent Index\", data = cost)\n\nplot(cost$Groceries.Index ~ cost$Cost.of.Living.Index, xlab = \"Cost of Living Index\", ylab = \"Cost of Groceries Index\", data = cost)\n\nplot(cost$Restaurant.Price.Index ~ cost$Cost.of.Living.Index, xlab = \"Cost of Living Index\", ylab = \"Restaurant Price Index\", data = cost)\n\nplot(cost$Local.Purchasing.Power.Index ~ cost$Cost.of.Living.Index, xlab = \"Cost of Living Index\", ylab = \"Local Purchasing Power Index\", data = cost)\n\n# Correlation Coefficients\ncor(cost$Rent.Index, cost$Cost.of.Living.Index)\n    # 0.7722926\ncor(cost$Cost.of.Living.Index, cost$Groceries.Index)\n    # 0.9538616\ncor(cost$Cost.of.Living.Index, cost$Restaurant.Price.Index)\n    # 0.9493554\ncor(cost$Cost.of.Living.Index, cost$Local.Purchasing.Power.Index)\n    # 0.525902\n\n\n# Linear Regression Model Check if Meet Conditions for Coorelation\n\n\nrentReg <- lm(Rent.Index ~ Cost.of.Living.Index, data = cost)\nplot(cost$Rent.Index ~ cost$Cost.of.Living.Index, xlab = \"Cost of Living Index\", ylab = \"Cost of Rent Index\", data = cost)\nabline(rentReg)\nsummary(rentReg)\n\n\ngroceriesReg <- lm(Groceries.Index ~ Cost.of.Living.Index, data = cost)\nplot(cost$Groceries.Index ~ cost$Cost.of.Living.Index, xlab = \"Cost of Living Index\", ylab = \"Cost of Groceries Index\", data = cost)\nabline(groceriesReg)\nsummary(groceriesReg)\n\n\nrestaurantPriceReg <- lm(Restaurant.Price.Index ~ Cost.of.Living.Index, data = cost)\nplot(cost$Restaurant.Price.Index ~ cost$Cost.of.Living.Index, xlab = \"Cost of Living Index\", ylab = \"Restaurant Price Index\", data = cost)\nabline(restaurantPriceReg)\nsummary(restaurantPriceReg)\n\n\nlocalPurchasingPowerReg <- lm(Local.Purchasing.Power.Index ~ Cost.of.Living.Index, data = cost)\nplot(cost$Local.Purchasing.Power.Index ~ cost$Cost.of.Living.Index, xlab = \"Cost of Living Index\", ylab = \"Local Purchasing Power Index\", data = cost)\nabline(localPurchasingPowerReg)\n\n\n# Find Cost of Living as predicted by Groceries Index...\n#... and residual for Beijing, China\nrange(cost$Cost.of.Living.Index)\n\nnew <- data.frame(Cost.of.Living.Index = c(83.57))\npredict(groceriesReg,newdata = new)\ngroceriesReg$residuals[172] #Index of Beijing\n\n    # Prediction cost of living in Beijing = 88.85556\n#Cost of living and residual\n", "meta": {"hexsha": "1f7b7fee76e58b24e670d628f91d8786d774b77c", "size": 2679, "ext": "r", "lang": "R", "max_stars_repo_path": "Prices_of_Items_NYC/Price_analysis.r", "max_stars_repo_name": "wzmemo/Starting_Regression_STA3155", "max_stars_repo_head_hexsha": "481fbfb96b17c9bc3ba6199e1eba68600ab85d49", "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": "Prices_of_Items_NYC/Price_analysis.r", "max_issues_repo_name": "wzmemo/Starting_Regression_STA3155", "max_issues_repo_head_hexsha": "481fbfb96b17c9bc3ba6199e1eba68600ab85d49", "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": "Prices_of_Items_NYC/Price_analysis.r", "max_forks_repo_name": "wzmemo/Starting_Regression_STA3155", "max_forks_repo_head_hexsha": "481fbfb96b17c9bc3ba6199e1eba68600ab85d49", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2153846154, "max_line_length": 150, "alphanum_fraction": 0.7200447928, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688783, "lm_q2_score": 0.9124361676202372, "lm_q1q2_score": 0.8788863759456782}}
{"text": "\npH <- c(8,9,8,10,10,9,10,7,12,12,11,12,9,10,11,11,9,10,11,9,9,10,11,9,8,10,8,9,10,\n        8,9,13,13,7,10,10,9,9,9,9,10,13,11,6,8,7,7,10,8,5,11,11,7,10,10,12,8,9,13,\n        11,10,11,10,9,9,8,11,12,10,9,7,10,11,10,9)\n\nn <- length(pH)\nnj <- table(pH)\nprint(nj)\nnj <- c(0, 0, 0, 0, nj, 0)\nnames(nj) <- 1:14\n# frecuencias relativas\nhj <- nj/n\n# frecuencias acumuladas\nNj <- cumsum(nj)\nHj <- cumsum(hj)\n\n# b) Diagrama de barras para las frecuencias relativas.\nbarplot(height = 100*hj, xlab = \"pH\", ylab = \"F. Relativa (%)\", density = 16, \n        col = \"lightblue\", border = \"blue\")\n\n# c) Hacer un diagrama de barras para las frecuencias relativas acumuladas.\nbarplot(height = 100*Hj, xlab = \"pH\", ylab = \"F. Rel. Acumulada (%)\", density = 16, \n        col = \"lightblue\", border = \"blue\")\n\n# d) Usando la informaci\u00f3n de la tabla y de los diagramas, responder las siguientes preguntas:\n#   * \u00bfCu\u00e1ntas observaciones se realizaron en este caso?\nprint(n) # 75\n#   * \u00bfCu\u00e1ntas observaciones en la muestra tienen un pH netro? \u00bf\u00e1cido? \u00bfb\u00e1sico?\nsum(nj[7])      # pH Neutro\nsum(nj[1:6])    # pH \u00e1cido\nsum(nj[8:14])   # pH b\u00e1sico\n\n#   * \u00bfQu\u00e9 porcentaje de observaciones tienen un pH neutro? \u00bf\u00e1cido? \u00bfb\u00e1sico?\nsum(100*hj[7])\nsum(100*hj[1:6])\nsum(100*hj[8:14])\n\n#   * \u00bfQue porcentaje de observaciones tienen un pH entre 9 y 11 unidades, inclusive?\nsum(100*hj[9:11])\n\n\n# Considere la informaci\u00f3n de la siguiente disitrbuci\u00f3n de frecuencias:\n# a) Completar la tabla\nn <- 80\nhj <- c(4/n,0.15,0.25,0.75-0.25-0.15-0.05,1-0.75)\nprint(hj)\nHj <- cumsum(hj)\nprint(Hj)\nnj <- hj*n\nprint(nj)\nNj <- cumsum(nj)\nprint(Nj)\n\n# b. \n# b* La cantidad de datos mayores a 15 es 44%.\nsum(nj[4:5]) # Falso, nos estan pidiendo es cantidad de datos y no el porcentaje\n\n# b* La cantidad de datos mayores que 5 pero menores que 20 es 36.\nsum(nj[2:3]) # Falso, el resultado es 32\n# b* La proporci\u00f3n de datos mayores que 10 es 95.\nsum(100*hj[3:5]) # Falso la proporci\u00f3n es del 80%\n# b* La proporci\u00f3n de datos entre 10 y 20, inclusive, es 70%.\nsum(100*hj[2:4]) # Verdadera\n", "meta": {"hexsha": "02b345cb40a5639df904961cf4b0ab531409c202", "size": 2025, "ext": "r", "lang": "R", "max_stars_repo_path": "02.tablas/taller2.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": "02.tablas/taller2.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": "02.tablas/taller2.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": 31.640625, "max_line_length": 94, "alphanum_fraction": 0.652345679, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.9196425377849806, "lm_q1q2_score": 0.877307802958397}}
{"text": "# Example : 6.1A   Chapter : 6.1     Page No: 291\r\n# Eigen values and eigen vectors\r\nsolution<-function(A){\r\n  sol<-eigen(A)\r\n  lambda<-sol$values\r\n  x<-sol$vectors #these are normalised eigen vectors\r\n  #to get the eigen vectors as in texxt book multiply these normalised vectors with scalars\r\n  x[,1]<-x[,1]*(1/x[1,1])\r\n  x[,2]<-x[,2]*(1/x[1,2])\r\n  print(\"The eigen values of the matrix are\")\r\n  print(lambda)\r\n  print(\"The eigen vecotrs of the matrix respective to above eigen values are\")\r\n  print(x)\r\n}\r\n\r\nA<-matrix(c(2,-1,-1,2),ncol=2)\r\nprint(\"For A\")\r\nsolution(A)\r\nA2<-A%*%A\r\nprint(\"For square of A\")\r\nsolution(A2)\r\nA1<-solve(A)\r\nprint(\"For inverse of A\")\r\nsolution(A1)\r\nI<-matrix(c(1,0,0,1),ncol=2)\r\nA4I<-A+4*I\r\nprint(\"For A+4I\")\r\nsolution(A4I)\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": "b7bf991a6851f1073e5425d9a7ee953703126d13", "size": 998, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.1.a/Ex6_6.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/CH6/EX6.1.a/Ex6_6.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/CH6/EX6.1.a/Ex6_6.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": 31.1875, "max_line_length": 99, "alphanum_fraction": 0.6713426854, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992932829918, "lm_q2_score": 0.9032941982430049, "lm_q1q2_score": 0.8742978161060312}}
{"text": "\t\t\t\t\tR07\r\n\r\n\t\t\t\tPrincipal Components Analysis\r\n\r\n\r\noptions(digits=4, scipen=3)\r\n\r\n# Eigenvalues and eigenvectors\r\n\r\nA <- matrix(sample(9), nrow=3)\r\nA\r\n\r\nA.e <- eigen(A)\r\nA.e\r\n\r\nA %*% A.e$vectors[,1]\r\nA.e$values[1] * A.e$vectors[,1]\r\n\r\nA %*% A.e$vectors[,2]\r\nA.e$values[2] * A.e$vectors[,2]\r\n\r\nA %*% A.e$vectors[,3]\r\nA.e$values[3] * A.e$vectors[,3]\r\n\r\n\r\n# PCA Example\r\n\r\nX <- as.matrix(read.table(\"H:/S5600/Data sets/ASCII/Ch04/PCA_EXAMPLE.txt\"))\r\n\r\napply(X, 2, mean)\r\napply(X, 2, sd)\t\t# already standardized\r\n\r\npairs(X)\r\n\r\nlibrary(rgl)\r\n\r\nrgl.open()\r\nbg3d(\"white\")\r\n\r\nrgl.spheres(X[,1],X[,2],X[,3],radius=.1, color=rainbow(300)[rank(X[,1])])\r\n\r\nX.cor <- cor(X)\r\nX.cor\r\n\r\nX.e <- eigen(X.cor)\r\n\r\nX.e\r\n\r\nX.svd <- svd(X.cor)\r\nX.svd\r\n\r\nU <- X.e$vectors\t# Get rotation matrix of eigenvectors\r\n\r\nzapsmall(t(U) %*% U)\r\n\r\nZ <- X %*% U\t\t# Rotated data matrix\r\n\r\npairs(Z)\r\nzapsmall(cor(Z))\r\n\r\nrgl.clear()\t\t# All three principal components\r\nrgl.spheres(Z[,1],Z[,2],Z[,3],radius=.1, color=rainbow(300)[rank(X[,1])])\r\n\r\nrgl.clear()\t\t# First two principal components\r\nrgl.spheres(Z[,1],Z[,2],rep(0,300),radius=.1, color=rainbow(300)[rank(X[,1])])\r\n\r\nrgl.clear()\t\t# First principal component\r\nrgl.spheres(Z[,1],rep(0,300),rep(0,300),radius=.1, color=rainbow(300)[rank(X[,1])])\r\n\r\n# Rotate back to X-space\r\n\r\nZ1 <- cbind(Z[,1], rep(0,300), rep(0,300))\r\nX1 <- Z1 %*% t(U)\r\n\r\nrgl.clear()\r\nrgl.spheres(X[,1],X[,2],X[,3],radius=.1, color=rainbow(300)[rank(X[,1])], alpha=.3)\r\n\t# Original data\r\nrgl.spheres(X1[,1],X1[,2],X1[,3],radius=.1, color=rainbow(300)[rank(X[,1])])\r\n\t# First PC\r\n\r\nZ2 <- cbind(rep(0,300), Z[,2], rep(0,300))\r\nX2 <- Z2 %*% t(U)\r\n\r\nrgl.spheres(X2[,1],X2[,2],X2[,3],radius=.1, color=rainbow(300)[rank(X[,1])])\r\n\t# Second PC\r\n\r\nZ3 <- cbind(rep(0,300),rep(0,300), Z[,3])\r\nX3 <- Z3 %*% t(U)\r\n\r\nrgl.spheres(X3[,1],X3[,2],X3[,3],radius=.1, color=rainbow(300)[rank(X[,1])])\r\n\t# Third PC\r\n\r\nZ12 <- cbind(Z[,1:2],rep(0, 300))\r\nX12 <- Z12 %*% t(U)\r\n\r\nrgl.clear()\r\nrgl.spheres(X[,1],X[,2],X[,3],radius=.1, color=rainbow(300)[rank(X[,1])], alpha=.3)\r\nrgl.spheres(X12[,1],X12[,2],X12[,3],radius=.1, color=rainbow(300)[rank(X[,1])])\r\n\t# First two PCs\r\n\r\n# Fractions of variance\r\n\r\nlambda <- X.e$values\t# Eigenvalues of cor(X) = variances of PCs\r\nlambda\r\n\r\nzapsmall(cov(Z))\r\n\r\nzapsmall(cor(Z))\r\n\r\ndiag(cov(Z))\r\nsum(diag(cov(Z)))\t# Note: sum = number of dimensions = sum of original correlations\r\n\r\n# The prcomp( ) function\r\n\r\nX.pc <- prcomp(X, scale=T)\r\nX.pc\r\n\r\nX.pc$rotation\t# Compare to U above - same except for possible sign reversal\r\n\r\nU\t\r\n\r\nX.pc$sdev\t# Component sds\r\nX.pc$sdev^2\t# Component Variances - compare to lambda above\r\nlambda\t\t\r\n\r\npairs(X.pc$x)\t# Same as Z above, again except for possible sign change\r\n\r\n\r\n# New example: State economic data\r\ndata(state)\r\n\r\ngsp.raw<-read.table(\"H:/S5600/GSP_RAW.txt\",header=T)\r\nrownames(gsp.raw) <- state.abb\r\npairs(gsp.raw)\r\nstars(gsp.raw, key.loc=c(15, 1.5))\r\ncor(gsp.raw)\t# Strong correlation\r\n\r\ngsp.raw.pc <- prcomp(gsp.raw, scale=T)\r\ngsp.raw.pc$sdev^2\t# Variances - almost everything in PC 1\r\n\r\ngsp.raw.pc$rotation[,1:2]\t# Loadings for PCs 1 and 2\r\n\t# Loadings for PC 1 almost all equal - simply a measure of economic size\r\n\r\n# COnvert each state's earnings into a percentage for each sector\r\n\r\ngsp.share <- gsp.raw/apply(gsp.raw, 1, sum)*100\r\n\r\npairs(gsp.share)\r\nstars(gsp.share, key.loc=c(15, 1.5))\r\ncor(gsp.share)\r\n\r\ngsp.share.pc <- prcomp(gsp.share, scale=T)\r\nzapsmall(gsp.share.pc$sdev^2)\t# Variances - much more balanced\r\n\r\npairs(gsp.share.pc$x[,1:6]) \t# First 6 PCs\r\nplot(gsp.share.pc$x[,1:2], pch=16)\t# First 2\r\n\t# identify outliers\r\nidentify(gsp.share.pc$x[,1], gsp.share.pc$x[,2], state.abb)\r\n\t# Or label all points\r\nplot(gsp.share.pc$x[,1:2], type='n')\r\ntext(gsp.share.pc$x[,1:2], state.abb)\r\n\r\n# Loadings - first 6 PCs\r\n\r\ngsp.share.pc$rotation[,1:6]\r\n\r\n# Values of some outliers in original units\r\n\r\ngsp.share[c(2,8,11,28,50),]\r\n\r\n# biplot - loadings on 1st 2 PCs and plot of first 2 PCs\r\n\r\nbiplot(gsp.share.pc)\r\n\r\n# How many components?\r\n\r\nplot(gsp.share.pc)\t# Scree plot\r\nplot(gsp.share.pc$sdev^2, type=\"o\", pch=16)\t# Alternate Version\r\n\r\nzapsmall(gsp.share.pc$sdev^2)\r\nsum(gsp.share.pc$sdev>1)\t# Kaiser's Rule - keep components with variance > 1\r\nabline(h=1,col=\"grey\")\r\n\r\nsummary(gsp.share.pc)\r\n\r\n# Horn's procedure - compare to randomly permuted (bootstrapped) data\r\n\r\ngsp.boot <- gsp.share\r\nfor (i in 1:13) {\r\n\tgsp.boot[,i] <- sample(gsp.share[,i], replace=T) }\r\ngsp.boot.pc <- prcomp(gsp.boot, scale=T)\r\npoints(gsp.boot.pc$sdev^2, type=\"o\")\t# Add to alternate scree plot; compare\r\n\t\t\t\t\t# Repeat; add different runs in different colors\r\n\r\n\r\n# Another example - planetary data\r\n\r\nplanets1<-read.table(\"H:/S5600/planets.txt\")\r\nplanets1\r\npairs(planets1)\r\n\r\n# Log transform values except rings (add one to number Moons)\r\n\r\nplanets <- cbind(logDist=log(planets1$Dist), logRadius = log(planets1$Radius), \r\n\tlogMass =log(planets1$Mass), logDensity=log(planets1$Density), \t\tlogMoons=log(planets1$Moons+1), Rings=unclass(planets1$Rings)-1) \t \r\nrownames(planets)<-rownames(planets1)\r\nplanets\r\npairs(planets)\r\n\r\nplanets.pc <- prcomp(planets, scale=T)\r\nplanets.pc$sdev^2\r\n\r\nplot(planets.pc$sdev^2, type=\"o\", pch=16)\r\nabline(h=1,col=\"grey\")\r\n\r\npairs(planets.pc$x)\r\nplot(planets.pc$x[,1:2], pch=16)\r\n\r\nidentify(planets.pc$x[,1], planets.pc$x[,2], rownames(planets))\r\n\t# Note the three clusters\r\n\r\nplanets.pc$rotation[,1:2]\r\n\r\nbiplot(planets.pc)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "657dd32848e7444a286029b04ca640751c7750d5", "size": 5395, "ext": "r", "lang": "R", "max_stars_repo_path": "code/r07.r", "max_stars_repo_name": "phewson/mvstats", "max_stars_repo_head_hexsha": "f39ab1c1b97c89e26c708bd6d532fe13c063a95c", "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": "code/r07.r", "max_issues_repo_name": "phewson/mvstats", "max_issues_repo_head_hexsha": "f39ab1c1b97c89e26c708bd6d532fe13c063a95c", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-08-28T16:37:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T16:49:11.000Z", "max_forks_repo_path": "code/r07.r", "max_forks_repo_name": "phewson/mvstats", "max_forks_repo_head_hexsha": "f39ab1c1b97c89e26c708bd6d532fe13c063a95c", "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": 23.6622807018, "max_line_length": 134, "alphanum_fraction": 0.6407784986, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.9219218327098193, "lm_q1q2_score": 0.8741243623771126}}
{"text": "## Linear algebra\n1:10\n\nx=seq(from=3.1, to=8.9, length.out=10)\nx[1]\nx[2]\n\nx.t=t( x ) # transpose of x\nlength(x.t)\nlength(x)\n\nx\nx.t\n\ny=x^2\ny\n\nx/y\ny-x*x\n\ndim(x %o% y) # outer product\n\nx%*%y # inner product\n\nsum(x*y)\n\n### Create a matrix with 2 rows and 3 columns\nM=matrix(0,2,3);\nM\n\nXmat1=matrix(x,2,5)\nXmat1\nXmat2=matrix(x,2,5,byrow=T)\nXmat2\n\nM<-Xmat1;\ndimnames(M)\n\nrownames(M)<-c(\"first\",\"second\")\nM\ncolnames(M)<-c('a','b','c','d','e')\nM\n\nidentical(M[,1],M[,'a'])\n\nidentical(M[2,],M['second',])\n\n\nM[,1:3]\nM[,c(\"a\",\"d\",\"e\")]\n\n\nM2=rbind(M, c(1,2,3,4,5))\nrownames(M2)[3]<-'third'\nM2\n?cbind\n\nlength(M)\ndim(M)\n\n\n### Operations on matrices\n\nM.t=t(M)\nM.t\nidentical(t(M.t),M)\n\n\n### Diagonal and identity matrix\ndiag(5) # identity matrix\ndiag(c(1,2,3,4,5)) # diagonal matrix\n\n\n### Symmetric matrix\ndim(M.t)\ndim(M)\n\nA=matrix(rnorm(9),3,3)\nidentical(A,t(A))\nA= A+t(A);\nidentical(A,t(A))\n# A is a symmetric matrix!\n\n### Trace of a matrix\n# ?tr()\ndiag(diag(c(1,2,3,4,5)))\n\nA\nsum(diag(A))\n### Create our own function to calculate the trace\ntr<-function(A){\n  # Need to check whether A is a squared matrix or not\n  out=sum(diag(A))\n  return(out)\n}\ntr(A)\n\n## Verify the properties of trace\nB=matrix(rnorm(9),3,3)\nB\nA\n\ntr(A)\ntr(t(A))\n\ntr(A+B)\ntr(A)+tr(B)\n\nA\nB\nA+B # A-B?\n\ntr(A%*%B)\ntr(B%*%A)\n\ntr(A)\nsum(eigen(A)$values)\n\n## Matrix product:\n\n## Matrix-vector product\ndim(M)\nxvec=rnorm(5)\nxvec\nM%*%xvec\n# M: 2 by 5 matrix\n# xvec: 5 by 1 vector (matrix)\n# (2 by 5) %*% (5 by 1)\n# 2 by 1\n\nxvec2=rnorm(7)\nM%*%xvec2\n\n\n### Matrix-matrix product\ndim(M)\n\nC<- matrix(rnorm(15),5,3)\nM%*%C # a 2 (by 5) by (5 by) 3 matrix\n\nM2<- matrix(rnorm(10),2,5)\n\nM*M2 # elementwise product between two matrices\ndim(M)\ndim(M2)\n\nM%*%M2\nM%*%t(M2)\n\nt(M%*%t(M2))\n\nM2%*%t(M)\n", "meta": {"hexsha": "17caabca435b5cc8baa52aba4a98946c67d18c28", "size": 1728, "ext": "r", "lang": "R", "max_stars_repo_path": "Scripts_lectures/Lecture_04062020.r", "max_stars_repo_name": "ChenShizhe/STA108_UCD", "max_stars_repo_head_hexsha": "3ee97392086f17efc9eee572d0ad686efe203166", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-05T22:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T22:59:39.000Z", "max_issues_repo_path": "Scripts_lectures/Lecture_04062020.r", "max_issues_repo_name": "ChenShizhe/STA108_UCD", "max_issues_repo_head_hexsha": "3ee97392086f17efc9eee572d0ad686efe203166", "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": "Scripts_lectures/Lecture_04062020.r", "max_forks_repo_name": "ChenShizhe/STA108_UCD", "max_forks_repo_head_hexsha": "3ee97392086f17efc9eee572d0ad686efe203166", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-04-13T19:11:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T15:40:22.000Z", "avg_line_length": 11.2941176471, "max_line_length": 54, "alphanum_fraction": 0.6041666667, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.9241418168448761, "lm_q1q2_score": 0.8740545056072075}}
{"text": "# Example : 5   Chapter : 4.4     Page No: 233\r\n# Gram-Schmidt method to convert matrix into its orthogonal form\r\nmagnitude<-function(a){\r\n  x<-0\r\n  for(i in 1:length(a)){\r\n    x<-x+a[i]*a[i]\r\n  }\r\n  x<-sqrt(x)\r\n  return(x)\r\n}\r\na<-c(1,-1,0)\r\nb<-c(2,0,-2)\r\nc<-c(3,-3,3)\r\nA<-a\r\nB<-b-(sum(A*b)/sum(A*A))*A \r\nC<-c-(sum(A*c)/sum(A*A))*A-(sum(B*c)/sum(B*B))*B\r\nprint(\"Orthogonal vectors corresponding to a,b,c are\")\r\nprint(A)\r\nprint(B)\r\nprint(C)\r\nq1<-(1/magnitude(A))*A\r\nq2<-(1/magnitude(B))*B\r\nq3<-(1/magnitude(C))*C\r\nQ<-matrix(c(q1,q2,q3),ncol=3)\r\nprint(\"Orthogonal matrix with orthonormal vectors of a,b,c \")\r\nprint(Q)\r\n#The  answer may slightly vary due to  rounding off values", "meta": {"hexsha": "f94e8c09555ba318b71561333bb676dced17f9aa", "size": 675, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.4.5/Ex4.4_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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.4.5/Ex4.4_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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.4.5/Ex4.4_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": 25.0, "max_line_length": 65, "alphanum_fraction": 0.6044444444, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446517423792, "lm_q2_score": 0.8947894569842487, "lm_q1q2_score": 0.8712069692281815}}
{"text": "#Stegarescu Ana-Maria 341\r\n\r\nlibrary(cubature)\r\nlibrary(pracma)\r\n\r\n#Ex4\r\n#Integrala dubla, de la 1 la 2, si de la 3 la 4\r\ng4 <- function(x, y){\r\n  x*y^2\r\n}\r\n\r\n#teta <- adaptIntegrate(g4, lowerLimit = c(1,3), upperLimit=c(2,4))$integral\r\n\r\nteta <- integral2(g4, 1, 2, 3, 4)$Q\r\n\r\nn <- 10^6\r\nx <- runif(n, 1, 2)\r\ny <- runif(n, 3, 4)\r\n\r\n\r\ng4U <- g4(x, y)\r\nteta_est <- sum(g4U)/n\r\n\r\n\r\n#Ex5\r\n#Integrala dubla de la 0 la Inf si de la 0 la x\r\ng5 <- function(x, y){\r\n  3*x*exp(-x-y)\r\n}\r\n\r\nteta <- integrate(function(x) {sapply(x, function(x) \r\n{integrate(function(y) 3*x*exp(-x-y), 0, x)$value})}, 0, Inf)$value\r\n\r\n\r\n#Schimbare de variabila, pentru x de la 0 la Inf, t va fi de la 0 la 1\r\n#x = t/(1-t)\r\n#t = x/(x-1)\r\n\r\n#dx = 1/(1+t)^2\r\n\r\ng5t <- function(t, y){\r\n  x <- t/(1-t)\r\n  g5(x, y)*1/(1-t)^2\r\n  \r\n}\r\n\r\nn <- 10^6\r\n\r\nt <- runif(n)\r\nmed_t <- sum(t)/n\r\ny <- runif(n, 0, t/(1-t))\r\n\r\ng5U <- g5t(t, y)\r\nteta_est <- sum(g5U * t/(1-t))/n\r\n\r\n\r\n#Caprita Catalin 341\r\n#1.\r\n# g(x) = 4 * x ^ 3 * exp(-x ^ 2 / 8) de integrat de la -Inf la Inf\r\n# f(x) = 1 / 2 * sqrt(2 * pi) * exp(-x ^ 2 / 8\r\n# h(x) = 4 * x ^ 3\r\nn <-  1e7\r\nX <- rnorm(n,0,2)\r\n\r\ng <- function(x){\r\n  4 * x ^ 3 * exp(-x ^ 2 / 8)S\r\n}\r\nh <- function(x){\r\n  4 * x ^ 3\r\n}\r\nteta_aprox <- 2 * sqrt(2 * pi) * sum(h(X)) / n\r\nteta <- integral(g,-Inf,Inf)\r\n#TEMA: Aceeasi problema pornind de la o Uniforma(Schimbare de variabila) \r\n#si Exponentiala\r\n\r\n#Memenduf Alen 341\r\nrequire(plotrix)\r\n\r\nn <- 10^4\r\nx <- runif(n, -1, 1)\r\ny <- runif(n, -1, 1)\r\n\r\n\r\n# asp => aspect ratio\r\nplot(x, y,asp = 1, col = ifelse(x^2 + y^2 < 1, 'white', 'gray'))\r\ndraw.circle(0, 0, 1, border = \"black\", lwd = 3)\r\n\r\n# Chirut Veronica\r\nN <- c()\r\nfor (i in 1:10 ^ 5) {\r\n  U <- c()\r\n  \r\n  sum <- 0\r\n  n <- 0\r\n  while(sum <= 1) {\r\n    U <- runif(1, 0, 1)\r\n    sum <- sum + U\r\n    n <- n + 1\r\n  }\r\n  \r\n  N <- append(N, n)\r\n}\r\n\r\ncovarianta <- function(x, y) {\r\n  mean(x * y) - mean(x) * mean(y)\r\n}\r\n\r\n# a\r\nE_N <- mean(N)\r\n\r\n# ASA NU!\r\n# Folosim Monte Carlo - Lab 3\r\nVar_N <- covarianta(N, N)\r\n\r\n# b\r\ncazuri_favorabile <- sum(N == 2)\r\ncazuri_posibile <- length(N)\r\n\r\nP_2 = cazuri_favorabile / cazuri_posibile\r\n\r\n# c\r\n# E(N) este o aproximare a numarului lui Euler", "meta": {"hexsha": "0de0d8c3b0793ca4bf754e85e3ba0c15955e17ff", "size": 2168, "ext": "r", "lang": "R", "max_stars_repo_path": "Tehnici de Simulare (TS)/Laborator/3/Laborator 3.r", "max_stars_repo_name": "DLarisa/FMI-Materials-BachelorDegree", "max_stars_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_stars_repo_licenses": ["W3C"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-12T02:05:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:44:43.000Z", "max_issues_repo_path": "Tehnici de Simulare (TS)/Laborator/3/Laborator 3.r", "max_issues_repo_name": "DLarisa/FMI-Materials-BachelorDegree-UniBuc", "max_issues_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_issues_repo_licenses": ["W3C"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tehnici de Simulare (TS)/Laborator/3/Laborator 3.r", "max_forks_repo_name": "DLarisa/FMI-Materials-BachelorDegree-UniBuc", "max_forks_repo_head_hexsha": "138e1a20bc33617772e9cd9e4432fbae99c0250c", "max_forks_repo_licenses": ["W3C"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7704918033, "max_line_length": 77, "alphanum_fraction": 0.5235239852, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.9032942080055512, "lm_q1q2_score": 0.8700805651283494}}
{"text": "# Exercises in section 2.10\n\n# import library and open dataset\nlibrary(dslabs)\ndata('murders')\n\n# 1. Use the $ operator to access the population size data and store it as the object pop. Then use the sort function to redefine pop so that it is sorted. Finally, use the [ operator to report the smallest population size.\n\npop <- murders$population\npop <- sort(pop)\npop[1]\n\n# 2. Now instead of the smallest population size, find the index of the entry with the smallest population size. Hint: use order instead of sort.\n\npop <- murders$population # reassign to original vector\nord <- order(pop)\nord[1]\npop[ord[1]]\n\n# 3. We can actually perform the same operation as in the previous exercise using the function which.min. Write one line of code that does this.\n\nindex_min = which.min(pop)\nindex_min\npop[which.min(pop)]\nindex_max = which.max(pop)\nindex_max\n\n# 4. Now we know how small the smallest state is and we know which row represents it. Which state is it? Define a variable states to be the state names from the murders data frame. Report the name of the state with the smallest population.\n\nstates <- murders$state\nstates[index_min]\nstates[index_max]\n\n# 5. Use the rank function to determine the population rank of each state from smallest population size to biggest. Save these ranks in an object called ranks, then create a data frame with the state name and its rank. Call the data frame my_df.\n\nranks <- rank(pop)\nmy_df = data.frame(state = states, rank = ranks)\nmy_df\n\n# 6. Repeat the previous exercise, but this time order my_df so that the states are ordered from least populous to most populous. Hint: create an object ind that stores the indexes needed to order the population values. Then use the bracket operator [ to re-order each column in the data frame.\n\nind = order(pop)\nmy_df = data.frame(state = states[ind], rank = ranks[ind])\nmy_df\n\n# 7. The na_example vector represents a series of counts. However, when we compute the average with the function mean, we obtain an NA. The is.na function returns a logical vector that tells us which entries are NA. Assign this logical vector to an object called ind and determine how many NAs does na_example have.\n\ndata('na_example')\nind <- is.na(na_example)\nlength(na_example[ind])\n#sum(ind) gives the same output\n\n# 8. Now compute the average again, but only for the entries that are not NA. Hint: remember the ! operator.\n\nmean(na_example[!ind])\n", "meta": {"hexsha": "7d96f4d750bbf1902e5b2cfd4e31ebd4abb39cb1", "size": 2408, "ext": "r", "lang": "R", "max_stars_repo_path": "edx/harvardx_ph125/chapter_02/02-10_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-10_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-10_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": 43.0, "max_line_length": 315, "alphanum_fraction": 0.7645348837, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.9196425339307879, "lm_q1q2_score": 0.8659852142147174}}
{"text": "library(tidyverse)\r\nlibrary(readr)\r\nlibrary(xts)\r\nlibrary(tseries)\r\nlibrary(astsa)\r\n\r\n####CHAPTER 3\r\n\r\n####ARIMA - Plug and Play####\r\nx <- arima.sim(model = list(order = c(1, 1, 0), \r\n                            ar = .9), n = 200)\r\n# Plot x\r\nplot(x)\r\n# Plot the P/ACF pair of x\r\nplot(acf2(x))\r\n# Plot the differenced data\r\nplot(diff(x))\r\n# Plot the P/ACF pair of the differenced data\r\nplot(acf2(diff(x)))\r\n####\r\n\r\n####Simulated ARIMA####\r\n# Plot sample P/ACF of differenced data and determine model\r\ny <- diff(x)\r\nplot(acf2(y))\r\n# Estimate parameters and examine output\r\nsarima(x,2,1,0)\r\n####\r\n\r\n####Global Warming####\r\n# Plot the sample P/ACF pair of the differenced data \r\nplot(acf2(diff(globtemp)))\r\n# Fit an ARIMA(1,1,1) model to globtemp\r\nsarima(globtemp, 1,1,1)\r\n# Fit an ARIMA(0,1,2) model to globtemp. Which model is better?\r\nsarima(globtemp, 0,1,2)\r\n#0,1,2\r\n####\r\n\r\n####Diagnostics - Simulated Overfitting####\r\n# Plot sample P/ACF pair of the differenced data\r\nplot(acf2(diff(x)))\r\n# Fit the first model, compare parameters, check diagnostics\r\nsarima(x, 0,1,1)\r\n# Fit the second model and compare fit\r\nsarima(x, 0,1,2)\r\n# As you can see from the t-table, the second MA parameter is not significantly \r\n# different from zero and the first MA parameter is approximately the same \r\n# in each run. Also, the AIC and BIC both increase when the parameter is added. \r\n# In addition, the residual analysis of your ARIMA(0,1,1) model is fine. \r\n# All of these facts together indicate that you have a successful model fit.\r\n####\r\n\r\n####Diagnostics - Global Temperatures####\r\n# Fit ARIMA(0,1,2) to globtemp and check diagnostics  \r\nsarima(globtemp, 0,1,2) #-3.58 , -4.51\r\n# Fit ARIMA(1,1,1) to globtemp and check diagnostics\r\nsarima(globtemp, 1,1,1) #-3.57 , -4.51\r\n# Which is the better model?\r\n# \"ARIMA(___,___,___)\"\r\n\"ARIMA(0,1,2)\"\r\n####\r\n\r\n####Forecasting Simulated ARIMA####\r\n# Plot P/ACF pair of differenced data \r\nplot(acf2(diff(x)))\r\n# Fit model - check t-table and diagnostics\r\nsarima(x, 1,1,0)\r\n# Forecast the data 20 time periods ahead\r\n# sarima.for(x, n.ahead = ___, p = ___, d = ___, q = ___) \r\nsarima.for(x, n.ahead =20, p = 1, d = 1, q = 0) \r\nlines(y)\r\n####\r\n\r\n####Forecasting Global Temperatures####\r\n# Fit an ARIMA(0,1,2) to globtemp and check the fit\r\nsarima(globtemp, 0,1,2)\r\n# Forecast data 35 years into the future\r\nsarima.for(globtemp, 35, 0,1,2)\r\n####\r\n\r\n####CHAPTER 4\r\n\r\n####Fit a Pure Seasonal Model####\r\n# Plot sample P/ACF to lag 60 and compare to the true values\r\nacf2(x, max.lag = 60)\r\n# Fit the seasonal model to x\r\n#sarima(x, p = 0, d = 0, q = 0, \r\n#       P = ___, D = 0, Q = ___, S = ___)\r\nsarima(x, p = 0, d = 0, q = 0, \r\n       P = 1, D = 0, Q = 1, \r\n       S = 12)\r\n####\r\n\r\n####Fit a Mixed Seasonal Model####\r\n# Plot sample P/ACF pair to lag 60 and compare to actual\r\nplot(acf2(x, max.lag=60))\r\n# Fit the seasonal model to x\r\nsarima(x, 0,0,1, 0,0,1, 12)\r\n####\r\n\r\n####Data Analysis - Unemployment I####\r\npar(mfrow = c(3,1))\r\n# Plot unemp \r\nplot(unemp)\r\n# Difference your data and plot it\r\nd_unemp <-diff(unemp)\r\nplot(d_unemp)\r\n# Seasonally difference d_unemp and plot it\r\n#dd_unemp <- diff(___, lag = 12)  \r\ndd_unemp <- diff(d_unemp, lag = 12) \r\nplot(dd_unemp)\r\n####\r\n\r\n####Data Analysis - Unemployment II####\r\n# Plot P/ACF pair of fully differenced data to lag 60\r\ndd_unemp <- diff(diff(unemp), lag = 12)\r\nplot(acf2(dd_unemp, max.lag=60))\r\n# Fit an appropriate model\r\nsarima(unemp, 2,1,0 , 0,1,1, 12)\r\n####\r\n\r\n####Data Analysis - Commodity Prices####\r\n# Plot differenced chicken\r\nchicken\r\nplot(diff(chicken))\r\n# Plot P/ACF pair of differenced data to lag 60\r\nplot(acf2(diff(chicken), max.lag=60))\r\n# Fit ARIMA(2,1,0) to chicken - not so good\r\nsarima(chicken, 2,1,0)\r\n# Fit SARIMA(2,1,0,1,0,0,12) to chicken - that works\r\nsarima(chicken, 2,1,0, 1,0,0, 12)\r\n####\r\n\r\n####Data Analysis - Birth Rate####\r\n# Plot P/ACF to lag 60 of differenced data\r\nd_birth <- diff(birth)\r\nplot(acf2(d_birth, max.lag=60))\r\n# Plot P/ACF to lag 60 of seasonal differenced data\r\ndd_birth <- diff(d_birth, lag = 12)\r\nplot(acf2(dd_birth, max.lag=60))\r\n# Fit SARIMA(0,1,1)x(0,1,1)_12. What happens?\r\nsarima(birth, 0,1,1, 0,1,1, 12)\r\n# Add AR term and conclude\r\nsarima(birth, 1,1,1, 0,1,1, 12)\r\n####\r\n\r\n####Forecasting Monthly Unemployment####\r\n# Fit your previous model to unemp and check the diagnostics\r\nsarima(unemp, 2,1,0, 0,1,1, 12)\r\n# Forecast the data 3 years into the future\r\nsarima.for(unemp,n.ahead = 3*12, 2,1,0, \r\n           P=0,D=1,Q=1, \r\n           S=12)\r\n####\r\n\r\n####How Hard is it to Forecast Commodity Prices?####\r\n# Fit the chicken model again and check diagnostics\r\nsarima(chicken, 2,1,0, 1,0,0, 12)\r\n# Forecast the chicken data 5 years into the future\r\nsarima.for(chicken, n.ahead=5*12, 2,1,0, 1,0,0, 12)\r\n####", "meta": {"hexsha": "b14fb97532db58e4aaebbb4133d0eca3c61dce4c", "size": 4736, "ext": "r", "lang": "R", "max_stars_repo_path": "Time_Series_with_R_Track/3_ARIMA_Modeling_with_R/ARIMA_Modeling_with_R_03-04.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/3_ARIMA_Modeling_with_R/ARIMA_Modeling_with_R_03-04.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/3_ARIMA_Modeling_with_R/ARIMA_Modeling_with_R_03-04.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": 29.2345679012, "max_line_length": 81, "alphanum_fraction": 0.6418918919, "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452772, "lm_q2_score": 0.9032941988938413, "lm_q1q2_score": 0.8635324100951665}}
{"text": "# Inverse of a matrix\nset.seed(1)\nA=matrix(rnorm(9),3,3)\nB=matrix(rnorm(9),3,3)\n# Pseudorandomness\n\ndim(A)\n\nA.inv =solve(A)\nA.inv\n\nA.inv %*% A\nmat.tmp=A%*%A.inv\nmat.tmp[2,3]==0\nabs(mat.tmp[2,3])< 1e-10\n\nAB.inv = solve(A%*%B)\nB.inv=solve(B);\n\nidentical(AB.inv,B.inv%*%A.inv)\nAB.inv-B.inv%*%A.inv\nmax(abs( AB.inv-B.inv%*%A.inv))<1e-10\n\n# AB.inv satisfies that\n# AB%*%AB.inv = I\n# AB=A%*%B\n#  AB%*%(B.inv)%*%(A.inv)\n# = A%*%B%*%(B.inv)%*%(A.inv)\n# = A%*% (B%*%B.inv)%*%(A.inv)\n# = A%*%I%*%A.inv\n# = A%*%A.inv = I\n\nset.seed(1)\nX=matrix(rnorm(6),3,2)\n\nP=X%*%solve(t(X)%*%X)%*%t(X)\n\nP%*%P%*%P%*%P%*%P-P\n(diag(3)-P)%*%P\n\nP%*%X-X\n(diag(3)-P)%*%X\n\n\ndim(P)\ndim(X)\ndim(P%*%X)\nP%*%t(X)\n\n# Rank of a matrix\nqr(X)$rank\ndim(X)\n\n#\nXXt=X%*%t(X)\nqr(XXt)$rank\ndim(XXt) # Not full rank!\n\nsolve(XXt)\n\n# Determinant of a matrix\ndet(A)\n1/det(solve(A))\ndet(A%*%B)\ndet(A)*det(B)\n\ndet(2*A)/det(A)\n2^3\n\ntr<-function(A){\n  # Need to check whether A is a squared matrix or not\n  out=sum(diag(A))\n  return(out)\n}\ntr(A)\n\nA.symm= (A+t(A))/2;\nidentical(A.symm,t(A.symm))\n\nsum(eigen(A.symm)$values)\ntr(A.symm)\n\ndet(A.symm)\nprod(eigen(A.symm)$values)\n\n# Eigenvalue and eigenvector\nA.symm.eigenvalues = eigen(A.symm)$values\nA.symm.eigenvectors = eigen(A.symm)$vectors\n\n(A.symm%*%A.symm.eigenvectors[,1])/A.symm.eigenvectors[,1]\nA.symm.eigenvalues[1]\n\n\neigen(XXt)\nqr(XXt)$rank\n\neigen(P)\n\n# Data set\nlibrary(AER)\n\n#install.package('AER')\n\ndata('Fatalities')\n?Fatalities\n\ndata('CreditCard')\n?CreditCard\n\nhead(CreditCard)\n\ndat.CC=CreditCard;\nY.CC=dat.CC[,1]=='yes';\nX.CC=as.matrix(dat.CC[,c('reports','age','income','share','expenditure','dependents','months','majorcards','active')])\n\n\nqr(X.CC)$rank\ndim(X.CC) # Full rank, i.e., no multicolinearity!\n\n\nfit.CC=lm(Y.CC~X.CC-1)\nsummary(fit.CC)\n\nbeta.hat=solve(t(X.CC)%*%X.CC)%*%t(X.CC)%*%Y.CC;\nfit.CC$coefficients-beta.hat\n\nP.CC=X.CC%*%solve(t(X.CC)%*%X.CC)%*%t(X.CC)\n\nYhat.CC=P.CC%*%Y.CC\nmax(abs(fit.CC$fitted.values-Yhat.CC))\n\n\n\n", "meta": {"hexsha": "2fa26042c53ca97e483a752add0c4043abb36270", "size": 1939, "ext": "r", "lang": "R", "max_stars_repo_path": "Scripts_lectures/Lecture_04082020.r", "max_stars_repo_name": "ChenShizhe/STA108_UCD", "max_stars_repo_head_hexsha": "3ee97392086f17efc9eee572d0ad686efe203166", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-05T22:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T22:59:39.000Z", "max_issues_repo_path": "Scripts_lectures/Lecture_04082020.r", "max_issues_repo_name": "ChenShizhe/STA108_UCD", "max_issues_repo_head_hexsha": "3ee97392086f17efc9eee572d0ad686efe203166", "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": "Scripts_lectures/Lecture_04082020.r", "max_forks_repo_name": "ChenShizhe/STA108_UCD", "max_forks_repo_head_hexsha": "3ee97392086f17efc9eee572d0ad686efe203166", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-04-13T19:11:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T15:40:22.000Z", "avg_line_length": 14.4701492537, "max_line_length": 118, "alphanum_fraction": 0.6137184116, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041521, "lm_q2_score": 0.900529795461386, "lm_q1q2_score": 0.8631917824305941}}
{"text": "notestreak=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  temp=diff(c(0,which(song==1),length(song)+1))-1\n  streak_lengths=subset(temp,temp>0)\n\n  # About these commands:\n  # which(song==1) returns a vector indicating which on which notes (indices) a miss occurs\n  #                this is important for you because it will indicate the end of a streak\n  # c(0,which(song==1),length(song)+1) creates a vector starting with 0 (indicates the beginning of the song),\n  #                 then the locations of misses, and then the length of the song + 1 (indicates when the song has ended)\n  # diff(above vector) calculates the difference between consecutive entries in this vector; we don't actually care about \n  #\t\t\t the locations of the misses but how many hits occur between misses; we start the process of finding this \n  #\t\t\t by finding the difference between consecutive indices in the vector (note that this is not the length of\n  #\t\t\t the streak, but actually the length + 1, which is why the last part of the first line subtracts 1); the \n  #\t\t\t resulting lengths are stored in \"temp\"\n\n\n  m = median(streak_lengths)\n  return (m)\n\n}\n\n# Hypothesis test based on the note streak method\nnotestreak_test = function(song,B=1000){\n    # song is a vector of 0's and 1's that represents the hits (0) \n\t# and misses (1) of the notes in order\n\t# B is the number of new samples to generate\n\t\n\ttest_stat = notestreak(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] = notestreak(song_tmp)\n\t}\n\t\n\t# calculate the two-sided p-value from the sampling distribution\n\tpval = 2*min(sum(tstar_b >= test_stat),sum(tstar_b <= test_stat))/B\n\t\t# calculate a one sided p-value\n#\tpval = sum(tstar_b >= test_stat)/B\n\treturn(pval)\n}\n\n\n# Examples using Songs A and B from Table 1\n\nsongA = c(1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0)\nnotestreak(songA)\nnotestreak_test(songA,5000)\n\n\nsongB = c(0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,0,0)\nnotestreak(songB)\nnotestreak_test(songB,5000)\n", "meta": {"hexsha": "d9d369400c1d6268349d8348fe2aba2c17a03b32", "size": 2233, "ext": "r", "lang": "R", "max_stars_repo_path": "GHSupplementaryFiles/AppendixC/median_streak.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/median_streak.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/median_streak.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.8474576271, "max_line_length": 122, "alphanum_fraction": 0.7044334975, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203816, "lm_q2_score": 0.8933094010836642, "lm_q1q2_score": 0.8619141811997287}}
{"text": "## 1. The Range ##\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()))\nlibrary(dplyr)\n\nsale_price_range <- houses %>%\n    group_by(`Yr Sold`) %>%\n    summarize(range_by_year = max(SalePrice) - min(SalePrice))\n\none  <-  FALSE\ntwo  <-  TRUE\n\n## 2. The Average Distance ##\n\nC  <-  c(1,1,1,1,1,1,1,1,1,21)\naverage_distance <- function(vector) {\n    distances  <-  vector - mean(vector)\n    sum(distances) / length(distances)\n}\n\navg_distance  <-  average_distance(C)\n\n## 3. Mean Absolute Deviation ##\n\nC  <-  c(1,1,1,1,1,1,1,1,1,21)\n\n#average_distance <- function(vector) {\n#    distances  <-  vector - mean(vector)\n#    sum(distances) / length(distances)\n#}\nmean_absolute_deviation <- function(vector) {\n    distances  <-  abs(vector - mean(vector)) #we only add abs function here\n    sum(distances) / length(distances)\n}\n\nmad  <-  mean_absolute_deviation(C)\n\n## 4. Variance ##\n\nC  <-  c(1,1,1,1,1,1,1,1,1,21)\n\n#mean_absolute_deviation <- function(vector) {\n#    distances  <-  abs(vector - mean(vector))\n#    sum(distances) / length(distances)\n#}\nvariance <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n    sum(distances) / length(distances)\n}\n\nvariance_C  <-  variance(C)\n\n## 5. Standard Deviation ##\n\nC  <-  c(1,1,1,1,1,1,1,1,1,21)\n\n#variance <- function(vector) {\n#    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n#    sum(distances) / length(distances)\n#}\nstandard_deviation <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 \n    sqrt(sum(distances) / length(distances)) #adding sqrt at this line\n}\n\nstandard_deviation_C  <-  standard_deviation(C)\n\n## 6. Average Variability Around the Mean ##\n\nlibrary(dplyr)\n\nstandard_deviation <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n    sqrt(sum(distances) / length(distances))\n}\n# Measure first the variability for each year\nhouses_years_std <- houses %>%\n    group_by(`Yr Sold`) %>%\n    summarize(st_dev = standard_deviation(SalePrice)) %>%\n    arrange(st_dev)\n\n# Get years of max and min variability\ngreatest_variability  <-  houses_years_std %>%\n  filter(st_dev == max(st_dev)) %>% \n  pull(`Yr Sold`)\n\nlowest_variability  <-  houses_years_std %>%\n  filter(st_dev == min(st_dev)) %>% \n  pull(`Yr Sold`)\n\n## 7. A Measure of Spread ##\n\nset.seed(10)\n\nsample1  <-  sample(x = houses$`Year Built`, size = 50)\nsample2  <-  sample(x = houses$`Year Built`, size = 50)\n\nstandard_deviation <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n    sqrt(sum(distances) / length(distances))\n}\nbigger_spread  <-  'sample 2'\nst_dev1  <-  standard_deviation(sample1)\nst_dev2  <-  standard_deviation(sample2)\n\n## 8. The Sample Standard Deviation ##\n\nstandard_deviation <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n    sqrt(sum(distances) / length(distances))\n}\n\nlibrary(ggplot2)\nset.seed(1)\nstd_points  <-  replicate(n = 5000, expr = standard_deviation(sample(x = houses$SalePrice, size = 10)))\n\nstd_points_tibble <- tibble::tibble(std_points)\n\nggplot(data = std_points_tibble, aes(x = std_points)) +\n    geom_histogram(bins = 10, position = \"identity\") +\n    geom_vline(aes(xintercept = standard_deviation(houses$SalePrice))) +\n    xlab(\"Sample standard deviation\") + \n    ylab(\"Frequency\")\n\n## 10. Bessel's Correction ##\n\nstandard_deviation <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n    sqrt(sum(distances) / length(distances))\n}\n\nlibrary(ggplot2)\nset.seed(1)\n\nstd_points  <-  replicate(n = 5000, expr = standard_deviation(sample(x = houses$SalePrice, size = 10)))\n\n#ggplot(data = tibble::tibble(std_points), aes(x = std_points)) +\n#    geom_histogram(bins = 10, position = \"identity\") +\n#    geom_vline(aes(xintercept = standard_deviation(houses$SalePrice))) +\n#    xlab(\"Sample standard deviation\") + \n#    ylab(\"Frequency\")\n\npopulation_stdev  <-  standard_deviation(houses$SalePrice)\nstandard_deviation_bessel_correction <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 \n    sqrt(sum(distances) / (length(distances) - 1) ) #Only this line has to change\n}\n\nlibrary(ggplot2)\nset.seed(1)\n\nstd_points  <-  replicate(n = 5000, expr = standard_deviation_bessel_correction(sample(x = houses$SalePrice, size = 10)))\n\nstd_points_tibble <- tibble::tibble(std_points)\n\nggplot(data = std_points_tibble, aes(x = std_points)) +\n    geom_histogram(bins = 10, position = \"identity\") +\n    geom_vline(aes(xintercept = population_stdev)) +\n    xlab(\"Sample standard deviation\") + \n    ylab(\"Frequency\")\n\n## 11. Standard Notation ##\n\nset.seed(1)\n\nsample_sales  <-  sample(x=houses$SalePrice, size=100)\n\nvariance_bessel_correction <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n    sum(distances) / (length(distances) - 1)\n}\n\nstandard_deviation_bessel_correction <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n    sqrt(sum(distances) / (length(distances)-1) )\n}\ncomputed_stdev  <-  standard_deviation_bessel_correction(sample_sales)\nstdev_r  <-  sd(sample_sales)\nequal_stdevs  <-  computed_stdev == stdev_r\n\ncomputed_var  <-  variance_bessel_correction(sample_sales)\nvar_r  <-  var(sample_sales)\nequal_vars  <-  computed_var == var_r\n\n## 12. Sample Variance \u2014 Unbiased Estimator ##\n\npopulation  <-  c(0, 3, 6)\n\nsamples  <-  list(c(0,3), c(0,6),\n               c(3,0), c(3,6),\n               c(6,0), c(6,3)\n)\n\nvariance <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n    sum(distances) / length(distances)\n}\n\nstandard_deviation <- function(vector) {\n    distances  <-  (vector - mean(vector))**2 #we only need to compute the squared distances here\n    sqrt(sum(distances) / length(distances) )\n}\npopulation_var  <-  variance(population)\npopulation_std  <-  standard_deviation(population)\n\nst_devs  <-  purrr::map_dbl(samples,sd)\nvariances  <-  purrr::map_dbl(samples,var)\n\nmean_std  <-  mean(st_devs)\nmean_var  <-  mean(variances)\n\nequal_stdev  <-  population_std == mean_std\nequal_var  <-  population_var == mean_var", "meta": {"hexsha": "7f99fcd573f63a723de8d3ca70630443b485d028", "size": 6777, "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/4. Measures of Variability.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/4. Measures of Variability.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/4. Measures of Variability.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": 31.2304147465, "max_line_length": 121, "alphanum_fraction": 0.6901283754, "num_tokens": 1898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.90192067652954, "lm_q1q2_score": 0.8616220803746246}}
{"text": "#integrate is a function from package stats which is included in R by default\r\n#if not install package stats\r\n# Example : 2   Chapter : 8.5     Page No: 448\r\n# length of function sinx and sinx and cosx are orthogonal in function space\r\nf1<-function(x){\r\n  return (sin(x)*sin(x))\r\n}\r\nf2<-function(x){\r\n  return (sin(x)*cos(x))\r\n}\r\nprint(\"Inner product of sinx and sinx is \")\r\nlsin2x<-integrate(f1,0,2*pi)\r\nprint(lsin2x)\r\nprint(\"Length of sinx is square root of above inner product\")\r\nprint(sqrt(lsin2x$value))\r\nprint(\"Cos x and sinx are orthogonal in functional space because their inner product equals zero\")\r\nlsinxcosx<-integrate(f2,0,2*pi)\r\nprint(lsinxcosx)\r\n#The  answer may slightly vary due to  rounding off values", "meta": {"hexsha": "634de0d93b3a52d10f5b39b8ae4d133ec03afb5a", "size": 719, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.5.2/Ex8.5_2.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.5.2/Ex8.5_2.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.5.2/Ex8.5_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": 37.8421052632, "max_line_length": 99, "alphanum_fraction": 0.7246175243, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138170582865, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.8595539511037799}}
{"text": "# Example : 5.3B   Chapter : 5.3     Page No: 278\r\n# Solve by crammers rule and inverse of the matrix\r\n\r\nsolve_by_crammersrule<-function(A,b){\r\n  B1<-A\r\n  B2<-A\r\n  B3<-A\r\n  B1[,1]<-b\r\n  B2[,2]<-b\r\n  B3[,3]<-b\r\n  x1<-det(B1)/det(A)\r\n  x2<-det(B2)/det(A)\r\n  x3<-det(B3)/det(A)\r\n  x<-c(x1,x2,x3)\r\n  return(x)\r\n}\r\ninverse<-function(A){\r\n  C<-matrix(c(1:9),ncol=3)\r\n  for(i in 1:3){\r\n    for(j in 1:3){\r\n      if((i+j)%%2==0){\r\n        x<-1\r\n      }\r\n      else{\r\n        x<--1\r\n      }\r\n      C[i,j]<-x*det(A[-i,-j])\r\n    }\r\n  }\r\n  CT<-t(C)\r\n  A1<-(1/det(A))*CT\r\n  return(A1)\r\n}\r\n\r\nA<-matrix(c(2,1,5,6,4,9,2,2,0),ncol=3)\r\nb<-c(0,0,1)\r\nx<-solve_by_crammersrule(A,b)\r\nprint(\"x is \")\r\nprint(x)\r\nA1<-inverse(A)\r\nprint(\"Inverse of A is \")\r\nprint(A1)\r\nprint(\"A * inverse of A is Identity matrix\")\r\nI<-A%*%A1\r\nprint(I)\r\n#The  answer may slightly vary due to  rounding off values", "meta": {"hexsha": "2dfb1feb9662e2d5695c5cf31a32225af6247e6d", "size": 867, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH5/EX5.3.b/Ex5_5.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/CH5/EX5.3.b/Ex5_5.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/CH5/EX5.3.b/Ex5_5.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": 18.847826087, "max_line_length": 58, "alphanum_fraction": 0.5155709343, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971992474526142, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8592795186490991}}
{"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 : 6.2B   Chapter : 6.2     Page No: 306\r\n# Inverse Eigen values Determinant and eigen vector matrix\r\nlibrary(pracma)\r\nA<-5*eye(4)-ones(4)\r\neigenvalues<-eigen(A)$values\r\nprint(\"Eigen Values of A \")\r\nprint(eigenvalues)\r\nA1<-solve(A)\r\nprint(\"Inverse of A \")\r\nprint(A1)\r\neigenvalues1<-eigen(A1)$value\r\nprint(\"Eigen Values of A inverse \")\r\nprint(eigenvalues1)\r\ndetA<-det(A)\r\nprint(\"Determinant of A\")\r\nprint(detA)\r\nx<-eigen(A)$vectors[,4] #normalized  eigen vector of eigen value=1\r\n#toget eigen vector in text book\r\nx<-x*(1/x[1])\r\nprint(\"Eigen vector of A for eigen value 1\")\r\nprint(x)\r\nprint(\"The other eigen vectors are perpendicular to x since A is Symmetric so eigen vector matrix contains x with different signs as follows\")\r\nS<-matrix(c(1,-1,1,-1,1,1,-1,-1,1,-1,-1,1,x),ncol=4)\r\nprint(S)\r\nprint(\"To get normalized matrix multiply by magnitude of vectors which is same for all and is 0.5\")\r\nS<-0.5*S\r\nprint(S) # The eigen vectors are with respect to 5,5,5,1", "meta": {"hexsha": "991d615aada009430808fee0ce8028c0663ac285", "size": 1267, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.2.b/Ex6_6.2B.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.b/Ex6_6.2B.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.b/Ex6_6.2B.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": 38.3939393939, "max_line_length": 143, "alphanum_fraction": 0.7166535122, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535094, "lm_q2_score": 0.8962513828326955, "lm_q1q2_score": 0.8579615542040017}}
{"text": "library(data.table)\nlibrary(ggplot2)\nlibrary(gtools)\n\ndata.dir <- \"D:/Project/Statistical-Computing/datasets/\"\n\n### Beer/Wings Consumption\n\nBeerwings <- data.table(read.csv(paste0(data.dir, \"Beerwings.csv\"),\n                                 header = T))\n\nwith(Beerwings, {\n  tapply(Hotwings, Gender, mean)\n})\n\nobserved <- 14.5333 - 9.3333 # store observed mean difference\n\nhotwings <- Beerwings$Hotwings\n\nN <- 10^5 - 1\n\nresult <- numeric(N)\n\nfor( i in 1:N)\n{ #sample of size 15, from 1 to 30, without replacement\n  index <- sample(30, size = 15, replace = F)\n  result[i] <- mean(hotwings[index]) - mean(hotwings[-index])\n}\n\nggplot(data.table(result), aes(result)) +\n  geom_histogram(aes(fill = ..count..)) +\n  geom_vline(xintercept = observed, col = \"darkorange\", linetype = 3, lwd = 1.3) +\n  scale_y_continuous(labels = comma) +\n  labs(title = \"Beer/Wings Resampling\")\n\np <- (sum(result >= observed) + 1) / (N + 1) # p-value\nv <- p*(1 - p) / N # variance of the samples\n\n### Verizon Repair Times\n\nVerizon <- data.table(read.csv(paste0(data.dir, \"Verizon.csv\"),\n                                 header = T))\n\nwith(Verizon, {\n  tapply(Time, Group, mean)\n})\n\nTime.CLEC <- Verizon[Group == \"CLEC\"]$Time\nTime.ILEC <- Verizon[Group == \"ILEC\"]$Time\nTime <- c(Time.CLEC, Time.ILEC)\n\nobserved <- mean(Time.ILEC) - mean(Time.CLEC) # store the observed mean difference\n\nN <- 10e4 - 1\n\nresult <- numeric(N)\n\nsample.size <- length(Time.ILEC) + length(Time.CLEC)\n\nfor( i in 1:N)\n{\n  index <- sample(sample.size, length(Time.ILEC), replace = F)\n  result[i] <- mean(Time[index]) - mean(Time[-index])\n}\n\nggplot(data.table(result), aes(result)) +\n  geom_histogram(aes(fill = ..count..)) +\n  geom_vline(xintercept = observed, col = \"darkorange\", linetype = 3, lwd = 1.3) +\n  scale_y_continuous(labels = comma) +\n  labs(title = \"Verizon Repair Times - Resampling\")\n\np <- ( sum(result <= observed) + 1 ) / ( N + 1 ) # p-value\np * 100\n\nv <- p*(1 - p) / N # variance of p\n\n### Verizon, Median\n\nwith(Verizon, {\n  tapply(Time, Group, median)\n})\n\nobserved <- median(Time.ILEC) - median(Time.CLEC)\n\nN <- 10e4 - 1\n\nresult <- numeric(N)\nsample.size <- length(Time.ILEC) + length(Time.CLEC)\n\nfor( i in 1:N)\n{\n  index <- sample(sample.size, length(Time.ILEC), replace = F)\n  result[i] <- median(Time[index]) - median(Time[-index])\n}\n\nggplot(data.table(result), aes(result)) +\n  geom_histogram(aes(fill = ..count..)) +\n  geom_vline(xintercept = observed, col = \"darkorange\", linetype = 3, lwd = 1.3) +\n  scale_y_continuous(labels = comma) +\n  labs(title = \"Verizon Repair Times - Resampling\")\n\np <- ( sum( result <= observed ) + 1) / ( N + 1)\np * 100\nv <- p*(1 - p)/N\n\n### Verizon, Trimmed Mean\n\nwith(Verizon, {\n  tapply(Time, Group, function(x) { mean(x, trim = .25)})\n})\n\nobserved <- mean(Time.ILEC, trim = .25) - mean(Time.CLEC, trim = .25)\n\nN <- 10e4 - 1\n\nresult <- numeric(N)\nsample.size <- length(Time.ILEC) + length(Time.CLEC)\n\nfor( i in 1:N)\n{\n  index <- sample(sample.size, length(Time.ILEC), replace = F)\n  result[i] <- mean(Time[index], trim = .25) - mean(Time[-index], trim = .25)\n}\n\nggplot(data.table(result), aes(result)) +\n  geom_histogram(aes(fill = ..count..)) +\n  geom_vline(xintercept = observed, col = \"darkorange\", linetype = 3, lwd = 1.3) +\n  scale_y_continuous(labels = comma) +\n  labs(title = \"Verizon Repair Times - Resampling\")\n\np <- ( sum( result <= observed ) + 1) / ( N + 1)\np * 100\nv <- p*(1 - p)/N\n\n### Verizon, repair time differences\n\nobserved <- mean(Time.ILEC > 10) - mean(Time.CLEC > 10)\nobserved\n\nN <- 10e4 - 1\n\nresult <- numeric(N)\nsample.size <- length(Time.ILEC) + length(Time.CLEC)\n\nfor( i in 1:N)\n{\n  index <- sample(sample.size, length(Time.ILEC), replace = F)\n  result[i] <- mean(Time[index] > 10) - mean(Time[-index] > 10)\n}\n\nggplot(data.table(result), aes(result)) +\n  geom_histogram(aes(fill = ..count..)) +\n  geom_vline(xintercept = observed, col = \"darkorange\", linetype = 3, lwd = 1.3) +\n  scale_y_continuous(labels = comma) +\n  labs(title = \"Verizon Repair Times - Resampling\")\n\np <- ( sum( result <= observed ) + 1) / ( N + 1)\np * 100\nv <- p*(1 - p)/N\n\n### Verizon, repair time varances\n\nobserved <- var(Time.ILEC) - var(Time.CLEC)\nobserved\n\nN <- 10e4 - 1\n\nresult <- numeric(N)\nsample.size <- length(Time.ILEC) + length(Time.CLEC)\n\nfor( i in 1:N)\n{\n  index <- sample(sample.size, length(Time.ILEC), replace = F)\n  result[i] <- var(Time[index]) - var(Time[-index])\n}\n\nggplot(data.table(result), aes(result)) +\n  geom_histogram(aes(fill = ..count..)) +\n  geom_vline(xintercept = observed, col = \"darkorange\", linetype = 3, lwd = 1.3) +\n  scale_y_continuous(labels = comma) +\n  labs(title = \"Verizon Repair Times - Resampling\")\n\np <- ( sum( result <= observed ) + 1) / ( N + 1)\np * 100\nv <- p*(1 - p)/N\n\n### Recidivism Data\n\nRecid <- data.table(read.csv(paste0(data.dir, \"Recidivism.csv\"),\n                             header = T))\n\nk <- complete.cases(Recid$Age25)\n\nRecid2 <- Recid[k]\nRecid2[, .(Recid = sum(Recid == \"Yes\"), Pct = sum(Recid == \"Yes\") / .N), by = Age25]\n\nobserved <- .365 - 0.306\nN <- 10e4 - 1\n\nresult <- numeric(N)\n\nRecidR <- ifelse(Recid2$Recid == \"Yes\", 1, 0)\n\nfor(i in 1:N)\n{\n  index <- sample(nrow(Recid2), 3077, replace = F)\n  result[i] <- mean(RecidR[index]) - mean(RecidR[-index]) \n}\n\n2 * (sum(result >= observed) + 1) / (N + 1)\n\n### Diving Scores\n\nDiving <- data.table(read.csv(paste0(data.dir, \"Diving2017.csv\"),\n                              header = T))\n\nDiff <- Diving$Final - Diving$Semifinal # Difference in two scores\nobserved <- mean(Diff)                  # mean of differences \n\nN <- 10e5-1\nresult <- numeric(N)\n\nfor(i in 1:N)\n{\n  Sign <- sample(c(-1,1), 12, replace = T) # Random vector of 1's or -1's\n  Diff2 <- Sign*Diff # random pairs (a-b) -> (b-a)\n  result[i] <- mean(Diff2)\n}\n\nggplot(data.table(result), aes(result)) +\n  geom_histogram(aes(fill = ..count..)) +\n  geom_vline(xintercept = observed, col = \"darkorange\", linetype = 3, lwd = 1.3) +\n  scale_y_continuous(labels = comma) +\n  labs(title = \"Diving Times - Resampling\")\n\np <- 2 * (sum(result >= observed + 1)) / (N + 1)\nv <- p*(1 - p) / N\n\n# Table 3.1\n\ndrug.t <- c(30, 25, 20)\ndrug.c <- c(18, 21, 22)\n\nchoose(6, 3)\n\ndrug <- c(drug.t, drug.c)\n\ntreatment <- combinations(n = 6, r = 3, drug, repeats.allowed = F)\n\ncontrol <- matrix(nrow = 20, ncol = 3)\nfor( i in 1:nrow(c))\n{\n  control[i,] <- drug[!drug %in% treatment[i,]]\n}\ncontrol\n\nperms <- data.table(cbind(treatment, control))\n\nstopifnot(nrow(perms) == choose(6, 3))\n\ncolnames(perms) <- c(\"D1\", \"D2\", \"D3\", \"C1\", \"C2\", \"C3\")\n\nperms$Xd <- (perms$D1 + perms$D2 + perms$D3) / 3\nperms$Xc <- (perms$C1 + perms$C2 + perms$C3) / 3\nperms$Diff <- round(perms$Xd - perms$Xc, 2)\n\nperms[Diff >= 4.67]\n\n", "meta": {"hexsha": "294a490df2792b8db39228b5bab60a6a4b9b460c", "size": 6660, "ext": "r", "lang": "R", "max_stars_repo_path": "Mathematical Statistics/03_permutation_testing.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/03_permutation_testing.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/03_permutation_testing.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": 24.7583643123, "max_line_length": 84, "alphanum_fraction": 0.6154654655, "num_tokens": 2188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.9086178913651383, "lm_q1q2_score": 0.8571424870354399}}
{"text": "# Example : 6.3B   Chapter : 6.3     Page No: 322\r\n# Eigen Values and Eigen vectors of A\r\nA<-matrix(c(-2,1,0,1,-2,1,0,1,-2),ncol=3)\r\neigenvalues<-eigen(A)$values\r\nx<-eigen(A)$vectors\r\nprint(\"Eigen values of A are \")\r\nprint(eigenvalues)\r\nprint(\"Eigen vectors of A in normalised form\")\r\nprint(x)\r\n#to get eigen vectors in the textbook multiply normalised vectors by scalars\r\nx[,1]<-x[,1]*(1/x[1,1])\r\nx[,2]<-x[,2]*(1/x[1,2])\r\nx[,3]<-x[,3]*(1/x[1,3])\r\nprint(\"Eigen vectors with respect to the above eigen values respectively are\")\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": "30f54de1c6dd7c9d3deaa24f4518a6f4a819e1e9", "size": 782, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.3.b/Ex6_6.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/CH6/EX6.3.b/Ex6_6.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/CH6/EX6.3.b/Ex6_6.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": 41.1578947368, "max_line_length": 99, "alphanum_fraction": 0.689258312, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8962513648201267, "lm_q1q2_score": 0.8567995875549229}}
{"text": "# fit multiple regression in R\r\n\r\nbrain <- read.table('brain.txt',as.is=T, header=T)\r\n\r\nbrain$loggest <- log(brain$gest)\r\nbrain$logbrain <- log(brain$brain)\r\nbrain$logbody <- log(brain$body)\r\nbrain$loglitter <- log(brain$litter)\r\n\r\nbrain.lm <- lm(logbrain ~ logbody + loglitter + loggest, data=brain)\r\n\r\nsummary(brain.lm)\r\n# print out coefficients, se's, individual tests, and other info\r\n\r\n# need to use explicit model comparison to construct F tests\r\n\r\nbrain.lm2 <- lm(logbrain ~ logbody  + loggest, data=brain)\r\n # model with loglitter = 0\r\n\r\nanova(brain.lm2,brain.lm)\r\n # gives F test of loglitter = 0\r\n\r\n# can also get F test for each term using drop1()\r\ndrop1(brain.lm, .~., test='F')\r\n\r\nbrain.lm3 <- lm(logbrain ~ logbody, data=brain)\r\n # model with log gest= 0 and loglitter = 0\r\nanova(brain.lm3,brain.lm)\r\n\r\n\r\nbrain$littgest <- brain$loglitter - brain$loggest\r\nbrain.lm4 <- lm(logbrain ~ logbody + littgest, data=brain)\r\n # model with loglitter + loggest = 0\r\n # reasoning behind littgest described in lecture\r\n\r\nanova(brain.lm4,brain.lm)\r\n\r\n# to test loggest + loglitter = 1, need to expand prev. approach\r\n#  substituting the constraint and simplifying, you see you need\r\n#  Y = logbrain - loggest\r\n\r\nbrain$braingest <- brain$logbrain - brain$loggest\r\nbrain.lm5 <- lm(braingest ~ logbody + littgest, data=brain)\r\n\r\n# can't use anova() because Y has changed.\r\n#  could compare error SS by hand\r\n\r\n# can fit desired model, keeping logbrain as response by \r\n#  specifying loggest as an offset (a fixed constant)\r\n\r\nbrain.lm5 <- lm(logbrain ~ logbody + littgest, offset = loggest, data=brain)\r\nanova(brain.lm5)\r\n\r\n# same as SAS test3 from proc reg.\r\n\r\n# N.B. if H0 was something like loggest + loglitter = 2, would need\r\n#  compute a new variable with 2*loggest, can not specify a formula\r\n#  as an offset\r\n\r\n\r\n# residuals from lm()\r\n#  obtained as before\r\n\r\nbrain.resid <- resid(brain.lm)\r\n\r\n# to get lag residuals, use appropriate indexing\r\nn <- length(brain.resid)\r\n\r\nplot(brain.resid[1:(n-1)], brain.resid[2:n])\r\n# index deletion is a bit shorter but more opaque\r\n# plot(brain.resid[-n], brain.resid[-1])\r\n\r\n# can get just the lag-1 correlation\r\ncor(brain.resid[-n], brain.resid[-1])\r\n\r\n# or a bunch of  lag correlations, \r\n#  what is called an autocorrelation function\r\nacf(brain.resid)\r\n\r\n\r\n\r\n# demonstration of partial regression \r\nbrain.plm1 <- lm(logbrain~logbody + loglitter, data=brain)\r\nbrain.plm2 <- lm(loggest~logbody + loglitter, data=brain)\r\n\r\nbrain.plm3 <- lm(resid(brain.plm1) ~ -1 + resid(brain.plm2) )\r\n\r\nsummary(brain.plm3)\r\n", "meta": {"hexsha": "7bdf0634c5055b45b5474d154c18d075f8ff503f", "size": 2553, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/brain.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)/brain.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)/brain.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6853932584, "max_line_length": 77, "alphanum_fraction": 0.6956521739, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422255326288, "lm_q2_score": 0.9005297947939936, "lm_q1q2_score": 0.8565319131788006}}
{"text": "mle <- function(x) max(x) # W1\nunbiased <- function(x) mle(x) * (n+1)/(n) # W2, unbiased\nmoments <- function(x) 2*mean(x)\nf_M <- function(t) n/theta * (t/theta)^(n-1) \nf_M <- Vectorize(f_M)\n#\n\ntheta <- pi^2/6\nn <- 10\nM <- 10000\n###########\n\ndata.sets <- matrix(runif(n = n*M, min = 0, max = theta), ncol = n, nrow = M)\n\n##### MLE\nW1 <- apply(data.sets, 1, mle)\nhist(W1, probability = TRUE)\nmean(W1)\nn/(n+1) * theta ## the actual E[W1]\nvar(W1)\nc <- n/(n+1)\n( VarW1 <- (n/(n+2) - c^2)*theta^2   )\n( MSE1 <- mean((theta-W1)^2) )\n(2/((n+1)*(n+2)))*theta^2 ## true MSE1\n\n##### Unbiased\n\nW2 <- apply(data.sets, 1, unbiased)\nhist(W2, probability = TRUE)\nmean(W2)\ntheta ## the actual E[W2]\nvar(W2)\n( VarW2 <- (1/(n*(n+2)))*theta^2   )\n( MSE2 <- mean((theta-W2)^2) )\n\n##### \n\nW3 <- apply(data.sets, 1, moments)\nhist(W3, probability = TRUE)\nmean(W3)\ntheta ## the actual E[W2]\nvar(W3)\n( VarW3 <- theta^2/(3*n)   )\n( MSE3 <- mean((theta-W3)^2) )\n\n###\n\nMSE1\nMSE2\nMSE3\n\n", "meta": {"hexsha": "2598b0a86102f3fd89fa2370f445c3364c4f1ec7", "size": 956, "ext": "r", "lang": "R", "max_stars_repo_path": "code/estimadores_uniforme_0_theta.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_0_theta.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_0_theta.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.3846153846, "max_line_length": 77, "alphanum_fraction": 0.5554393305, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812299938006, "lm_q2_score": 0.8840392893839085, "lm_q1q2_score": 0.8560870544164347}}
{"text": "# Example : 6.1B   Chapter : 6.1     Page No: 292\r\n# Eigen values and eigen vectors\r\nsolution<-function(A){\r\n  sol<-eigen(A)\r\n  lambda<-round(sol$values)\r\n  x<-sol$vectors #these are normalised eigen vectors\r\n  #to get eigen vectors in text book multiply normalised eigen vectors with scalars\r\n  x[,1]<-x[,1]*(1/x[1,1])\r\n  x[,2]<-round(x[,2]*(1/x[1,2]))\r\n  x[,3]<-x[,3]*(1/x[1,3])\r\n  print(\"The eigen values of the matrix are\")\r\n  print(lambda)\r\n  print(\"The eigen vectors of the matrix respective to above eigen values are\")\r\n  print(x)\r\n}\r\n\r\nA<-matrix(c(1,-1,0,-1,2,-1,0,-1,1),ncol=3)\r\nsolution(A)\r\n#The  answer may slightly vary due to  rounding off values\r\n", "meta": {"hexsha": "f2c11521d1da2649c9ea7767ffe4fb9b9da1c11f", "size": 661, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.1.b/Ex6_6.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/CH6/EX6.1.b/Ex6_6.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/CH6/EX6.1.b/Ex6_6.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": 33.05, "max_line_length": 84, "alphanum_fraction": 0.6459909228, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799399736477, "lm_q2_score": 0.8872045832787205, "lm_q1q2_score": 0.8550699800167104}}
{"text": "library(invgamma)\n\ncomputa_emv <- function(x){\n  1/mean(x)\n}\nalpha_emv <- function(x, c){\n exp(-c*x)\n}\n\ntheta0 <- 2\ncc <- 1\nalpha.vdd <- exp(-cc*theta0)\nM <- 10000\nn <- 100\n\namostras <- matrix(NA, ncol = n, nrow = M)\nfor (j in 1:M){\n  amostras[j, ] <- rexp(n = n, rate = theta0)\n}\n\n### Estimating theta\nEMVs <- apply(amostras, 1, computa_emv)\n\nmean(EMVs)\nn/(n-1) * theta0\n\ntheo_eqm <- function(n, theta){\n  theta^2 * (n^2+ n -2)/((n-1)^2*(n-2))\n}\nmean((EMVs-theta0)^2)\ntheo_eqm(n = n, theta = theta0)\n\n\nvar(EMVs)\n(mean(EMVs)-theta0)^2\n1/(n * theta0^2)\n\nhist(EMVs, probability = TRUE)  \nabline(v = theta0, lwd = 2, lty = 2)\ncurve(invgamma::dinvgamma(x, shape = n, rate = n*theta0),\n      min(EMVs), max(EMVs), add = TRUE, lwd = 2)\n\n## Estimating of alpha\nalpha.EMVs <- sapply(EMVs, alpha_emv, c = cc)\nhist(alpha.EMVs)\nabline(v = alpha.vdd, lwd = 2, lty = 2)\n\nmean((alpha.EMVs-alpha.vdd)^2)\nvar(alpha.EMVs)\n(mean(alpha.EMVs)-alpha.vdd)^2\n\n(alpha.vdd * log(alpha.vdd)^2)/(n *cc)\n", "meta": {"hexsha": "fbb53b007420077f2297c82b2b07fdc1a86e86f0", "size": 976, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Q_2_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_2_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_2_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": 18.4150943396, "max_line_length": 57, "alphanum_fraction": 0.6147540984, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.8947894724152068, "lm_q1q2_score": 0.8548095046299253}}
{"text": "#unsupervised learning \n\n## Dimension reduction with pca \ndata(\"iris\")\nX = iris[,-5]\nY = as.numeric(iris$Species)\n\ninstall.packages(\"class\")\nlibrary(class)\n\nY = predict(pca)[,1:2]\n# rhis is equivalent to these actions:\nU = pca$loadings[,1:2]\ndim(U)\nY = as.matrix(X) %*% U\ndim(Y)\n\nX[1,]\nY[1,]\n\nplot(Y,col=cls)\n\n# another example of PCA with decathlon data\n\n#let's first load data from internet:\n\ndecathlon = read.table(\"http://math.agrocampus-ouest.fr/infoglueDeliverLive/digitalAssets/108286_decathlon.csv\",header=TRUE,sep=';')\n\ndim(decathlon)\n\n# let's now focus on athlete's performance data\nX = decathlon[,2:11] # we focus on the data that is related to competitions\nrownames(X) = decathlon$X\n\n#exercise: perform a PCA and visualize the data in 2-dimentional space and \n#identify the most performant athlets.\n\npca = princomp(X)\nbiplot(pca)\n\n# we can guess that Serble or Clay are the most performant athlets \nY=predict(pca)[,1:2]\n\n#coordinates of the 1st individual in the original space (X)\nX[1,]\n\n# coordinates of the 1st individual in the projection space (Y = X*U)\nY[1,]\n\nplot(Y, type='n')\n\ntext(Y, labels = rownames(X))\n\n\n\n#selection of the numbers of axes to retrain\n# one of the rules is to retrain the nb of axes s.t. the percentage of explained\n#variance is larger than 90%\n\nsummary(pca)\n\n#here 2 PCA components is enough to explain 93% of the variance \n#the other rule is to look for a break in the eigenvalue scree:\n\nscreeplot(pca)\n# on this example perhaps we would prefer $d=3$.\n\n#############\n\n#Kmeans and hierarchical clustering \n#In order to highlight the main feautures of kmeans and HC, let's consider the \n# 'swiss' data\ndata(swiss)\n?swiss\n#let's first try to apply HC on this data. A general call to HC in R can be done\n#as follows:\nlibrary(class)\n?hclust()\n\nD = dist(swiss)\nhc = hclust(D, method = \"complete\")\nplot(hc)\n#remark: we observe here that 'hclust' can be applied to any type of data\n# if we are able to compute the distance for this data. Conversly, kmeans is mostly \n#restricted to continuous data due to the need to compute centers\n\nhc_centroid = hclust(D, method = \"centroid\")\nplot(hc_centroid)\n\nhc_ward = hclust(D, method = \"ward.D\")\nplot(hc_ward)\n\n#remark: we can see here that the different methods lead to quite different \n#dendogram, leading in turn to different choices of numbers of clusters\n\n#let's remember that clustering aims to help the analyst to understand data. \n#The choice of a method should be done according to this idea.\n\ncl4 = cutree(hc_ward, k=2)\ncl4\n\nplot(swiss,col=cl4,pch=19)\n\nclcompl = cutree(hc, k=2)\nclcompl\nplot(swiss,col=clcompl, pch=19)\n\nclcentroid = cutree(hc_centroid, k=2)\nclcentroid\nplot(swiss,col=clcentroid,pch=19)\n\n\n\n# Kmeans\n\n# let's have a look at the same data with Kmeans\n\n?kmeans\n#a basic call to kmeans would be \n\n\ndata(swiss)\nout = kmeans(swiss, centers =2)\nout\n\n#ex: write a short script that plot the curve of J(k) for the dataset at hand\n\nJ = rep(NA, 15)\nfor (k in 1:15){\n  out = kmeans(swiss, centers=k)\n  J[k] = out$betweenss/out$totss\n  }\nplot(J, type='b')\n\n#we observe on this small script that the curve can change with different initialization\n#and we can even observe some non-increasing curves for 'unlucky' initialization \n# a way to avoid this init effect we can average on several runs for each value of k\n\nJ = matrix(NA, 10, 15)\nfor (k in 1:15){\n  for(l in 1:10){\n    out = kmeans(swiss, centers=k)\n    J[l,k] = out$betweenss/out$totss\n  }\n}\nboxplot(J,type='b')\n\n# on this example I'd probably pick $k^*=5$ as the most appropriate nb of clusters\n#ex: visualize the clustering result with a pair plot, and compare to the one \n#obtained with hclust\n\nout5 = kmeans(swiss, centers= 5, nstart =10)\nplot(swiss, col=out5$cluster,pch=19)\n\n# The GMM and the EM algorithm\n\n# we use 'mclust' packsge:\ninstall.packages(\"mclust\")\nlibrary(mclust)\n\n#the help of the pkg is available as usual:\n?Mclust\n# a basic call can be performed as follows:\ndata(swiss)\nout_m = Mclust(swiss, G =3)\nout_m\n\nsummary(out_m)\n\nout_m$parameters\n\nout_m$classification\n\n\n\n", "meta": {"hexsha": "8d9a2afab1a04f141f2197c9f59973b59e51c391", "size": 4031, "ext": "r", "lang": "R", "max_stars_repo_path": "GMM kmeans and hclust.r", "max_stars_repo_name": "milxss/R_and_stats", "max_stars_repo_head_hexsha": "67e6f7842e6a22adef636a0891f8681fc646b816", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GMM kmeans and hclust.r", "max_issues_repo_name": "milxss/R_and_stats", "max_issues_repo_head_hexsha": "67e6f7842e6a22adef636a0891f8681fc646b816", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GMM kmeans and hclust.r", "max_forks_repo_name": "milxss/R_and_stats", "max_forks_repo_head_hexsha": "67e6f7842e6a22adef636a0891f8681fc646b816", "max_forks_repo_licenses": ["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.9034090909, "max_line_length": 132, "alphanum_fraction": 0.7258744728, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.9196425245706047, "lm_q1q2_score": 0.8547529211976487}}
{"text": "\n#  Artificial Intelligence for Humans\n## Volume 1: Fundamental Algorithms\n## R Version\n## http://www.aifh.org\n## http://www.jeffheaton.com\n##\n## Code repository:\n## https://github.com/jeffheaton/aifh\n##\n## Copyright 2013 by Jeff Heaton\n##\n## Licensed under the Apache License, Version 2.0 (the \"License\");\n## you may not use this file except in compliance with the License.\n## You may obtain a copy of the License at\n##\n##     http://www.apache.org/licenses/LICENSE-2.0\n##\n## Unless required by applicable law or agreed to in writing, software\n## distributed under the License is distributed on an \"AS IS\" BASIS,\n## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n## See the License for the specific language governing permissions and\n## limitations under the License.\n##\n## For more information on Heaton Research copyrights, licenses\n## and trademarks visit:\n## http://www.heatonresearch.com/copyright\n\n## Chapter 4 Example: Inscribed Circle \n## \n## This example shows how random numbers can be used to estimate pi \n## using random sampling (Monte Carlo method)\n##\n## Area of a circle = pi/(r^2)\n## Area of a square = (2r)^2\n## circle/square = (pi/(r^2))/(2r)^2 = pi/4\n\nestimate_pi <- function(samples, r){\n\ttries <- 0\n\tsuccesses <- 0\n\tfor (i in 1:samples){\n\n\t\t# pick a point randomly\t\n\t\tx = r*runif(1)\n\t\ty = r*runif(1)\n\t\ttries <- tries + 1\n\t\t# check if point is in the circle\n\t\tif (x*x + y*y <= r*r){\n\t\t\tsuccesses <- successes + 1\n\t\t}\n\t}\t\n\tpi_est <- 4*successes/tries\n\treturn(pi_est)\n}\n\n## After a million samples, Monte Carlo comes pretty close!\n## Returns: 3.144756 (but will be different unless seed is the same)\nprint(estimate_pi(1000000,4))\n\n\n", "meta": {"hexsha": "55a86d557a17197200fbec8ed9548a7ca8ee32d0", "size": 1677, "ext": "r", "lang": "R", "max_stars_repo_path": "vol1/r-examples/ch4/inscribed_circle.r", "max_stars_repo_name": "Sun-Joong/aifh", "max_stars_repo_head_hexsha": "1b6363d26f54b77348020ce88ced0670568ed736", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 777, "max_stars_repo_stars_event_min_datetime": "2015-01-17T22:48:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:10:07.000Z", "max_issues_repo_path": "vol1/r-examples/ch4/inscribed_circle.r", "max_issues_repo_name": "Sun-Joong/aifh", "max_issues_repo_head_hexsha": "1b6363d26f54b77348020ce88ced0670568ed736", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-01-02T14:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-02T02:57:09.000Z", "max_forks_repo_path": "vol1/r-examples/ch4/inscribed_circle.r", "max_forks_repo_name": "Sun-Joong/aifh", "max_forks_repo_head_hexsha": "1b6363d26f54b77348020ce88ced0670568ed736", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 445, "max_forks_repo_forks_event_min_datetime": "2015-01-26T17:01:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T07:16:58.000Z", "avg_line_length": 27.4918032787, "max_line_length": 75, "alphanum_fraction": 0.6964818128, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.9073122288794595, "lm_q1q2_score": 0.854374335673851}}
{"text": "##########  Function to calculate the Bootstrapped Distribuition  ##########\r\n\r\nnew.boot = function(data,func.name,R)\r\n{\r\n  t = numeric(R)\r\n  n = length(data)\r\n  for(i in 1:R)\r\n  {\r\n    indices = sample(1:n,n,replace=T)\r\n    t[i] = func.name(data,indices)\r\n  }\r\n  t0 = func.name(data,1:n)\r\n  weights = numeric(n)\r\n  for(i in 1:n)\r\n  {\r\n    weights[i] = 1/n\r\n  }\r\n  print(paste0(\"ORDINARY NONPARAMETRIC BOOTSTRAP\"))\r\n  print(paste0(\"Original: \",(t0)))\r\n  print(paste0(\"Bias: \",format(round((mean(t)-t0),4))))\r\n  print(paste0(\"Std. error: \",format(round((sd(t)),4))))\r\n  return(list(t0=t0,t=t,R=R,data=data,statistic=func.name,weights=weights))\r\n}\r\n\r\n##########  Function to find the Confidence Intervels  ##########\r\n\r\nnew.boot.ci = function(x)\r\n{\r\n  conf = 0.95\r\n  alpha = 1 - conf\r\n  N = c(x[[1]]-(mean(x[[2]])-x[[1]])-qnorm(1-(alpha/2))*sd(x[[2]]), \r\n        x[[1]]-(mean(x[[2]])-x[[1]])-qnorm((alpha/2))*sd(x[[2]]))\r\n  l = ((x[[3]]+1)*(alpha/2))\r\n  u = ((x[[3]]+1)*(1-(alpha/2)))\r\n  P = sort(x[[2]])[c(l,u)]\r\n  B = c(2*x[[1]]-sort(x[[2]])[c(u)],2*x[[1]]-sort(x[[2]])[c(l)])\r\n  print(paste0(\"Normal approximation: (\",format(round(N[1],4)),\"  \",format(round(N[2],4)),\")\"))\r\n  print(paste0(\"Basic approximation: (\",B[1],\"  \",B[2],\")\"))\r\n  print(paste0(\"Percentile approximation: (\",P[1],\"  \",P[2],\")\"))\r\n  return(list(R=x[[3]],t0=x[[1]],Normal=(N),Basic=(B),Percentile=(P)))\r\n}\r\n\r\n########## Function to calculate the 90-th percentile of a samlpe data ##########\r\n\r\nninty.npar = function(x,indices)\r\n{\r\n  result = quantile(x[indices],prob=0.90,type=1)\r\n  return(result)\r\n}\r\n\r\n# To compute the 90-th percentile from the draws\r\n# First we load the given data and store it into variable\r\ncpu = scan(file=\"cputime.txt\")\r\n\r\n# we call the new.boot function that gives the bootstrap draws with \r\n#           bias and standard deviation of the draws\r\nninty.npar.boot = new.boot(cpu, ninty.npar, 999)\r\n\r\n# to get the confidence intervals of the draws call the new.boot.ci function\r\n#       with the result stored in 'ninty.npar.boot' variable\r\nconf = new.boot.ci(ninty.npar.boot)", "meta": {"hexsha": "6abb173aa95bbc4c6b3add83f817157c52c69d70", "size": 2070, "ext": "r", "lang": "R", "max_stars_repo_path": "Mini-project-4/bootstrap.r", "max_stars_repo_name": "dheerajgoudb/Statistical-methods-in-Data-Science", "max_stars_repo_head_hexsha": "30d914083c7c31bc71e6dabe129465f4dc9142ee", "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": "Mini-project-4/bootstrap.r", "max_issues_repo_name": "dheerajgoudb/Statistical-methods-in-Data-Science", "max_issues_repo_head_hexsha": "30d914083c7c31bc71e6dabe129465f4dc9142ee", "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": "Mini-project-4/bootstrap.r", "max_forks_repo_name": "dheerajgoudb/Statistical-methods-in-Data-Science", "max_forks_repo_head_hexsha": "30d914083c7c31bc71e6dabe129465f4dc9142ee", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9344262295, "max_line_length": 96, "alphanum_fraction": 0.584057971, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8991213786215105, "lm_q1q2_score": 0.8538680282920219}}
{"text": "xbar <- 8.307849\ns2bar <- 7.930452 ## 1/n * Delta^2; Delta^2 = sum((x-xbar)^2)\nn <- 1000\n\ngama <- .95\ncc <- qt(p = (1  + gama)/2,\n         df = n-1) ## inv_cdf_T_{n-1}((1 + gamma)/2)\nsigma.prime <- sqrt(n*s2bar/(n-1))\nd <- cc * sigma.prime/sqrt(n)\n\na <- xbar - d\nb <- xbar + d\n\nc(a, b)\nc(xbar, a, b)\n\n### Supondo que sigma \u00e9 conhecida\ntruesd <- 2\n\n# (xbar - mu)/sqrt(sigma^2/n) ~ N(0, 1)\n\n# Pr( -k < Z < k) = gamma\n# Pr( xbar - k*sigma/sqrt(n) < mu < xbar + k*sigma/sqrt(n)) = gamma\n\n# a > 0\n# 2*Phi(k)-1 = gamma => a = Phi_inv((1+gamma)/2)\n\nk <- qnorm(p = (1  + gama)/2, mean = 0, sd = 1)\n\nd2 <- k*truesd/sqrt(n)\na2 <- xbar - d2\nb2 <- xbar + d2\n\nc(xbar, a, b)\nc(xbar, a2, b2)\n\n# Fun\u00e7\u00e3o poder\n\nmu0 <- 7\n\npoder_pamonha <- function(mu){\n  x <- sqrt(n) * (mu0 + cc - mu)/truesd\n  y <- sqrt(n) * (mu0 - cc - mu)/truesd\n  res <- pnorm(x, mean = 0, sd = 1,\n               lower.tail = FALSE) +\n    pnorm(y, mean = 0, sd = 1)\n  return(res)\n}\npoder_pamonha <- Vectorize(poder_pamonha)\n\ncurve(poder_pamonha, 0, 14,\n      xlab = expression(mu),\n      ylab = expression(pi(mu*\"|\"*delta)), lwd = 3)\nabline(v = mu0, lty = 2, lwd = 2)\n\n### Testando hip\u00f3teses (APG)\n#### Unilateral\n## H0: mu >= 7\n## H1: mu < 7\n### U > c => reijeito H0\n### U < c => n\u00e3o rejeito H0\n# X ~n(mu0, sigma^2)\nU <- (sqrt(n) * (xbar-mu0))/sigma.prime\n## Se H0 = vdd ent\u00e3o U ~ T(n-1)\n( p.valor <- pt(q = U, df = n-1) ) ## T^{-1}(U; n-1)\n\n## install.packages(\"BSDA\")\nBSDA::tsum.test(mean.x = xbar,\n                s.x = sigma.prime,\n                n.x = n,  mu = mu0,\n                alternative = \"less\")\n\nBSDA::tsum.test(mean.x = xbar,\n                s.x = sigma.prime,\n                n.x = n,  mu = mu0)  \n", "meta": {"hexsha": "eed21dd671f277f19ce2164a39c7a53dd297023b", "size": 1669, "ext": "r", "lang": "R", "max_stars_repo_path": "code/IC_da_palmirinha.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_da_palmirinha.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_da_palmirinha.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.9605263158, "max_line_length": 67, "alphanum_fraction": 0.5074895147, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561694652216, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.8517667634313855}}
{"text": "# Group members (Name, Student ID, E-Mail):\n# 1. Baldomero Valdez,  Valenzuela, 2905175, baldmer.w@gmail.com\n# 2. Omar Trinidad Gutierrez Mendez, 2850441, omar.vpa@gmail.com\n# 3. Shinho Kang, 2890169, wis.shinho.kang@gmail.com\n\n#=========================================\n# TASK 1\n#=========================================\nsample.mean <- 4\nsample.sd <- 0.7\nn <- 5\n\n# a) Compute the standard error of the mean\nse <- sample.sd / sqrt(n)\n# => se : 0.3130495\n\n# b) Compute the 95% confidence interval\n# 2.5% quantile of t-distribution with df n-1\nt.qt <- qt(0.025, n-1)\ninterval <- c(sample.mean + se*t.qt, sample.mean - se*t.qt)\nsize <- interval[2] - interval[1]\n# => interval: [3.130835, 4.869165]\n# => size: [1.73833]\n\n# c) half the size of the confidence interval\nn2 <- 12 # or 13\nse2 <- sample.sd / sqrt(n2)\nt.qt2 <- qt(0.025, n2-1)\ninterval2 <- c(sample.mean + se2*t.qt2, sample.mean - se2*t.qt2)\nsize2 <- interval2[2] - interval2[1]\n# => interval2: [3.555241, 4.444759]\n# => size2: 0.8895176 (when n=12)\n# => size2: 0.8460115 (when n=13)\n", "meta": {"hexsha": "5d4b5083eef539e654553eb49c8379649a782b7b", "size": 1041, "ext": "r", "lang": "R", "max_stars_repo_path": "Ex4/Ex4_1.r", "max_stars_repo_name": "omartrinidad/ml_bioinformatics", "max_stars_repo_head_hexsha": "2ff4962767a9cfe206620f1fc870839e249dde96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ex4/Ex4_1.r", "max_issues_repo_name": "omartrinidad/ml_bioinformatics", "max_issues_repo_head_hexsha": "2ff4962767a9cfe206620f1fc870839e249dde96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ex4/Ex4_1.r", "max_forks_repo_name": "omartrinidad/ml_bioinformatics", "max_forks_repo_head_hexsha": "2ff4962767a9cfe206620f1fc870839e249dde96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-15T02:23:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-15T02:23:47.000Z", "avg_line_length": 30.6176470588, "max_line_length": 64, "alphanum_fraction": 0.6023054755, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692345869641, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.8502855694094595}}
