在 apply 函数中使用 %in% 的正确方法

The correct way of using %in% within apply function

R 的新手所以有一些基本和愚蠢的问题。希望在不久的将来,我能向这里所有有经验的大师学习,成为对所有其他数据专家有帮助的人。

我的目标是检查 test 的每一行,如果 id 列在同一行的 id_lag 中。我的示例代码如下:

test <- as.data.frame(matrix(NA,10,3))
names(test) <- c("Year","id","id_lag")
test[,1] <- c(2011,2012,2013,2010,2014,2015,2016,2010,2011,2012)
test[,2] <- c(76,560,342,7908,200,23,23,890,780,150)
test[,3] <- c("76,89","209,2000,400","342,333,234","908,888","","23","8097,5678","12","780,209","150,4504")

involved <- function(id,id_lag)
{
 a <- return(id %in% scan(what = "", sep = ",",text = id_lag) )
 return(a)
}



check <- apply(test, 1, function(x,y) involved(test$id,test$id_lag))

我希望得到 1 x 10 的 TRUEFALSE 列表,无论它是否列在此行中。但是,我得到一个 10 x 10 的矩阵,其中 TRUEFALSE 扫描了整个列表 10 次。有什么办法可以消除此应用功能,只扫描行而不是对整个列表进行全面扫描?或者有没有更好的方法,比如 data.tables 等等?

谢谢,
安妮

apply(X, MARGIN, FUN, ...) 如果 MARGIN = 1 则在矩阵的行上应用函数,如果 MARGIN = 2.

则在列上应用函数

你用

做了什么
check <- apply(test, 1, function(x,y) involved(test$id,test$id_lag))

是"call the function involved(test$id,test$id_lag) for each row of the text matrix"。所以你最终得到一个 10x10 矩阵,因为你已经为 test.

的 10 行中的每一行调用了一次 involved(test$id,test$id_lag)

如果您想跨行应用一个函数,同时将多个列的元素作为每个函数调用的参数,mapply() 是一个有用的函数。也许是这样的:

mapply( function(x,y) involved(x,y), x = test$id, y = test$id_lag )