[R] how to pass defined function with more than one arguments to apply?

Gabor Grothendieck ggrothendieck at myway.com
Sat May 29 03:13:48 CEST 2004


Not sure what you intend with regard to length but to get a logical
vector indicating which rows equal a particular vector:

f1 <- function(tb, row) apply(tb,1,function(x)all(x==row))

# or without using apply:

f2 <- function(tb, row) colSums( abs( (t(tb) - row) ) ) == 0

# or in terms of a general compare function:

f3 <- function(tb, row, compare = function(x)all(x==row)) apply(tb,1,compare)

row <- c(0,3,1)
f1(tb,row)
f2(tb,row)
f3(tb,row)

# If you want the number of matching rows:

length(which(f1(tb,row)))
etc.



anoly <anoly16b <at> hotmail.com> writes:

: 
: Dear all:
: I meet a problem of apply function. I have a matrix called tb
: >tb
:    V1 V2 V3
: 1   0  3  1
: 2   1  4  0
: 3   0  3  0
: 4   0  4  0
: 5   0  3  1
: 6   1  4  1
: 7   1  1  0
: 8   1  3  0
: 9   0  1  1
: 10  0  3  1
: 
: I hope to get the number of row that match c(0,3,1)
: I do this way:
: >length(apply(t(tb) = = c (0,3,1), 2, all))
:  I defined a funtion, compare<-function(vector1, vector2){...}. For example,
: compare(1:3, 1:3) will return TRUE. compare(1:3,2:4) return FALSE.
: Then I hope to call  apply(tb,1,compare). But this can not work, because
: apply only pass one argument to compare function. Does anyone know how to
: solve this problem?
: 
: Thanks so much.
: Anoly
: 
: ______________________________________________
: R-help <at> stat.math.ethz.ch mailing list
: https://www.stat.math.ethz.ch/mailman/listinfo/r-help
: PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
: 
:




More information about the R-help mailing list