정의
function_name = function ( arguments ) body
- Editor program is useful to write a long program including R function. R program provides an editor but there are several editors or IDEs freely available for R programming. (for example, Tinn-R, RStudio)
함수의 정의
rm( list = ls() )
my.mean = function( data ) sum( data ) / length( data )
ls()
## [1] "my.mean"
my.mean
## function( data ) sum( data ) / length( data )
my.mean( 1:10 )
## [1] 5.5
mean( 1:10 )
## [1] 5.5
R editor
# try this in the R console
#fix(my.sd)
my.sd
## function( data )
## {
## data.var <- sum( ( data - my.mean( data ) )^2 ) / ( length( data ) - 1 )
## data.sd <- sqrt( data.var )
## return( data.sd )
## }
my.sd( 1:10 )
## [1] 3.02765
sd( 1:10 )
## [1] 3.02765
source() function
source( 'files/my.range.R' )
my.range
## function (data)
## {
## data.min <- min(data)
## data.max <- max(data)
## c(data.min, data.max)
## }
my.range( 1:10 )
## [1] 1 10
range( 1:10 )
## [1] 1 10
함수의 구조
my.range2 = function( data , opt = 'r' ) {
data.min = min( data )
data.max = max( data )
switch( EXPR = opt , diff = data.max - data.min , r = c( data.min , data.max ) , NA )
}
my.range2( data = 1:10 )
## [1] 1 10
my.range2( datas = 1:10 )
## Error in my.range2(datas = 1:10): unused argument (datas = 1:10)
my.range2( 1:10 )
## [1] 1 10
my.range2( data = 1:10 , opt = 'diff' )
## [1] 9
my.range2( 1:10 , 'diff' )
## [1] 9
my.range2( 1:10 , 'x' )
## [1] NA
my.range2( 1:10 , 'r' )
## [1] 1 10
my.range2( 'diff' , 1:10 )
## Error in switch(EXPR = opt, diff = data.max - data.min, r = c(data.min, : EXPR must be a length 1 vector
my.range2( opt = 'diff' , data = 1:10 )
## [1] 9
my.range3 = function( data , ... ) {
data.min = min( data )
data.max = max( data )
args = list( ... )
print( args )
opt = ifelse( !is.null( args$opt ) , args$opt , '' )
switch( EXPR = opt , diff = data.max - data.min , r = c( data.min , data.max ) , NA )
}
my.range3( 1:10 )
## list()
## [1] NA
my.range3( 1:10 , opt = 'r' )
## $opt
## [1] "r"
## [1] 1 10
my.range3( 1:10 , opt = 'r' , arg1 = 'a' , arg2 = 1:10 )
## $opt
## [1] "r"
##
## $arg1
## [1] "a"
##
## $arg2
## [1] 1 2 3 4 5 6 7 8 9 10
## [1] 1 10
my.mean
## function( data ) sum( data ) / length( data )
## <bytecode: 0x7fb513d985c8>
my.sd
## function( data )
## {
## data.var <- sum( ( data - my.mean( data ) )^2 ) / ( length( data ) - 1 )
## data.sd <- sqrt( data.var )
## return( data.sd )
## }
data.sd
## Error in eval(expr, envir, enclos): object 'data.sd' not found
rng = my.range3( 1:10 , opt = 'r' )
## $opt
## [1] "r"
rng
## [1] 1 10
diff( rng )
## [1] 9
is.function( my.sd )
## [1] TRUE
args( my.sd )
## function (data)
## NULL
attributes( my.sd )
## $srcref
## function( data )
## {
## data.var <- sum( ( data - my.mean( data ) )^2 ) / ( length( data ) - 1 )
## data.sd <- sqrt( data.var )
## return( data.sd )
## }