蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

验证函数返回、参数和内置工具

R基础 R。已在项目独立的 Windows x64 R 4.6.2 环境验证。functions.R
functions.R56 行
emit <- function(key, values) {
  cat(key, "=", paste(values, collapse = ","), "\n", sep = "")
}
combine <- function(x, y) {
  result <- x + y
  return(result)
}
attr(combine, "purpose") <- "total"
emit("definition", c(combine(12, 5), is.function(combine), attr(combine, "purpose"),
                    length(formals(combine)), typeof(environment(combine))))

squares <- function(n) {
  stopifnot(length(n) == 1L, is.finite(n), n >= 0, n == floor(n))
  for (step in seq_len(n)) cat(step ^ 2, "\n")
}
without_parameters <- function() squares(3L)
emit("squares", c(trimws(capture.output(squares(4L))), length(capture.output(squares(0L)))))
emit("no_args", trimws(capture.output(without_parameters())))
last_expression <- function(x) x ^ 2
as_value <- withVisible(last_expression(5L))
printed <- function(x) {
  cat(x, "\n")
}
written <- capture.output(value <- withVisible(printed(5L)))
emit("return", c(as_value$value, as_value$visible, trimws(written), is.null(value$value),
                value$visible))

score <- function(a, b, c) a*b+c
scaled <- function(value = 4, multiplier = 7) value*multiplier
join_words <- function(..., sep = "-") paste(..., sep = sep)
emit("arguments", c(score(4,2,3), score(c = 3, b = 2, a = 4), scaled(), scaled(2), scaled(multiplier=5),
                    join_words("ridge", "north", sep = "/")))

unused <- function(x) 17L
force_late <- function(x, y) {
  cat("square", x ^ 2, "\n")
  cat("input", x, "\n")
  y
}
trace <- capture.output(caught <- tryCatch(force_late(4L), error = function(e) conditionMessage(e)))
base <- 10
vary <- function(x, shift = base) {
  base <- 4
  x + shift
}
emit("lazy", c(unused(), unused(stop("unused")), vary(2), vary(2, base)))
emit("missing", c(trimws(trace), grepl("missing", caught, fixed = TRUE)))

samples <- c(2, 5, 8)
field <- matrix(1:6, nrow = 2)
emit("builtins", c(seq(11,15), sum(samples), sum(field), mean(samples), mean(field),
                  max(samples), length(samples), length(field), paste("Lake", "station")))
overview <- c(capture.output(str(samples)), capture.output(str(field)))
emit("structure", c(grepl("num [1:3]", overview[1L], fixed = TRUE),
                    grepl("int [1:2, 1:3]", overview[2L], fixed = TRUE)))
本例需在 基础 R。已在项目独立的 Windows x64 R 4.6.2 环境验证。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:基础 R。已在项目独立的 Windows x64 R 4.6.2 环境验证。

入口文件:projects/r-loops-functions-text/functions.R

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 functions.R,或下载右侧课程工程包。
  2. 确认本地已准备 基础 R。已在项目独立的 Windows x64 R 4.6.2 环境验证。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:R

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a317.zip

下载课程关联工程包:R

课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a325.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习