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

R 在应用函数中使用%in%的正确方法,r,function,apply,scanf,R,Function,Apply,Scanf,对R来说是新手,所以有一些基本的愚蠢的问题。希望我能向这里所有有经验的大师学习,并在不久的将来成为对所有其他数据专家都有帮助的人 我的目标是检查test的每一行,如果id列在同一行的id\u 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,201

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

我的目标是检查
test
的每一行,如果
id
列在同一行的
id\u 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))
test
apply(X,MARGIN,FUN,…)
如果
MARGIN=1,则在矩阵行中应用函数;如果
MARGIN=2,则在列中应用函数

你做了什么

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

将进一步探讨应用函数系列。谢谢
mapply( function(x,y) involved(x,y), x = test$id, y = test$id_lag )