【发布时间】:2017-08-09 10:29:42
【问题描述】:
alply(df1 %>% as.matrix, 2, foo, keyword.count)
上面的代码行在“df1”的每一列上应用了函数“foo”。我想向函数 foo 添加一个附加参数(df2),它的列数与 df1 相同。像
alply(df1 %>% as.matrix, 2, foo, df2 %>% as.matrix, keyword.count)
我想要一个对 df1 和 df2 使用相同迭代器的函数。在循环方面,第一次迭代中的 df1[1] 和 df2[1],第二次迭代中的 df1[2] 和 df2[2] 等等。 在当前使用 alply 的实现中,df1[1] 使用 df2 矩阵作为参数,而不是 df2 的列。
就循环而言,它看起来像这样
for(int i=0; i<ncol(df1); i++){
foo(df1[i], df2[i], keyword.count)
}
是否有一个应用家庭功能允许我这样做?或某种方式来获取可以在“foo”中访问的迭代次数。 任何帮助将不胜感激
示例:
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")
【问题讨论】: