0

如何将下面的嵌套 For 循环转换为 Apply?

for(i in 1:length(vList$Subgroup.Number))
{
  for(j in 1:length(viol_grp))
   {
    viol_List[[j]] <- vList[which(vList$Subgroup.Number==viol_grp[j]), ]
   }
}
4

2 回答 2

2

第一个循环根本不需要。第一个循环的主体中没有变量i,因此您多次执行相同的任务。

要更改第二个循环,您可以执行以下操作(感谢 florel 的评论):

viol_list = lapply(viol_grp, function(x) vList[vList$Subgroup.Number==x,])
于 2012-11-01T20:12:43.207 回答
1

I imagine what you want to do is split vList into separate data frames, based on their Subgroup.Number. This will do it very cleanly:

viol_list<-split(vList,vList$Subgroup.Number)

But if you really want just the groups in viol_grp, you'll have to subset:

split(vList,vList$Subgroup.Number)[as.character(viol_grp)]

But, if viol_grp is just all the unique values of vList$Subgroup.Number, you don't need it.

于 2012-11-01T23:49:44.570 回答