base: The R Base Package

R基礎パッケージ

> library(base)

バージョン: 3.4.0


関数名 概略
.Call Modern Interfaces to C/C++ code
.Device Lists of Open/Active Graphics Devices
.Internal Call an Internal Function
.Last.value Value of Last Evaluated Expression
.Library Search Paths for Packages
.Machine Numerical Characteristics of the Machine
.Platform Platform Specific Variables
.Primitive Look Up a Primitive Function
.bincode Bin a Numeric Vector
.deparseOpts Options for Expression Deparsing
.onLoad Hooks for Namespace Events
.packages Listing of Packages
.standard_regexps Miscellaneous Internal/Programming Utilities
: Colon Operator
:: Double Colon and Triple Colon Operators
@ Extract or Replace A Slot
Arithmetic Arithmetic Operators
AsIs Inhibit Interpretation/Conversion of Objects
Bessel Bessel Functions
Comparison Relational Operators
Constants Built-in Constants
Control Control Flow
Cstack_info Report Information on C Stack Size and Usage
DateTimeClasses Date-Time Classes
Dates Date Class
Defunct Marking Objects as Defunct
Deprecated Marking Objects as Deprecated
Encoding Read or Set the Declared Encodings for a Character Vector
Extract Extract or Replace Parts of an Object
Filter Common Higher-Order Functions in Functional Programming Languages
Foreign Foreign Function Interface
ISOdatetime Date-time Conversion Functions from Numeric Representations
InternalMethods Internal Generic Functions
La_version LAPACK version
Logic Logical Operators
Memory Memory Available for Data Storage
Memory-limits Memory Limits in R
NA 'Not Available' / Missing Values
NULL The Null Object
NotYetImplemented Not Yet Implemented Functions and Unused Arguments
NumericConstants Numeric Constants
Ops.Date Operators on the Date Class
Paren Parentheses and Braces
Quotes Quotes
R.Version Version Information
R.home Return the R Home Directory
Random Random Number Generation
Random.user User-supplied Random Number Generation
Rdconv Utilities for Processing Rd Files
Recall Recursive Calling
Reserved Reserved Words in R
Signals Interrupting Execution of R
Special Special Functions of Mathematics
Startup Initialization at Start of an R Session
Syntax Operator Syntax and Precedence
Sys.getenv Get Environment Variables
Sys.getpid Get the Process ID of the R Session
Sys.glob Wildcard Expansion on File Paths
Sys.info Extract System and User Information
Sys.localeconv Find Details of the Numerical and Monetary Representations in the Current Locale
Sys.readlink Read File Symbolic Links
Sys.setFileTime Set File Time
Sys.setenv Set or Unset Environment Variables
Sys.sleep Suspend Execution for a Time Interval
Sys.time Get Current Date and Time
Sys.which Find Full Paths to Executables
Trig Trigonometric Functions
UseMethod Class Methods
Vectorize Vectorize a Scalar Function
[.data.frame Extract or Replace Parts of a Data Frame
[.factor Extract or Replace Parts of a Factor
abbreviate Abbreviate Strings
abs Miscellaneous Mathematical Functions
addTaskCallback Add or Remove a Top-Level Task Callback
agrep Approximate String Matching (Fuzzy Matching)
all Are All Values True?
all.equal Test if Two Objects are (Nearly) Equal
all.names Find All Names in an Expression
any Are Some Values True?
aperm Array Transposition
append Vector Merging
apply Apply Functions Over Array Margins
args Argument List of a Function
array Multi-way Arrays
as.Date Date Conversion Functions to and from Character
as.POSIXct Date-time Conversion Functions
as.data.frame Coerce to a Data Frame
as.environment Coerce to an Environment Object
as.function Convert Object to Function
assign Assign a Value to a Name
assignOps Assignment Operators
attach Attach Set of R Objects to Search Path
attachNamespace Loading and Unloading Name Spaces
attr Object Attributes
attributes Object Attribute Lists
autoload On-demand Loading of Packages
backsolve Solve an Upper or Lower Triangular System
base-package The R Base Package
basename Manipulate File Paths
bindenv Binding and Environment Locking, Active Bindings
bitwNot Bitwise Logical Operations
body Access to and Manipulation of the Body of a Function
bquote Partial substitution in expressions
browser Environment Browser
browserText Functions to Retrieve Values Supplied by Calls to the Browser
builtins Returns the Names of All Built-in Objects by Apply a Function to a Data Frame Split by Factors
c Combine Values into a Vector or List
call Function Calls
callCC Call With Current Continuation
capabilities Report Capabilities of this Build of R
cat Concatenate and Print
cbind Combine R Objects by Rows or Columns
ceiling Rounding of Numbers
char.expand Expand a String with Respect to a Target Table
charToRaw Convert to or from Raw Vectors
character Character Vectors
charmatch Partial String Matching
chartr Character Translation and Casefolding
chol The Choleski Decomposition
chol2inv Inverse from Choleski (or QR) Decomposition
class Object Classes
col Column Indexes
colSums Form Row and Column Sums and Means
commandArgs Extract Command Line Arguments
comment Query or Set a '"comment"' Attribute
complex Complex Vectors
conditions Condition Handling and Recovery
conflicts Search for Masked Objects on the Search Path
connections Functions to Manipulate Connections
contributors R Project Contributors
copyright Copyrights of Files Used to Build R
cosh Hyperbolic Functions
crossprod Matrix Crossproduct
cumsum Cumulative Sums, Products, and Extremes
cut Convert Numeric to Factor
cut.POSIXt Convert a Date or Date-Time Object to a Factor
data.class Object Classes
data.frame Data Frames
data.matrix Convert a Data Frame to a Numeric Matrix
date System Date and Time
debug Debug a Function
delayedAssign Delay Evaluation
deparse Expression Deparsing
det Calculate the Determinant of a Matrix
detach Detach Objects from the Search Path
diag Matrix Diagonals
diff Lagged Differences
difftime Time Intervals
dim Dimensions of an Object
dimnames Dimnames of an Object
dir.create Manipulaton of Directories and File Permissions
do.call Execute a Function Call
dontCheck Identity Function to Suppress Checking
double Double-Precision Vectors
dput Write an Object to a File or Recreate it
drop Drop Redundant Extent Information
droplevels droplevels
dump Text Representations of R Objects
duplicated Determine Duplicate Elements
dyn.load Foreign Function Interface
eapply Apply a Function Over Values in an Environment
eigen Spectral Decomposition of a Matrix
encodeString Encode Character Vector as for Printing
environment Environment Access environment variables Environment Variables
eval Evaluate an (Unevaluated) Expression
exists Is an Object Defined?
expand.grid Create a Data Frame from All Combinations of Factors
expression Unevaluated Expressions
factor Factors
file.access Ascertain File Accessibility
file.choose Choose a File Interactively
file.info Extract File Information
file.path Construct Path to File
file.show Display One or More Files
files File Manipulation
find.package Find Packages
findInterval Find Interval Numbers or Indices
force Force Evaluation of an Argument
formals Access to and Manipulation of the Formal Arguments
format Encode in a Common Format
format.info format(.) Information
format.pval Format P Values
formatC Formatting Using C-style Formats
formatDL Format Description Lists
function Function Definition
gc Garbage Collection
gc.time Report Time Spent in Garbage Collection
gctorture Torture Garbage Collector
get Return the Value of a Named Object
getDLLRegisteredRoutines Reflectance Information for C/Fortran routines in a DLL
getHook Functions to Get and Set Hooks for Load, Attach, Detach and Unload
getLoadedDLLs Get DLLs Loaded in Current Session
getNativeSymbolInfo Obtain a Description of one or more Native (C/Fortran) Symbols
getTaskCallbackNames Query the Names of the Current Internal Top-Level Task Callbacks
gettext Translate Text Messages
getwd Get or Set Working Directory
gl Generate Factor Levels
grep Pattern Matching and Replacement
grepRaw Pattern Matching for Raw Vectors
groupGeneric S3 Group Generic Functions
gzcon (De)compress I/O Through Connections
hexmode Display Numbers in Hexadecimal
iconv Convert Character Vector between Encodings
icuSetCollate Setup Collation by ICU
identical Test Objects for Exact Equality
identity Identity Function
ifelse Conditional Element Selection
integer Integer Vectors
interaction Compute Factor Interactions
interactive Is R Running Interactively?
invisible Change the Print Mode to Invisible
is.R Are we using R, rather than S?
is.finite Finite, Infinite and NaN Numbers
is.function Is an Object of Type (Primitive) Function?
is.language Is an Object a Language Object?
is.object Is an Object 'internally classed'?
is.recursive Is an Object Atomic or Recursive?
is.single Is an Object of Single Precision Type?
is.unsorted Test if an Object is Not Sorted
isS4 Test for an S4 object
isSymmetric Test if a Matrix or other Object is Symmetric
jitter 'Jitter' (Add Noise) to Numbers
kappa Compute or Estimate the Condition Number of a Matrix
kronecker Kronecker Products on Arrays
l10n_info Localization Information
labels Find Labels from Object
lapply Apply a Function over a List or Vector
length Length of an Object
levels Levels Attributes
library Loading/Attaching and Listing of Packages
library.dynam Loading DLLs from Packages
license The R License Terms
list Lists - Generic and Dotted Pairs
list.files List the Files in a Directory/Folder
list2env From A List, Build or Add To an Environment
load Reload Saved Datasets
locales Query or Set Aspects of the Locale
log Logarithms and Exponentials
logical Logical Vectors
long vector Long Vectors
lower.tri Lower and Upper Triangular Part of a Matrix
ls List Objects
make.names Make Syntactically Valid Names
make.unique Make Character Strings Unique
mapply Apply a Function to Multiple List or Vector Arguments
margin.table Compute table margin
mat.or.vec Create a Matrix or a Vector
match Value Matching
match.arg Argument Verification Using Partial Matching
match.call Argument Matching
match.fun Extract a Function Specified by Name
matmult Matrix Multiplication
matrix Matrices
max Maxima and Minima
max.col Find Maximum Position in Matrix
mean Arithmetic Mean
memCompress In-memory Compression and Decompression
memory.profile Profile the Usage of Cons Cells
merge Merge Two Data Frames
message Diagnostic Messages
missing Does a Formal Argument have a Value?
mode The (Storage) Mode of an Object
name Names and Symbols
names The Names of an Object
nargs The Number of Arguments to a Function
nchar Count the Number of Characters (or Bytes or Width)
nlevels The Number of Levels of a Factor
noquote Class for 'no quote' Printing of Character Strings
norm Compute the Norm of a Matrix
normalizePath Express File Paths in Canonical Form
nrow The Number of Rows/Columns of an Array
numeric Numeric Vectors
numeric_version Numeric Versions
octmode Display Numbers in Octal
on.exit Function Exit Code
options Options Settings
order Ordering Permutation
outer Outer Product of Arrays
parse Parse Expressions
paste Concatenate Strings
path.expand Expand File Paths
pcre_config Report Configuration Options for PCRE
pmatch Partial String Matching
polyroot Find Zeros of a Real or Complex Polynomial
pos.to.env Convert Positions in the Search Path to Environments
pretty Pretty Breakpoints
print Print Values
print.data.frame Printing Data Frames
print.default Default Printing
prmatrix Print Matrices, Old-style
proc.time Running Time of R
prod Product of Vector Elements
prop.table Express Table Entries as Fraction of Marginal Table
pushBack Push Text Back on to a Connection
qr The QR Decomposition of a Matrix
qr.X Reconstruct the Q, R, or X Matrices from a QR Object
quit Terminate an R Session
range Range of Values
rank Sample Ranks
rapply Recursively Apply a Function to a List
raw Raw Vectors
rawConnection Raw Connections
read.dcf Read and Write Data in DCF Format
readBin Transfer Binary Data To and From Connections
readChar Transfer Character Strings To and From Connections
readLines Read Text Lines from a Connection
readRDS Serialization Interface for Single Objects
readRenviron Set Environment Variables from a File
readline Read a Line from the Terminal
reg.finalizer Finalization of Objects
regex Regular Expressions as used in R
regmatches Extract or Replace Matched Substrings
remove Remove Objects from a Specified Environment
rep Replicate Elements of Vectors and Lists
replace Replace Values in a Vector
rev Reverse Elements
rle Run Length Encoding
round.POSIXt Round / Truncate Data-Time Objects
row Row Indexes
row.names Get and Set Row Names for Data Frames
rownames Row and Column Names
rowsum Give Column Sums of a Matrix or Data Frame, Based on a Grouping Variable
sQuote Quote Text
sample Random Samples and Permutations
save Save R Objects
scale Scaling and Centering of Matrix-like Objects
scan Read Data Values
search Give Search Path for R Objects
seek Functions to Reposition Connections
seq Sequence Generation
seq.Date Generate Regular Sequences of Dates
seq.POSIXt Generate Regular Sequences of Times
sequence Create A Vector of Sequences
serialize Simple Serialization Interface
setTimeLimit Set CPU and/or Elapsed Time Limits
shQuote Quote Strings for Use in OS Shells
showConnections Display Connections
sign Sign Function
sink Send R Output to a File
slice.index Slice Indexes in an Array
socketSelect Wait on Socket Connections
solve Solve a System of Equations
sort Sorting or Ordering Vectors
source Read R Code from a File or a Connection
split Divide into Groups and Reassemble
sprintf Use C-style String Formatting Commands
srcfile References to source files
stop Stop Function Execution
stopifnot Ensure the Truth of R Expressions
strptime Date-time Conversion Functions to and from Character
`strsplit`` Split the Elements of a Character Vector
`strtoi`` Convert Strings to Integers
strtrim Trim Character Strings to Specified Display Widths
structure Attribute Specification
strwrap Wrap Character Strings to Format Paragraphs
subset Subsetting Vectors, Matrices and Data Frames
substitute Substituting and Quoting Expressions
substr Substrings of a Character Vector
sum Sum of Vector Elements
summary Object Summaries
svd Singular Value Decomposition of a Matrix
sweep Sweep out Array Summaries
switch Select One of a List of Alternatives
sys.parent Functions to Access the Function Call Stack
sys.source Parse and Evaluate Expressions from a File
system Invoke a System Command
system.file Find Names of R System Files
system.time CPU Time Used
system2 Invoke a System Command
t Matrix Transpose
table Cross Tabulation and Table Creation
tabulate Tabulation for Vectors
tapply Apply a Function Over a Ragged Array
taskCallbackManager Create an R-level Task Callback Manager
tempfile Create Names for Temporary Files
textConnection Text Connections
tilde Tilde Operator
timezones Time Zones
toString Convert an R Object to a Character String
topenv Top Level Environment
trace Interactive Tracing and Debugging of Calls to a Function or Method
traceback Print Call Stacks
tracemem Trace Copying of Objects
transform Transform an Object, for Example a Data Frame
try Try an Expression Allowing Error Recovery
typeof The Type of an Object
union Set Operations
unique Extract Unique Elements
unlink Delete Files and Directories
unlist Flatten Lists
unname Remove 'names' or 'dimnames'
utf8ToInt Convert to or from UTF-8-encoded Character Vectors
vector Vectors
warning Warning Messages
warnings Print Warning Messages
weekdays Extract Parts of a POSIXt or Date Object
which Which indices are TRUE?
which.min Where is the Min() or Max() or first TRUE or FALSE ?
with Evaluate an Expression in a Data Environment
withVisible Return both a value and its visibility
write Write Data to a File
writeLines Write Lines to a Connection
xtfrm Auxiliary Function for Sorting and Ranking
zapsmall Rounding of Numbers

Dates

日付クラス。時刻に関する情報は持たない

> (today <- Sys.Date())
[1] "2017-05-19"
> format(today, "%Y-%m-%d")
[1] "2017-05-19"
> weekdays(today)
[1] "金曜日"
> months(today)
[1] "5月"

DateTimeClasses

日付・時間クラス。POSIXctクラスのオブジェクトは1970-01-01からの経過時間(秒、UNIX時間)、as.POSIXltクラスのオブジェクトは、各要素についてリスト形式でオブジェクトを持つ

Arguments

  • x, objext
  • digits
  • ...
  • time
  • time1, time2
  • z
  • lop
> (z <- Sys.time())
[1] "2017-05-19 17:05:21 JST"
> class(z)
[1] "POSIXct" "POSIXt"
> Sys.time() - 3600 # 1時間前
[1] "2017-05-19 16:05:21 JST"
> as.POSIXlt(Sys.time(), "GMT") %>% {
+   print(class(.))
+   .
+ }
[1] "POSIXlt" "POSIXt"
[1] "2017-05-19 08:05:21 GMT"
> as.Date("1970-01-01") %>% unclass()
[1] 0
> Sys.time() %>% as.POSIXlt() %>% unclass() %>% {
+   print(names(.))
+   str(.)
+ }
 [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"  
 [8] "yday"   "isdst"  "zone"   "gmtoff"
List of 11
 $ sec   : num 21.4
 $ min   : int 5
 $ hour  : int 17
 $ mday  : int 19
 $ mon   : int 4
 $ year  : int 117
 $ wday  : int 5
 $ yday  : int 138
 $ isdst : int 0
 $ zone  : chr "JST"
 $ gmtoff: int 32400
 - attr(*, "tzone")= chr [1:3] "" "JST" "JDT"

Encoding / enc2native / enc2utf8

文字列ベクトルに対するエンコーディングの読み込みとセット

Arguments

  • x... 文字列ベクトル
  • value... 文字列ベクトル
> x <- "\U0001f363"
> Encoding(x)
[1] "UTF-8"

EnvVar

Extract

オブジェクト参照

> x <- 1:12
> x[2]
[1] 2
> x[[2]]
[1] 2
> DT <- data.frame(x = seq(1, 3), y = letters[1:3])
> DT[1]
  x
1 1
2 2
3 3
> DT[1, 2]
[1] a
Levels: a b c
> DT[[1]]
[1] 1 2 3
> DT[[1, 2]]
[1] a
Levels: a b c
> DT$x
[1] 1 2 3

ISOdatetime / ISOdate

日付・時間の属性をもつオブジェクトへ変換

Arguments

  • year, month, day
  • hour, min, sec
  • tz

Logic

> x <- c(NA, FALSE, TRUE)
> isTRUE(x)
[1] FALSE
> !is.na(x) # NAでない場合にTRUE(is.na()の否定)
[1] FALSE  TRUE  TRUE

NA

欠損値の扱いに関する関数

Arguments

  • x: Rオブジェクト
  • recursive:
  • value
> NA
[1] NA
> is.na(c(1, NA))
[1] FALSE  TRUE
> anyNA((xx <- c(0:4)), recursive = FALSE)
[1] FALSE

R.home

Rのホームディレクトリを返す

Arguments

  • component... bin, doc, etc, include, modules, share,
> R.home()
[1] "/Library/Frameworks/R.framework/Resources"
> R.home(component = "bin")
[1] "/Library/Frameworks/R.framework/Resources/bin"

Rprof

> # プロファイリングの結果をファイルで出力する
> Rprof(NULL)
> Rprof(append = TRUE)
> Rprof(NULL)

Sys.getenv

環境変数の取得

Arguments

  • x
  • unset
  • names
> Sys.getenv() %>% names()
 [1] "__CF_USER_TEXT_ENCODING"    "ANALYTICS_SECRET"          
 [3] "ANALYTICS_TOKEN"            "Apple_PubSub_Socket_Render"
 [5] "CARTODB_KEY"                "CLICOLOR_FORCE"            
 [7] "COMMAND_MODE"               "DISPLAY"                   
 [9] "DYLD_FALLBACK_LIBRARY_PATH" "EDITOR"                    
[11] "ESA_IO_TOKEN"               "ESTAT_TOKEN"               
[13] "GDAL_DATA"                  "GIT_ASKPASS"               
[15] "GITHUB_PAT"                 "GITHUB_TOKEN"              
[17] "GMAIL_SECRET"               "GMAIL_TOKEN"               
[19] "HOME"                       "LANG"                      
[21] "LANGUAGE"                   "LC_CTYPE"                  
[23] "LN_S"                       "LOGNAME"                   
[25] "MAKE"                       "NIGHTLEY_DB_PW"            
[27] "NIGHTLEY_DB_USER"           "PAGER"                     
[29] "PATH"                       "PROJ_LIB"                  
[31] "QIITA_TOKEN"                "R_BROWSER"                 
[33] "R_BZIPCMD"                  "R_DOC_DIR"                 
[35] "R_GZIPCMD"                  "R_HOME"                    
[37] "R_INCLUDE_DIR"              "R_LIBS_SITE"               
[39] "R_LIBS_USER"                "R_PAPERSIZE"               
[41] "R_PDFVIEWER"                "R_PLATFORM"                
[43] "R_PRINTCMD"                 "R_QPDF"                    
[45] "R_RD4PDF"                   "R_SESSION_TMPDIR"          
[47] "R_SHARE_DIR"                "R_SYSTEM_ABI"              
[49] "R_TEXI2DVICMD"              "R_UNZIPCMD"                
[51] "R_ZIPCMD"                   "RMARKDOWN_MATHJAX_PATH"    
[53] "RS_RPOSTBACK_PATH"          "RS_SHARED_SECRET"          
[55] "RSTUDIO"                    "RSTUDIO_PANDOC"            
[57] "RSTUDIO_PDFLATEX"           "RSTUDIO_SESSION_PORT"      
[59] "RSTUDIO_USER_IDENTITY"      "RSTUDIO_WINUTILS"          
[61] "SED"                        "SHELL"                     
[63] "SOUNDCLOUD_TOKEN"           "SPARK_HOME"                
[65] "SSH_AUTH_SOCK"              "TAR"                       
[67] "TERM"                       "TMPDIR"                    
[69] "TREXA_DB_HOST"              "TREXA_DB_PORT"             
[71] "TWITTER_ACCESS_SECRET"      "TWITTER_ACCESS_TOKEN"      
[73] "TWITTER_KEY"                "TWITTER_SECRET"            
[75] "UDUNITS2_XML_PATH"          "USER"                      
[77] "WAKATIME_ID"                "WAKATIME_KEY"              
[79] "WAKATIME_SECRET"            "XPC_FLAGS"                 
[81] "XPC_SERVICE_NAME"
> Sys.getenv(c("R_HOME", "R_PLATFORM", "R_LIBS_USER", "RSTUDIO"))
                                     R_HOME 
"/Library/Frameworks/R.framework/Resources" 
                                 R_PLATFORM 
                "x86_64-apple-darwin15.6.0" 
                                R_LIBS_USER 
                  "~/Library/R/3.4/library" 
                                    RSTUDIO 
                                        "1"

attr

オブジェクト属性

> x <- 1:10
> attr(x, "dim") <- c(2, 5)
> attr(x, "dim")
[1] 2 5

attributes

> x <- cbind(a = 1:3, pi = pi)
> attributes(x)
$dim
[1] 3 2

$dimnames
$dimnames[[1]]
NULL

$dimnames[[2]]
[1] "a"  "pi"

all.equal

オブジェクトが同一であるかを評価する

ref) identical()

> all.equal(1, 1)
[1] TRUE
> all.equal(1, 2)
[1] "Mean relative difference: 1"

class / unclass / inherits / oldClass

クラス属性の参照、設定

Arguments

  • x... Rオブジェクト
  • what, value
  • which
> # summary()
> class(summary)
[1] "function"
> class(1)
[1] "numeric"
> class("a")
[1] "character"
> class(FALSE)
[1] "logical"

connections: file / url / gzfile / bzfile / xzfile / unz / pipe / fifo / socketConnection / open / close / flush / isOpen / isIncomplete

接続操作の関数

combn

> combn(letters[1:4], 2)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "a"  "a"  "a"  "b"  "b"  "c" 
[2,] "b"  "c"  "d"  "c"  "d"  "d"

cut

連続した数値を因子に変換

Arguments

  • x
  • breaks
  • labels
  • include.lowest
  • right
  • dig.lab
  • ordered_result
  • ...
> Z <- stats::rnorm(100)
> table(cut(Z, breaks = -6:6))

(-6,-5] (-5,-4] (-4,-3] (-3,-2] (-2,-1]  (-1,0]   (0,1]   (1,2]   (2,3] 
      0       0       0       0      13      39      32      14       2 
  (3,4]   (4,5]   (5,6] 
      0       0       0
> # http://stackoverflow.com/questions/33139720/count-and-aggregate-date-in-r
> zoo::as.yearmon(2015 + seq(4, 9) / 12) %>% 
+   zoo::as.Date(., format = "%d/%m/%Y") %>% 
+   cut(., "month") %>% 
+   table()
.
2015-05-01 2015-06-01 2015-07-01 2015-08-01 2015-09-01 2015-10-01 
         1          1          1          1          1          1

diff

> diff(1:10, 2)
[1] 2 2 2 2 2 2 2 2
> diff(1:10, 2, 2)
[1] 0 0 0 0 0 0

dir, list.dir, list.files

ファイル・フォルダの一覧を出力

Arguments

  • path
  • pattern: パターンマッチング
  • all.files: logical. TRUEの場合、隠しファイルを含めて表示する(初期値はFALSE)
  • full.names: logical. TRUEの場合、ファイルまでのパスを表示する(初期値はFALSE)
  • recursive: logical.
  • ignore.case: logical. パターンマッチングを行う際、大文字と小文字を区別するか(FALSEで区別する)
  • include.dirs
  • no..
> list.files(path = R.home())
 [1] "bin"          "COPYING"      "doc"          "etc"         
 [5] "fontconfig"   "include"      "Info.plist"   "lib"         
 [9] "library"      "man1"         "modules"      "R"           
[13] "Rscript"      "share"        "SVN-REVISION" "tests"
> list.dirs(path  = R.home("doc"))
[1] "/Library/Frameworks/R.framework/Resources/doc"              
[2] "/Library/Frameworks/R.framework/Resources/doc/html"         
[3] "/Library/Frameworks/R.framework/Resources/doc/manual"       
[4] "/Library/Frameworks/R.framework/Resources/doc/manual/images"
> dir(path = "../", 
+     pattern = "^[a-lr]", 
+     full.names = TRUE, 
+     ignore.case = TRUE)
 [1] "..//application"           "..//book.json"            
 [3] "..//chunk_setup.md"        "..//chunk_setup.Rmd"      
 [5] "..//data_handling"         "..//data-analysis"        
 [7] "..//database"              "..//dataset"              
 [9] "..//date_and_time"         "..//design"               
[11] "..//development"           "..//ESP_msk_alt.grd"      
[13] "..//ESP_msk_alt.gri"       "..//ESP_msk_alt.vrt"      
[15] "..//ESP2_msk_alt.grd"      "..//ESP2_msk_alt.gri"     
[17] "..//ESP2_msk_alt.vrt"      "..//Figure"               
[19] "..//gapminder.feather"     "..//graphics"             
[21] "..//inst"                  "..//README.md"            
[23] "..//README.Rmd"            "..//references.md"        
[25] "..//references.Rmd"        "..//reproducible_research"
[27] "..//rpkg_showcase.Rproj"

duplicated

重複している要素を確認する

> x <- c(9:20, 1:5, 3:7, 0:8)
> x
 [1]  9 10 11 12 13 14 15 16 17 18 19 20  1  2  3  4  5  3  4  5  6  7  0
[24]  1  2  3  4  5  6  7  8
> x[!duplicated(x)] # 重複している要素を取り除く
 [1]  9 10 11 12 13 14 15 16 17 18 19 20  1  2  3  4  5  6  7  0  8

environment

環境へのアクセス

Arguments

  • fun
  • value
  • x
  • hash
  • parent
  • env
  • size
> f <- function() {
+   "top level function"
+ }
> 
> # 以下の結果は同じ
> environment()
<environment: 0x10d374980>
> environment(fun = f)
<environment: 0x10d374980>
> .GlobalEnv
<environment: R_GlobalEnv>
> is.environment(.GlobalEnv)
[1] TRUE
> # ref) http://qiita.com/kohske/items/06b8a010838445c3f890
> getNamespace("stats")
<environment: namespace:stats>
> (obj.e <- environment(rnorm)) # namespace:stats
<environment: namespace:stats>
> ls(name = obj.e, all = TRUE) %>% {
+   head(.) %>% {
+     print(.)
+     obj.head <<- .
+   }
+   length(.)
+ }
[1] ".__global__"          ".__NAMESPACE__."      ".__S3MethodsTable__."
[4] ".approxfun"           ".asSparse"            ".cbind.ts"
[1] 1125
> ls(name = as.environment("package:stats"), all = TRUE) %>% {
+   head(.) %>% {
+     print(.)
+     obj2.head <<- .
+   }
+   length(.)
+ }
[1] ".checkMFClasses" ".getXlevels"     ".lm.fit"         ".MFclass"       
[5] ".nknots.smspl"   ".preformat.ts"
[1] 453
> getNamespaceExports("stats") %>% length()
[1] 453
> getNamespaceExports("stats") %>% grep(obj2.head[1], .)
[1] 324
> obj.head[1]
[1] ".__global__"
> obj2.head[1]
[1] ".checkMFClasses"
> is.function(rnorm)
[1] TRUE
> is.function(.__global__)
Error in eval(expr, envir, enclos): object '.__global__' not found
> is.function(.checkMFClasses)
[1] TRUE

exists

オブジェクトが存在するかを確認

Arguments

  • x
  • where
  • envir
  • frame
  • mod
  • inherits
  • ifnotfound
> exists("x")
[1] TRUE
> x <- letters
> exists("x")
[1] TRUE

expand.grid

要素に対するすべての組み合わせでデータフレームを作成

> data.frame(mean = 1:5, sd = seq(0, 1, length = 10)) %>% dim()
[1] 10  2
> expand.grid(mean = 1:5, sd = seq(0, 1, length = 10)) %>% {
+   print(dim(.))
+   dplyr::tbl_df(.)
+ }
[1] 50  2
# A tibble: 50 x 2
    mean             sd
   <int>          <dbl>
 1     1 0.000000000000
 2     2 0.000000000000
 3     3 0.000000000000
 4     4 0.000000000000
 5     5 0.000000000000
 6     1 0.111111111111
 7     2 0.111111111111
 8     3 0.111111111111
 9     4 0.111111111111
10     5 0.111111111111
# ... with 40 more rows

file2 / dir.exists

ファイルやディレクトリの操作

Arguments

  • path
  • paths
  • showWarnings
  • mode
  • use_umask
> # 指定したディレクトリが存在するか否か
> dir.exists(path = "data-analysis/")
[1] FALSE
> # ディレクトリを作成
> # dir.create(path, showWarnings = TRUE, recursive = FALSE, mode = "0777")
> # 権限の変更
> # Sys.chmod(paths, mode = "0777", use_umask = TRUE)
> # Sys.umask(mode = NA)

file.info

ファイルに関する情報を取得

Arguments

  • ...
  • extra_cols 真偽値:
> file.info(..., extra_cols = TRUE)
> file.mode(...)
> file.mtime(...)
> file.size(...)

file.show

ファイルを表示する

> file.show(file.path(R.home("doc"), "COPYRIGHTS"))

findInterval

> findInterval(3, c(1:10))
[1] 3
> findInterval(x = 2:10, vec = c(5, 10, 15), rightmost.closed = TRUE)
[1] 0 0 0 1 1 1 1 1 2

format

Arguments

  • x
  • trim
  • digits
  • nsmall
  • justify
  • width
  • na.encode
  • scientific
  • ...
  • big.mark, big.interval, small.mark, small.interval, decimal.mark, zero.print, drop0trailing
> format(1:10, trim = TRUE)
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"
> format(13.7, nsmall = 3)
[1] "13.700"
> format(c(6.0, 13.1), digits = 2)
[1] " 6" "13"
> format(Sys.Date(), "%Y-%m-%d")
[1] "2017-05-19"

formula / as.formula

モデル式

> class(fo <- y ~ x1 * x2) # チルダ演算子を使った式はformulaクラスになる
[1] "formula"
> fo
y ~ x1 * x2
<environment: 0x10d374980>
> typeof(fo)
[1] "language"
> terms(fo)
y ~ x1 * x2
attr(,"variables")
list(y, x1, x2)
attr(,"factors")
   x1 x2 x1:x2
y   0  0     0
x1  1  0     1
x2  0  1     1
attr(,"term.labels")
[1] "x1"    "x2"    "x1:x2"
attr(,"order")
[1] 1 1 2
attr(,"intercept")
[1] 1
attr(,"response")
[1] 1
attr(,".Environment")
<environment: 0x10d374980>

funprog / Reduce/ Filter / Find / Map / Negate / Position

> Filter(function(x) {
+   x %% 2
+   } == 0, 1:10)
[1]  2  4  6  8 10

gc / gcinfo

ガベージコレクション

> gc()
          used (Mb) gc trigger  (Mb) max used  (Mb)
Ncells 1560027 83.4    2637877 140.9  2164898 115.7
Vcells 3128703 23.9    5510187  42.1  5510187  42.1
> gcinfo(TRUE)
[1] FALSE
> x <- integer(100000); for(i in 1:18) x <- c(x, i)
> gcinfo(verbose = FALSE)
[1] TRUE
> gc(TRUE)
          used (Mb) gc trigger  (Mb) max used  (Mb)
Ncells 1560018 83.4    2637877 140.9  2164898 115.7
Vcells 3178682 24.3    5510187  42.1  5510187  42.1
> gc(reset = TRUE)
          used (Mb) gc trigger  (Mb) max used (Mb)
Ncells 1560024 83.4    2637877 140.9  1560024 83.4
Vcells 3178698 24.3    5510187  42.1  3178698 24.3

gctorture / gctorture2

iconv / iconvlist

文字列のエンコーディング

> x <- "fa\xE7ile"
> Encoding(x) <- "latin1"
> x
[1] "façile"
> Encoding(x)
[1] "latin1"
> iconv(x, from = "latin1", to = "UTF-8")
[1] "façile"
> utils::head(iconvlist(), n = 50)
 [1] "437"             "850"             "852"            
 [4] "855"             "857"             "860"            
 [7] "861"             "862"             "863"            
[10] "865"             "866"             "869"            
[13] "ANSI_X3.4-1968"  "ANSI_X3.4-1986"  "ARABIC"         
[16] "ARMSCII-8"       "ASCII"           "ASMO-708"       
[19] "ATARI"           "ATARIST"         "BIG-5"          
[22] "BIG-FIVE"        "BIG5"            "BIG5-2003"      
[25] "BIG5-HKSCS"      "BIG5-HKSCS:1999" "BIG5-HKSCS:2001"
[28] "BIG5-HKSCS:2004" "BIG5HKSCS"       "BIGFIVE"        
[31] "C99"             "CHINESE"         "CN"             
[34] "CN-BIG5"         "CN-GB"           "CN-GB-ISOIR165" 
[37] "CP-GR"           "CP-IS"           "CP1046"         
[40] "CP1124"          "CP1125"          "CP1129"         
[43] "CP1133"          "CP1161"          "CP1162"         
[46] "CP1163"          "CP1250"          "CP1251"         
[49] "CP1252"          "CP1253"
> length(iconvlist())
[1] 419
> iconv("\U001F618", "UTF-8", "UTF-16", toRaw = TRUE)
[[1]]
[1] fe ff d8 3d de 18
> iconv("\U0001F423", "UTF-8", "UTF-16") %>% charToRaw()
[1] fe ff d8 3d dc 23
> as.hexmode("0001f618") %>% as.character()
[1] "1f618"
> tolower("u_ribo: \xF0\x9F\x98\x94 \xF0\x9F\x98\x96イウエオ") %>% stringr::str_extract("_all[\U0001F600-\U0001F64F]")
[1] NA
> toupper("u_ribo: \xF0\x9F\x98\x94")
[1] "U_RIBO: \U0001f614"
> onv("u_ribo: \xed\xa0\xbd\xed\xb0\xa3 アイウエオ", "ASCII", "UTF-8", sub = "")
Error in onv("u_ribo: \xed\xa0\xbd\xed\xb0\xa3 アイウエオ", "ASCII", : could not find function "onv"

identical

オブジェクトが等しいかどうかの判定

ref) all.equal

> identical(1, NULL)
[1] FALSE
> identical(1, 1.)
[1] TRUE
> identical(1, as.integer(1))
[1] FALSE

isS4 / asS4

オブジェクトのクラスがS4であるかを検証

> isS4(iris)
[1] FALSE
> asS4(iris) %>% {
+   names(.) %>% print()
+   attributes(.)
+ }
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width" 
[5] "Species"
$names
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width" 
[5] "Species"     

$row.names
  [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
 [18]  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34
 [35]  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51
 [52]  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68
 [69]  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85
 [86]  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102
[103] 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
[120] 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
[137] 137 138 139 140 141 142 143 144 145 146 147 148 149 150

$class
[1] "data.frame"
> asS4(iris) %>% asS3()
$Sepal.Length
  [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7 5.4
 [18] 5.1 5.7 5.1 5.4 5.1 4.6 5.1 4.8 5.0 5.0 5.2 5.2 4.7 4.8 5.4 5.2 5.5
 [35] 4.9 5.0 5.5 4.9 4.4 5.1 5.0 4.5 4.4 5.0 5.1 4.8 5.1 4.6 5.3 5.0 7.0
 [52] 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2 5.0 5.9 6.0 6.1 5.6 6.7 5.6 5.8
 [69] 6.2 5.6 5.9 6.1 6.3 6.1 6.4 6.6 6.8 6.7 6.0 5.7 5.5 5.5 5.8 6.0 5.4
 [86] 6.0 6.7 6.3 5.6 5.5 5.5 6.1 5.8 5.0 5.6 5.7 5.7 6.2 5.1 5.7 6.3 5.8
[103] 7.1 6.3 6.5 7.6 4.9 7.3 6.7 7.2 6.5 6.4 6.8 5.7 5.8 6.4 6.5 7.7 7.7
[120] 6.0 6.9 5.6 7.7 6.3 6.7 7.2 6.2 6.1 6.4 7.2 7.4 7.9 6.4 6.3 6.1 7.7
[137] 6.3 6.4 6.0 6.9 6.7 6.9 5.8 6.8 6.7 6.7 6.3 6.5 6.2 5.9

$Sepal.Width
  [1] 3.5 3.0 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 3.7 3.4 3.0 3.0 4.0 4.4 3.9
 [18] 3.5 3.8 3.8 3.4 3.7 3.6 3.3 3.4 3.0 3.4 3.5 3.4 3.2 3.1 3.4 4.1 4.2
 [35] 3.1 3.2 3.5 3.6 3.0 3.4 3.5 2.3 3.2 3.5 3.8 3.0 3.8 3.2 3.7 3.3 3.2
 [52] 3.2 3.1 2.3 2.8 2.8 3.3 2.4 2.9 2.7 2.0 3.0 2.2 2.9 2.9 3.1 3.0 2.7
 [69] 2.2 2.5 3.2 2.8 2.5 2.8 2.9 3.0 2.8 3.0 2.9 2.6 2.4 2.4 2.7 2.7 3.0
 [86] 3.4 3.1 2.3 3.0 2.5 2.6 3.0 2.6 2.3 2.7 3.0 2.9 2.9 2.5 2.8 3.3 2.7
[103] 3.0 2.9 3.0 3.0 2.5 2.9 2.5 3.6 3.2 2.7 3.0 2.5 2.8 3.2 3.0 3.8 2.6
[120] 2.2 3.2 2.8 2.8 2.7 3.3 3.2 2.8 3.0 2.8 3.0 2.8 3.8 2.8 2.8 2.6 3.0
[137] 3.4 3.1 3.0 3.1 3.1 3.1 2.7 3.2 3.3 3.0 2.5 3.0 3.4 3.0

$Petal.Length
  [1] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 1.5 1.6 1.4 1.1 1.2 1.5 1.3
 [18] 1.4 1.7 1.5 1.7 1.5 1.0 1.7 1.9 1.6 1.6 1.5 1.4 1.6 1.6 1.5 1.5 1.4
 [35] 1.5 1.2 1.3 1.4 1.3 1.5 1.3 1.3 1.3 1.6 1.9 1.4 1.6 1.4 1.5 1.4 4.7
 [52] 4.5 4.9 4.0 4.6 4.5 4.7 3.3 4.6 3.9 3.5 4.2 4.0 4.7 3.6 4.4 4.5 4.1
 [69] 4.5 3.9 4.8 4.0 4.9 4.7 4.3 4.4 4.8 5.0 4.5 3.5 3.8 3.7 3.9 5.1 4.5
 [86] 4.5 4.7 4.4 4.1 4.0 4.4 4.6 4.0 3.3 4.2 4.2 4.2 4.3 3.0 4.1 6.0 5.1
[103] 5.9 5.6 5.8 6.6 4.5 6.3 5.8 6.1 5.1 5.3 5.5 5.0 5.1 5.3 5.5 6.7 6.9
[120] 5.0 5.7 4.9 6.7 4.9 5.7 6.0 4.8 4.9 5.6 5.8 6.1 6.4 5.6 5.1 5.6 6.1
[137] 5.6 5.5 4.8 5.4 5.6 5.1 5.1 5.9 5.7 5.2 5.0 5.2 5.4 5.1

$Petal.Width
  [1] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 0.2 0.2 0.1 0.1 0.2 0.4 0.4
 [18] 0.3 0.3 0.3 0.2 0.4 0.2 0.5 0.2 0.2 0.4 0.2 0.2 0.2 0.2 0.4 0.1 0.2
 [35] 0.2 0.2 0.2 0.1 0.2 0.2 0.3 0.3 0.2 0.6 0.4 0.3 0.2 0.2 0.2 0.2 1.4
 [52] 1.5 1.5 1.3 1.5 1.3 1.6 1.0 1.3 1.4 1.0 1.5 1.0 1.4 1.3 1.4 1.5 1.0
 [69] 1.5 1.1 1.8 1.3 1.5 1.2 1.3 1.4 1.4 1.7 1.5 1.0 1.1 1.0 1.2 1.6 1.5
 [86] 1.6 1.5 1.3 1.3 1.3 1.2 1.4 1.2 1.0 1.3 1.2 1.3 1.3 1.1 1.3 2.5 1.9
[103] 2.1 1.8 2.2 2.1 1.7 1.8 1.8 2.5 2.0 1.9 2.1 2.0 2.4 2.3 1.8 2.2 2.3
[120] 1.5 2.3 2.0 2.0 1.8 2.1 1.8 1.8 1.8 2.1 1.6 1.9 2.0 2.2 1.5 1.4 2.3
[137] 2.4 1.8 1.8 2.1 2.4 2.3 1.9 2.3 2.5 2.3 1.9 2.0 2.3 1.8

$Species
  [1] setosa     setosa     setosa     setosa     setosa     setosa    
  [7] setosa     setosa     setosa     setosa     setosa     setosa    
 [13] setosa     setosa     setosa     setosa     setosa     setosa    
 [19] setosa     setosa     setosa     setosa     setosa     setosa    
 [25] setosa     setosa     setosa     setosa     setosa     setosa    
 [31] setosa     setosa     setosa     setosa     setosa     setosa    
 [37] setosa     setosa     setosa     setosa     setosa     setosa    
 [43] setosa     setosa     setosa     setosa     setosa     setosa    
 [49] setosa     setosa     versicolor versicolor versicolor versicolor
 [55] versicolor versicolor versicolor versicolor versicolor versicolor
 [61] versicolor versicolor versicolor versicolor versicolor versicolor
 [67] versicolor versicolor versicolor versicolor versicolor versicolor
 [73] versicolor versicolor versicolor versicolor versicolor versicolor
 [79] versicolor versicolor versicolor versicolor versicolor versicolor
 [85] versicolor versicolor versicolor versicolor versicolor versicolor
 [91] versicolor versicolor versicolor versicolor versicolor versicolor
 [97] versicolor versicolor versicolor versicolor virginica  virginica 
[103] virginica  virginica  virginica  virginica  virginica  virginica 
[109] virginica  virginica  virginica  virginica  virginica  virginica 
[115] virginica  virginica  virginica  virginica  virginica  virginica 
[121] virginica  virginica  virginica  virginica  virginica  virginica 
[127] virginica  virginica  virginica  virginica  virginica  virginica 
[133] virginica  virginica  virginica  virginica  virginica  virginica 
[139] virginica  virginica  virginica  virginica  virginica  virginica 
[145] virginica  virginica  virginica  virginica  virginica  virginica 
Levels: setosa versicolor virginica

attr(,"row.names")
  [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
 [18]  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34
 [35]  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51
 [52]  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68
 [69]  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85
 [86]  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102
[103] 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
[120] 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
[137] 137 138 139 140 141 142 143 144 145 146 147 148 149 150

jitter

わずかな誤差を与える

Arguments

  • x
  • factor
  • amount... numeric. 与えるノイズの範囲(程度)
> rep(0, 7)
[1] 0 0 0 0 0 0 0
> rep(0, 7) %>% jitter(., amount = 1)
[1]  0.757348042447  0.625705375802  0.708199955057 -0.264208104461
[5]  0.747899825685 -0.697323657107 -0.436376660597

nchar

文字列の長さを数える

Arguments

  • x
  • type
  • allowNA
  • keepNA
> c("Hello", "こんにちは") %>% {
+   nchar(., type = "chars") %>% print()
+   nchar(., type = "bytes") %>% print()
+   nchar(., type = "width")
+ }
[1] 5 5
[1]  5 15
[1]  5 10

load

保存されたデータセットを読み込む

ref) save, readRDS

Arguments

  • file
  • envir
  • verbose
> load(file, envir = parent.frame(), verbose = FALSE)

locales

ロケール

Arguments

  • category... カテゴリカルな文字列。LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_CTYPE, LC_MONETARY, LC_NUMERIC and LC_TIME
  • locale
> # 現在のロケールを確認
> Sys.getlocale()
[1] "ja_JP.UTF-8/ja_JP.UTF-8/ja_JP.UTF-8/C/ja_JP.UTF-8/ja_JP.UTF-8"
> # 等しい
> sessionInfo()$locale
[1] "ja_JP.UTF-8/ja_JP.UTF-8/ja_JP.UTF-8/C/ja_JP.UTF-8/ja_JP.UTF-8"
> # Sys.setlocale("LC_ALL","English")

ls

オブジェクトの一覧を返す

ref) remove()

> x <- "aaa"
> ls()
 [1] "df"           "DT"           "f"            "fo"          
 [5] "i"            "l1"           "obj.e"        "res"         
 [9] "res_map"      "session.info" "sliced_df"    "today"       
[13] "x"            "xx"           "z"            "Z"

make.unique

文字列をユニークな形にする

> c("a", "a", "a") %>% make.unique()
[1] "a"   "a.1" "a.2"
> c("a", "a", "a.2", "a") %>% make.unique()
[1] "a"   "a.1" "a.2" "a.3"

match

該当する要素を返す

Arguments

  • x
  • table
  • nomatch
  • incomparables
> match("melon", c("apple", "banana", "melon"))
[1] 3
> fruits <- c("apple", "banana", "melon")
> match("watermelon", fruits)
[1] NA
> "banana" %in% fruits
[1] TRUE

mean

Arguments

  • x
  • trim
  • na.rm
  • ...
> x <- c(0:10, 50)
> (xm <- mean(x))
[1] 8.75
> c(xm, mean(x, trim = 0.10))
[1] 8.75 5.50

missing

関数内の引数に値が与えられているかを評価する

> myplot <- function(x, y) {
+   if (missing(y)) {
+     y <- x
+     x <- 1:length(y)
+   }
+   plot(x, y)
+ }
> myplot(y = 1)
Error in plot(x, y): argument "x" is missing, with no default

mode

> mode(2)
[1] "numeric"

noquote

> noquote(letters) %>% {
+   print(.)
+   class(.)
+ }
 [1] a b c d e f g h i j k l m n o p q r s t u v w x y z
[1] "noquote"

ns-dblcolon

パッケージの関数(内部名前空間)を呼び出すための2項演算子および3項演算子

> base::log
function (x, base = exp(1))  .Primitive("log")
> base::`+`
function (e1, e2)  .Primitive("+")
> rstan:::rstudio_stanc
Error in loadNamespace(name): there is no package called 'rstan'

ns-hooks / .onLoad / .onAttach / .onUnload / .Last.lib

Arguments

  • libname
  • pkgname
  • libpath
> ns-hooks()

ns-internals

内部名前空間の参照

Arguments

  • ns
  • base.OK
  • impenv
  • vars
  • generics
  • self
  • package
  • packages
  • package.lib
  • mustExist
  • genname
  • class
  • envir, env
  • info
  • which
  • val
  • ...
  • metaname
  • name
> getExportedValue("stats", "rnorm")
function (n, mean = 0, sd = 1) 
.Call(C_rnorm, n, mean, sd)
<bytecode: 0x10ad26fb8>
<environment: namespace:stats>
> getNamespace("stats")
<environment: namespace:stats>
> getNamespaceExports("stats") %>% length() # stats::hoge で参照できる関数
[1] 453
> getNamespaceImports("stats") %>% names()
[1] "base"      "graphics"  "grDevices" "utils"
> getNamespaceName("stats")
   name 
"stats"
> getNamespaceUsers("stats")
 [1] "zoo"        "crayon"     "DYM"        "munsell"    "stringi"   
 [6] "units"      "ggplot2"    "sf"         "devtools"   "knitr"     
[11] "dplyr"      "RefManageR" "memoise"    "lubridate"  "lattice"   
[16] "plyr"
> getNamespaceVersion("stats")
version 
"3.4.0"

path.expand

ファイルパスの表示。チルダをユーザーのホームディレクトリに置換する

> path.expand(path = "~")
[1] "/Users/uri"
> path.expand(getwd())
[1] "/Users/uri/git/rpkg_showcase/utility"

paste / paste0

文字列の結合

Arguments

  • ...
  • sep
  • collapse
> paste("a", "b", sep = ":")
[1] "a:b"
> paste("a", "b", se = ":")
[1] "a b :"
> paste0("a", "b")
[1] "ab"

pretty

Arguments

  • x
  • n
  • min.n
  • shrink.sml
  • high.u.bias
  • u5.bias
  • eps.correct
  • ...
> pretty(x = 1:15)
[1]  0  2  4  6  8 10 12 14 16

proc.time

R内での時間を返す

> ptm <- proc.time()
> for (i in 1:50) mad(stats::runif(500))
> proc.time() - ptm
            user           system          elapsed 
0.00900000000000 0.00000000000000 0.00900000000001

readBin / writeBin

バイナリデータの変換。コネクションからバイナリデータを読み込んだり、バイナリデータを書き出したり。

Arguments

  • descriptions
  • open
  • blocking
  • encoding
  • raw
  • method
  • compression
  • timeout
  • filename
  • host
  • port
  • server
  • con
  • type
  • rw
  • ...
> tempdir()
> zz <- file(description = paste(tempdir(), "testbin", sep = "/"), open = "wb")
> x <- as.integer(seq(0, 255, 32))
> writeBin(x, zz, size = 1)
> close(zz)

readRDS / saveRDS

単一のRオブジェクトの保存と再取得

Arguments

  • object
  • file
  • ascii
  • version
  • compress
  • refhook
> saveRDS(women, "women.rds")

regex

Rでの正規表現

remove / rm

オブジェクトを削除する

> x <- letters[1:4]
> ls()
 [1] "df"           "DT"           "f"            "fo"          
 [5] "fruits"       "i"            "l1"           "myplot"      
 [9] "obj.e"        "ptm"          "res"          "res_map"     
[13] "session.info" "sliced_df"    "today"        "x"           
[17] "xm"           "xx"           "z"            "Z"
> remove(x)
> ls()
 [1] "df"           "DT"           "f"            "fo"          
 [5] "fruits"       "i"            "l1"           "myplot"      
 [9] "obj.e"        "ptm"          "res"          "res_map"     
[13] "session.info" "sliced_df"    "today"        "xm"          
[17] "xx"           "z"            "Z"

sample

seq / seq.Date

連続値(シークエンス)の生成

> seq(1, 10) # 1:10 と同じ
 [1]  1  2  3  4  5  6  7  8  9 10
> LETTERS[seq( from = 1, to = 10 )]
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
> seq(from = as.Date("2000/1/1"), to = as.Date("2015/1/1"), by = "years") %>% 
+   sample(size = 10, replace = FALSE)
 [1] "2004-01-01" "2002-01-01" "2014-01-01" "2006-01-01" "2011-01-01"
 [6] "2001-01-01" "2008-01-01" "2007-01-01" "2010-01-01" "2015-01-01"
> # 日付
> seq(as.Date("2015/1/1"), as.Date("2015/12/31"), "days") %>% {
+   print(head(., n = 5))
+   length(.)
+ }
[1] "2015-01-01" "2015-01-02" "2015-01-03" "2015-01-04" "2015-01-05"
[1] 365

save / save.image

Rオブジェクトの保存

ref) load

Arguments

  • ...
  • list
  • file
  • ascii... FALSEでバイナリ形式での保存
  • version
  • envir
  • compress
  • compression_level
  • eval.promises
  • precheck
  • safe
> # save()はRオブジェクトを指定して保存
> 
> # save.image()は現在のワーキングディレクトリに含まれるオブジェクト全てを対象に保存

serialize / unserialize

シリアル化

Auguments

  • object
  • connection
  • ascii
  • xdr
  • version
  • refhook
> (x <- serialize(list(1,2,3), NULL))
 [1] 58 0a 00 00 00 02 00 03 04 00 00 02 03 00 00 00 00 13 00 00 00 03 00
[24] 00 00 0e 00 00 00 01 3f f0 00 00 00 00 00 00 00 00 00 0e 00 00 00 01
[47] 40 00 00 00 00 00 00 00 00 00 00 0e 00 00 00 01 40 08 00 00 00 00 00
[70] 00
> unserialize(x)
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

sets

要素の比較

> x <- 1:5
> y <- 2:7
> union(x, y) # 共通する要素を返す
[1] 1 2 3 4 5 6 7
> intersect(x, y) # 範囲にある要素を返す
[1] 2 3 4 5
> setdiff(x, y) # 第一引数にのみ含まれる要素を返す
[1] 1
> setdiff(y, x)
[1] 6 7
> setequal(x, y) # 要素が等しいか否か
[1] FALSE

stopinfo

引数に与えた値が等しくない場合に処理を停止する

> stopifnot(1 == 1)
> stopifnot(1 == 2)
Error: 1 == 2 is not TRUE

strptime

Arguments

  • x
  • tz
  • format
  • ...
  • usetz
> (z <- strptime(x = "10/10/15 20:31:16.683", format = "%d/%m/%y %H:%M:%OS"))
[1] "2015-10-10 20:31:16 JST"

subset

ベクター、行列及びデータフレームからの抽出

Arguments

  • x
  • subset
  • select
  • drop
  • ...
> nrow(iris)
[1] 150
> subset(iris, subset = Species == "setosa") %>% 
+   nrow()
[1] 50
> subset(iris, select = Petal.Length:Species) %>% names()
[1] "Petal.Length" "Petal.Width"  "Species"

substitute / quote / enquote

Arguments

  • expr
  • cl
  • env
> (s.e <- substitute(expression(a + b), list(a = 1))) # aの部分にリストで与えた値が入る
expression(1 + b)
> (s.s <- substitute( a + b,            list(a = 1)))
1 + b
> s.e %>% {
+   print(mode(.))
+   typeof(.)
+ }
[1] "call"
[1] "language"
> s.s %>% {
+   print(mode(.))
+   typeof(.)
+ }
[1] "call"
[1] "language"
> # これら2つは同じであるが、次のものは仕様が異なる
> (e.s.e <- eval(s.e))
expression(1 + b)
> e.s.e %>% {
+   print(mode(.))
+   typeof(.)
+ }
[1] "expression"
[1] "expression"
> quote(hello)
hello
> dplyr::summarise_(mtcars, quote(mean(mpg)))
  mean(mpg)
1 20.090625

system.time

実行時間の計測。ユーザーモード時間(個別のコードの処理時間)、システムモード時間(OSレベルでの処理時間)、経過時間

> system.time(for(i in 1:100) mad(runif(1000)))
           user          system         elapsed 
0.0160000000000 0.0000000000000 0.0160000000001

Sys.time / Sys.Date

現在の日付と時間を表示する

> Sys.time()
[1] "2017-05-19 17:05:23 JST"
> Sys.time() %>% format("%a %b %d %X %Y")
[1] "金  5 19 17時05分23秒 2017"
> Sys.Date()
[1] "2017-05-19"

table / as.table / is.table

クロス集計表の作成

Arguments

  • ...
  • exclude
  • useNA
  • dnn
  • x
  • row.names
  • responseName
  • stringsAsFactors
  • sep, base
> set.seed(71)
> rpois(100, 5) %>% table()
.
 1  2  3  4  5  6  7  8  9 11 
 7  8 14 18 19 11 10  9  3  1

tapply

因子グループに対して関数を適用

> set.seed(71)
> rbinom(32, n = 5, prob = 0.4) %>% as.factor() %>% {
+   tapply(., ., length) %>% print()
+   table(.) # 同じ
+ }
11 12 13 
 2  2  1
.
11 12 13 
 2  2  1

tempdir / tempfile

一時的なフォルダ、ファイルを作成する。一時ファイルはセッション終了時に削除される。

Arguments

  • pattern: 作成するファイル(フォルダ)につける名称のパターン
  • tmpdir:
  • fileext
> # tempfile(pattern = "file", tmpdir = tempdir(), fileext = "")
> tempdir()

terms

tilde

チルダ演算子(\~

timezones / OlsonNames

時間帯

> Sys.timezone(location = TRUE)
[1] "Asia/Tokyo"
> str(OlsonNames())
 chr [1:594] "Africa/Abidjan" "Africa/Accra" "Africa/Addis_Ababa" ...

transform

オブジェクトの修正

> summary(airquality$Ozone)
       Min.     1st Qu.      Median        Mean     3rd Qu.        Max. 
  1.0000000  18.0000000  31.5000000  42.1293103  63.2500000 168.0000000 
       NA's 
         37
> transform(airquality, Ozone = -Ozone) %$% summary(Ozone)
        Min.      1st Qu.       Median         Mean      3rd Qu. 
-168.0000000  -63.2500000  -31.5000000  -42.1293103  -18.0000000 
        Max.         NA's 
  -1.0000000           37

trimws

文字列の前後にある空白を取り除く

> x <- "  空白を含んだ文字列  "
> trimws(x)
[1] "空白を含んだ文字列"
> trimws(x, which = "right")
[1] "  空白を含んだ文字列"

typeof

Rオブジェクトの内部タイプを確認(logical, integer, doubleなどのタイプがある)

ref. mode()

> typeof(2)
[1] "double"

unique

> c("a", "a", "b") %>% unique()
[1] "a" "b"
> data.frame(x = c("A", "A", "B"),
+            y = seq(1, 1, 2)) %>% 
+   unique()
  x y
1 A 1
3 B 1

ファイルやフォルダの削除

Arguments

  • x
  • recursive
  • force
> unlink(x, recursive = FALSE, force = FALSE)

unlist

リストをベクトルに分解する

> unlist(options(), use.names = FALSE) %>% head()
[[1]]
[1] TRUE

[[2]]
function (prompt) 
{
    .Call("rs_askForPassword", prompt)
}
<environment: 0x103daf718>

[[3]]
[1] "quartz"

[[4]]
function (url) 
{
    .Call("rs_browseURL", url)
}
<environment: 0x109291200>

[[5]]
[1] TRUE

[[6]]
function (action) 
{
    if (identical(.Platform$pkgType, "mac.binary.mavericks")) {
        .Call("rs_canBuildCpp")
    }
    else {
        if (!.Call("rs_canBuildCpp")) {
            .rs.installBuildTools(action)
            FALSE
        }
        else {
            TRUE
        }
    }
}
<environment: 0x103daf718>
> unlist(Titanic)
, , Age = Child, Survived = No

      Sex
Class  Male Female
  1st     0      0
  2nd     0      0
  3rd    35     17
  Crew    0      0

, , Age = Adult, Survived = No

      Sex
Class  Male Female
  1st   118      4
  2nd   154     13
  3rd   387     89
  Crew  670      3

, , Age = Child, Survived = Yes

      Sex
Class  Male Female
  1st     5      1
  2nd    11     13
  3rd    13     14
  Crew    0      0

, , Age = Adult, Survived = Yes

      Sex
Class  Male Female
  1st    57    140
  2nd    14     80
  3rd    75     76
  Crew  192     20
> data.frame(x = c("A", "A", "B"),
+            y = seq(1, 1, 2)) %>% unlist()
x1 x2 x3 y1 y2 y3 
 1  1  2  1  1  1

warnings

警告文を出力する

> ow <- options("warn")
> for (w in -1:1) {
+    options(warn = w); cat("\n warn =", w, "\n")
+    for (i in 1:3) { cat(i,"..\n"); m <- matrix(1:7, 3,4) }
+ }

 warn = -1 
1 ..
2 ..
3 ..

 warn = 0 
1 ..
Warning in matrix(1:7, 3, 4): data length [7] is not a sub-multiple or
multiple of the number of rows [3]
2 ..
Warning in matrix(1:7, 3, 4): data length [7] is not a sub-multiple or
multiple of the number of rows [3]
3 ..
Warning in matrix(1:7, 3, 4): data length [7] is not a sub-multiple or
multiple of the number of rows [3]

 warn = 1 
1 ..
Warning in matrix(1:7, 3, 4): data length [7] is not a sub-multiple or
multiple of the number of rows [3]
2 ..
Warning in matrix(1:7, 3, 4): data length [7] is not a sub-multiple or
multiple of the number of rows [3]
3 ..
Warning in matrix(1:7, 3, 4): data length [7] is not a sub-multiple or
multiple of the number of rows [3]
> warnings()
Warning message:
Setting row names on a tibble is deprecated.
> options(ow)

with

attachせずに変数へアクセス可能

> with(iris, max(Sepal.Length))
[1] 7.9