R : Calling a Function -


i have matrix :

x <- cbind(x1 = 3, x2 = c(4:1, 2:5)) dimnames(x)[[1]] <- letters[1:8] 

how following codes work ?

cave <- function(x, c1, c2) c(mean(x[c1]), mean(x[c2])) apply(x,1, cave,  c1="x1", c2=c("x1","x2")) 

particularly not understanding argument , c(mean(x[c1]), mean(x[c2])) inside function cave.

also call function in way cave(x,a,b) . inside apply function input when call cave function ?

when define function, last thing listed implicitly returned. when define cave as

cave <- function(x, c1, c2) {     c(mean(x[c1]), mean(x[c2])) } 

this same as

cave <- function(x, c1, c2) {     return(c(mean(x[c1]), mean(x[c2]))) } 

in r, vectors defined concatenating elements using c(). c(a, b) makes vector of length 2 elements a , b. in case, a mean of input x @ index given c1 , b mean of x @ index given c2.

when apply() function x on dimension 1, you're computing cave() on every row of x.

the syntax of apply() follows:

apply(x, # object input function       1, # dimension of x on apply function, 1=rows, 2=columns       cave, # function apply       c1="x1", c2=c("x1", "x2") # further arguments function       ) 

apply cave() first row gives vector consisting of mean of x1 (which x1 since it's mean of single number) , mean of x1 , x2. mean of 3 3 , mean of 3 , 4 3.5, output c(3, 3.5).

we repeat every row in x, , in end this:

       b   c d   e f   g h [1,] 3.0 3 3.0 3 3.0 3 3.0 3 [2,] 3.5 3 2.5 2 2.5 3 3.5 4 

you can see column a corresponds cave() on row a of x , on.


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -