zunman
zunman

Reputation: 118

R - apply family function that uses same iterator for multiple variable

alply(df1 %>% as.matrix, 2, foo, keyword.count)

I have the above line of code that applies function 'foo' on each column of 'df1'. I want to add an additional parameter (df2) to function foo that has same number of columns as df1. something like

alply(df1 %>% as.matrix, 2, foo, df2 %>% as.matrix, keyword.count)

I want a function that uses same iterator for df1 and df2. In terms of loops, df1[1] and df2[1] in 1st iteration, df1[2] and df2[2] in 2nd iteration and so on. In current implementation using alply, df1[1] uses df2 matrix as a parameter and not a column of df2.

in terms of a loop, it would look something like this

for(int i=0; i<ncol(df1); i++){
 foo(df1[i], df2[i], keyword.count)
}

Is there an apply family function that allows me to do this? or some way to get the number of iteration that can be accessed in "foo". Any help would be appreciated

example:

df1 <- data.frame(
       col1 = sample(LETTERS[1:5]),
       col2 = sample(LETTERS[6:10])
   )
df2 <- data.frame(
  col1 = sample(LETTERS[11:13]),
  col2 = sample(LETTERS[14:16])
)


foo <- function(terms, fixed_terms , collocated_words ) {
  terms <- terms[terms != ""]
  fixed_terms <- fixed_terms[fixed_terms != ""]

##use terms and fixed_terms in another function

}

mlply(.data =  as.matrix(df1),  .fun =  foo, fixed_terms = as.matrix(df2), collocated_word=2)

##error:
##Error in (function (terms, fixed_terms, collocated_words)  : 
##  unused arguments (col1 = "B", col2 = "H")

Upvotes: 2

Views: 342

Answers (1)

tbradley
tbradley

Reputation: 2290

you can use mlply:

mlply(as.matrix(df1), foo, argument2 = as.matrix(df2), 2)

you may need to specify what argument of foo each matrix is being called by

Upvotes: 1

Related Questions