1. ホーム
  2. R

R言語における共通関数

2022-02-27 05:41:34
Rでよく使われる数学関数
この言語の数学的操作といくつかの簡単な関数は次のように構成されています。
ベクトルは通常の算術演算を行うことができ、異なる長さのベクトルを足すことができ、その場合、最短のベクトルがループされます。
コンパイル環境の言語変更(英語)
Sys.setenv(LANGUAGE="en")を実行します。
> x <- 1:4
10
x * a
[1] 10 20 30 40
x + a
[1] 11 12 13 14
> sum(x) #xの要素を合計する
[1] 10
> prod(x) # x の要素の連結積を求める。
[1] 24
> prod(2:8) # 8の階乗
[1] 40320
> prod(2:4) #4 の階乗
[1] 24
> max(x) # xに含まれる要素の最大値
[1] 4
> min(x) #xに含まれる要素の最小値
[1] 1
> which.max(x) # xの中で最大の要素の添え字を返す。
[1] 4
> which.min(x) # xの中で最も小さい要素の添え字を返す。
[1] 1
> x <- 4:1 # ベクトル x に値を再割り当てする。
> x
[1] 4 3 2 1
> which.min(x)
[1] 4
> which.max(x)
[1] 1
 <%in%は関数に含まれます>

>x[x%in%c(2,3)]<-0
> x
[1] 1 0 0 4 ## x の 2,3 を 0 に置き換える。

> range(x) # c(min(x), max(x)) と同じです。
[1] 1 4
> mean(x) #xに含まれる要素の平均値
[1] 2.5
> median(x) # xに含まれる要素の中央値
[1] 2.5
> var(x) # xの要素の分散(分母にn-1を使用)。
[1] 1.666667
x
[1] 4 3 2 1
> rev(x) #xの要素を逆順に取り出す
[1] 1 2 3 4
> sort(x) # x の要素を昇順に並べ替えます。
[1] 1 2 3 4
x
[1] 4 3 2 1
> cumsum(x) # 累積和を求め、i 番目の要素が x[1] から x[i] までの和であるベクトルを返す。
[1] 4 7 9 10
> cumsum(rev(x))
[1] 1 3 6 10
11:14
> pmin(x,y) # i番目の要素が x[i], y[i], ... の最小の値であるベクトルを返します。
[1] 4 3 2 1
> x <- rev(x) # 再配置する
> pmin(x,y)
[1] 1 2 3 4
> pmax(x,y) # 各要素が対応する位置のベクトル x と y の要素のうち最大のものを持つベクトルを返す。
[1] 11 12 13 14
> cumprod(x) # 累積(左から右への)積を求める。
[1] 1 2 6 24
> cummin(x) # 累積最小値を求める(左から右へ)
[1] 1 1 1 1
> cummax(x) # 累積最大値を求める(左から右へ)
[1] 1 2 3 4
> match(x, y) # xと同じ長さのベクトルで、xの要素のうちyの要素と同じもののyにおける位置を返す(同じものがなければNA)
[1] ナ ナ ナ ナ
> y[c(2,4)] <- c(2,4)
> y
[1] 11 2 13 4
> match(x, y)
[1] NA 2 NA 4
>merge(x,y,by=c(" "))を実行します。
2つのデータボックスをマージする x,y は、2つのデータボックスが共通に持つ列または行で "by" をマージすると考えます。
分割(x,f)
na.omit(x) 関数は、欠損値(NA)を持つオブザベーションを無視します(x が行列またはデータフレームである場合、対応する行は無視されます)。
> na.omit(マッチ(x,y))
[1] 2 4
attr(,"na.action")です。
[1] 1 3
attr(,"class")
[1] "omit"
> na.fail(match(x,y))です。#na.fail(x) は、xに少なくとも1つのNAが含まれていれば、エラーメッセージを返します。
na.fail.default(match(x,y)) でエラー。オブジェクトに値がありません
which()関数はxが満たす条件(比較演算が真(TRUE)になったとき)の添え字を含むベクトルを返し、この結果ベクトルの値iはx[i] == aを示します(この関数の引数は論理変数でなければなりません)。
> which( x == 2)
[1] 2
> which( x <= 2)
[1] 1 2
組み合わせの数を求める
選択(4,2)
[1] 6
> 選択(3,1)
[1] 3
> 選択(-3,1)
[1] -3
> 選択(-4,2)
[1] 10
順列の数を求めよ。
 ライブラリ(gregmisc)
> permutations(n = 4, r = 2)
      [,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 1 4
[4,] 2 1
[5,] 2 3
[6,] 2 4
[7,] 3 1
[8,] 3 2
[9,] 3 4
[10,] 4 1
[11,] 4 2
[12,] 4 3
> コンビネーション(n = 4, r = 2)
     [,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 1 4
[4,] 2 3
[5,] 2 4
[6,] 3 4
また、関数combn()を使って、すべての要素の組み合わせを取得することもできます。
> y <- c(1:4, rep(4,1))
> y
[1] 1 2 3 4 4
> unique(y) # y がベクトルまたはデータフレームの場合、類似のオブジェクトを返すが、重複する要素はすべて取り除く(重複の場合は1つだけ取る)。
[1] 1 2 3 4
> table(y) # y の繰り返し要素の数のリストを返すテーブル(特に整数や階乗の変数の場合)
y
1 2 3 4
1 1 1 1 2
> subset(x, x>2) # 特定の条件を満たすxの部分集合を返す......部分集合のうち
[1] 3 4
> sample(x, 2) # putbackなしのxからのサンプルサイズ、putbackありのサンプリングではオプションREPLACE= TRUE
[1] 1 2
> sample(x, 2, replace = TRUE) #プットバック付きサンプル
[1] 2 3
>union(x,y) 2つのベクトルの和を求めます。
>交差点(x,y) 2つのベクトルの交差点を求めます。
>setdiff(x=1:4, y=2:3) ベクトルxとyの異なる要素を見つける(xの異なる要素を取る)。
[1] 1 4
Rにはデータを処理するための関数がたくさんありすぎて、ここにすべてを列挙することはできません。基本的な数学関数(log, exp, log10, log2, sin, cos, tan, asin, acos, atan, abs, sqrt, ... )、特殊関数(γ, digamma, beta, besselI, ... )、さらに統計に役立つ様々な関数が含まれています。
形式は、データを科学的アルゴリズムの形式に変換します。

mm
[1] 300000
> format(mm,digits = 1,scientific = TRUE)
[1] "3e+05"

I. データ管理

vector: vector numeric: numeric vector logical: logical vector character; character vector list: list 
data.frame: data frame c: join as vector or list length: find length subset: find subset seq, from:to, sequence: equivariant sequence 
rep: duplicate NA: missing value NULL: null object sort, order, unique, rev: sort unlist: spreading list attr, attributes: object attributes 
mode, typeof: object storage mode and type names: object's name attributes

II. 文字列の取り扱い

character: character vector nchar: number of characters substr: take substring format, formatC: convert object to string using format paste, strsplit: concatenate or split
 charmatch, pmatch: string matching grep, sub, gsub: pattern matching and replacement  

III. 複数形

complex, Re, Im, Mod, Arg, Conj: complex number functions  

IV. ファクター

factor: factor codes: coding of factors levels: names of levels of factors nlevels: number of levels of factors cut: converting numerical objects into factors by intervals 
table: cross-frequency table split: group by factor aggregate: compute generalized statistics for each subset of data tapply: apply function to "irregular" arrays

数学

I. 計算方法

+, -, *, /, ^, %%, %/%: quadrature ceiling, floor, round, signif

1. round() #丸め
例:x <- c(3.1416, 15.377, 269.7)
round(x, 0) # 整数ビットを保持する。
round(x, 2) #小数点以下2桁を維持する。
round(x, -1) #10進数にする。
2. signif() #有効数字(学習した有効数字と同じでない)を取る
例:省略
3. trunc() # 丸め
   floor() #切り捨て
   天井() #切り上げ
例: xx <- c(3.60, 12.47, -3.60, -12.47)
trunc(xx)
フロア(XX)
天井(XX)
 max, min, pmax, pmin: max-min 
range: maximum and minimum sum, prod: vector element sum, product cumsum, cumprod, cummax, cummin: cumulative, cumulative multiplication sort: sort approx and approxx fun: interpolation diff: difference sign: symbolic function  

II:数学的機能

abs, sqrt: absolute value, square root log, exp, log10, log2: logarithmic and exponential functions sin, cos, tan, asin, acos, atan, atan2: trigonometric functions 
sinh, cosh, tanh, asinh, acosh, atanh: hyperbolic functions

beta, lbeta, gamma, lgamma, digamma, trigamma, tetragamma, pentagamma, choice , lchoose: special functions related to beta functions, gamma functions, combinatorial numbers

fft, mvfft, convolve: fulleaf transform and convolution polyroot: polynomial root poly: orthogonal polynomial spline, splinefun: spline difference 
besselI, besselK, besselJ, besselY, gammaCody: Bessel functions deriv: symbolic differentiation or algorithmic differentiation of simple expressions

array: build array matrix: generate matrix data.matrix: convert data frame to numeric matrix lower.tri: lower triangular part of matrix mat.or.vec: generate matrix or vector t: matrix transpose
 cbind: merge columns into matrix rbind: merge rows into matrix diag: matrix diagonal element vector or generate diagonal matrix aperm: array transpose nrow, ncol: calculate the number of rows and columns of the array dim: dimension vector of the object 
dimnames: the object's dimensional names row/colnames: row names or column names %*%: matrix multiplication crossprod: matrix crossproduct (inner product) outer: the array's outer product kronecker: the array's Kronecker product 
apply: apply a function to some dimension of the array tapply: apply a function to "irregular" arrays sweep: calculate the generalized statistics of the array aggregate: calculate the generalized statistics of a subset of the data scale: matrix normalization
 matplot: plot the columns of the matrix cor: correlation or covariance matrix Contrast: control matrix row: the set of row subscripts of the matrix col: the set of column subscripts  

solve: solve a system of linear equations or find the inverse eigen: eigenvalue decomposition of a matrix svd: singular value decomposition of a matrix backsolve: solve a system of upper or lower triangular equations chol: Choleski decomposition 
qr: QR decomposition of matrices chol2inv: inverse from Choleski decomposition  

iii. 配列

<, >, <=, >=, ==, ! =: comparison operators ! , &, &&, |, ||, xor(): logical operators logical: generates logical vectors all, any: logical vectors are all true or exist true
ifelse(): choose one of the two match, %in%: find unique: find elements which are not identical to each other which: find the set of truth subscripts duplicated: find duplicate elements  

IV. 線形代数

optimize, uniroot, polyroot: one-dimensional optimization and rooting

V. 論理演算

if, else, ifelse, switch: branch for, while, repeat, break, next: loop apply, lapply, sapply, tapply, sweep: functions that replace loops.  

VI. 最適化とルート探索

function: function definition source: call file call: function call . Recall: recursive calls 
browser, debug, trace, traceback: program debugging options: specifies system parameters missing: determines whether a virtual parameter has a corresponding real parameter nargs: number of parameters stop: terminates function execution
on.exit: specify when to exit eval, expression: expression calculation system.time: expression calculation timing invisible: make variables invisible menu: select menu (character list menu)

Other functions related to: delay, delete.response, deparse, do.call, dput, environment ,, formals, format.info, interactive
is.finite, is.function, is.language, is.recursive, match.arg, match.call, match.fun, model.extract, name, parse, substitute, sys.parent , and warning, machine

プログラミング

I. 制御構造

cat, print: display object sink: output to the specified file dump, save, dput, write: output object scan, read.table, load, dget: read in  

II. 機能一覧

ls, objects: show the list of objects rm, remove: remove objects q, quit: exit the system .First, .Last: initial run function and exit run function. 
options: system options ? help, help.start, apropos: help functions data: list data set head() to see the first few rows of data tail() to see the last few rows of data

Each distribution has four functions: d - density (density function), p - distribution function, q - quantile function, r --the random number function.
For example, these four functions of the normal distribution are dnorm, pnorm, qnorm, and rnorm. Below we list the suffixes of each distribution, preceded by the prefixes d, p, q, or r to form the function names.

norm: normal, t: t-distribution, f: F-distribution, chisq: chi-square (including non-central) unif: uniform, exp: exponential, weibull: Weibull, gamma: gamma, beta: beta 
lnorm: lognormal, logis: logistic distribution, cauchy: cauchy, binom: binomial distribution, geom: geometric distribution, hyper: hypergeometric, nbinom: negative binomial, pois: Poisson signrank: sign rank
wilcox: rank sum, tukey: studentized extreme deviation  

III. 入力と出力

sum, mean, var, sd, min, max, range, median, IQR (interquartile range), etc. are statistics, sort, order, rank are related to sorting, and others are ave, fivenum, mad, quantile, stem, etc.

IV. 作業環境

 The implemented ones in R are chisq.test, prop.test, t.test.  

統計計算

I. 統計的分布

cor, cov.wt, var: covariance array and correlation array calculation biplot, biplot.princomp: multivariate data biplot plot cancor: canonical correlation princomp: principal component analysis hclust: spectral clustering 
kmeans: k-means clustering cmdscale: classical multidimensional scaling Others are dist, mahalanobis, cov.rob.  

ts: time series object diff: compute the difference time: time series sampling time window: time window  

II. 単純な統計

lm, glm, aov: linear model, generalized linear model, analysis of variance


III. 統計テスト

 The implemented ones in R are chisq.test, prop.test, t.test.  

IV. 多変量解析

cor, cov.wt, var: covariance array and correlation array calculation biplot, biplot.princomp: multivariate data biplot plot cancor: canonical correlation princomp: principal component analysis hclust: spectral clustering 
kmeans: k-means clustering cmdscale: classical multidimensional scaling Others are dist, mahalanobis, cov.rob.  

V. 時系列

ts: time series object diff: compute the difference time: time series sampling time window: time window  

VI. 統計モデル

lm, glm, aov: linear model, generalized linear model, analysis of variance