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

用基础 R 验证名称、向量与文件流

R基础 R。已在项目独立的 Windows x64 R 4.6.2 环境验证。basic.R
basic.R69 行
show_names <- function() {
  readings = c(4L, 9L)
  label <- "West"
  c(TRUE, 7) -> mixed
  print(mixed)
  print(ls())
  rm(mixed)
  print(ls())
}

print("Weekly notes")
print(27L)
print(6e2)
print(8e-2)
print(c(6, 9, 14) * 2)
cat("sample", 7, "accepted\n", sep = " ")
show_names()

candidates <- c("total_n2.", "total%", "2total", ".total", "total.n",
                ".2total", "_total")
accepts_name <- function(candidate) {
  tryCatch({
    expression <- parse(text = paste(candidate, "<- 1"))[[1L]]
    is.symbol(expression[[2L]])
  }, error = function(error) FALSE)
}
valid <- vapply(candidates, accepts_name, logical(1L), USE.NAMES = FALSE)
cat("ordinary names:", paste(as.integer(valid), collapse = " "), "\n")

write_and_read <- function() {
  work <- tempfile("mbsky-r-")
  stopifnot(dir.create(work))
  previous <- getwd()
  on.exit({
    setwd(previous)
    unlink(work, recursive = TRUE)
  })
  setwd(work)
  cat("working directory changed:", getwd() != previous, "\n")
  cat("previous\n", file = "notes.txt")
  cat("north", file = "notes.txt")
  cat("-south\n", file = "notes.txt", append = TRUE)
  print(readLines("notes.txt"))

  cat("last line without newline", file = "unfinished.txt")
  warned <- FALSE
  result <- withCallingHandlers(readLines("unfinished.txt"), warning = function(w) {
    warned <<- TRUE
    invokeRestart("muffleWarning")
  })
  cat("missing newline:", length(result), "line; warning:", warned, "\n")

  record <- function(split, append, number) {
    sink("transcript.txt", split = split, append = append)
    on.exit(sink())
    print(number)
  }
  record(TRUE, FALSE, 11)
  record(FALSE, TRUE, 22)
  cat("restored console:", sink.number() == 0L, "\n")
  cat("saved transcript:", paste(readLines("transcript.txt"), collapse = " | "), "\n")
}
write_and_read()

connection <- file("stdin", open = "rt")
input <- readLines(connection, n = 1L, warn = FALSE)
close(connection)
if (length(input)) cat("received:", input, "\n")
本例需在 基础 R。已在项目独立的 Windows x64 R 4.6.2 环境验证。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/r-first-scripts/basic.R

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

下载课程关联工程包:R

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

下载课程关联工程包:R

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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