summaryrefslogtreecommitdiff
path: root/simulate_grade_hours.R
diff options
context:
space:
mode:
Diffstat (limited to 'simulate_grade_hours.R')
-rw-r--r--simulate_grade_hours.R30
1 files changed, 30 insertions, 0 deletions
diff --git a/simulate_grade_hours.R b/simulate_grade_hours.R
new file mode 100644
index 0000000..d9c21f8
--- /dev/null
+++ b/simulate_grade_hours.R
@@ -0,0 +1,30 @@
+# 某门课程的成绩与每周学习小时数关系举例(1)线性关系(2)非线性关系
+# 蓝珲 2018年3月6日
+
+# 定义函数
+bound_data <- function(x, low, high) {
+ y <- pmin(pmax(x, rep(low, length(x))), rep(high, length(x)))
+}
+
+linear_relationship <- function(x, a, b) {
+ epsilon <- 10 + 7 * rnorm(length(x))
+ y <- a + b * x + epsilon
+ y <- bound_data(y, 0, 100) # make sure grades not lower than 0 nor higher than 100
+}
+
+nonlinear_relationship <- function(x) {
+ epsilon <- 10 + 7 * rnorm(length(x))
+ y <- -1.0 * (x - 10)^2 + 80 + epsilon # sometime extra effort means learning difficulty in this course
+ y <- bound_data(y, 0, 100)
+}
+
+# 主程序
+N <- 30 # number of students
+hours <- sample(0:20, N, replace=T) # weekly hours of study
+grade <- linear_relationship(hours, 20, 3)
+plot(hours, grade, xlab='每周学习小时数', ylab='成绩', main='线性关系')
+
+grade.2 <- nonlinear_relationship(hours)
+plot(hours, grade.2, xlab='每周学习小时数', ylab='成绩', main='非线性关系')
+
+