如何减少R中的条件嵌套循环

如何减少R中的条件嵌套循环,r,loops,R,Loops,我正在使用Reddit JSON API和R从Reddit中删除一些注释。由于数据没有平面结构,提取它有点棘手,但我找到了一种方法。为了让大家了解我要做的事情,这里有一个简单的例子: x = "http://www.reddit.com/r/funny/comments/2eerfs/fifa_glitch_cosplay/.json" # example url rawdat = readLines(x,warn=F) # reading in the data rawdat = fr

我正在使用Reddit JSON API和R从Reddit中删除一些注释。由于数据没有平面结构,提取它有点棘手,但我找到了一种方法。为了让大家了解我要做的事情,这里有一个简单的例子:

x = "http://www.reddit.com/r/funny/comments/2eerfs/fifa_glitch_cosplay/.json" # example url
rawdat   = readLines(x,warn=F) # reading in the data
rawdat   = fromJSON(rawdat) # formatting
dat_list = repl = rawdat[[2]][[2]][[2]] # this will be used later
sq       = seq(dat_list)[-1]-1 # number of comments
txt      = unlist(lapply(sq,function(x)dat_list[[x]][[2]][[14]])) # comments (not replies)

# loop time:

for(a in sq){
  repl  = tryCatch(repl[[a]][[2]][[5]][[2]][[2]],error=function(e) NULL) # getting replies all replies to comment a

  if(length(repl)>0){ # in case there are no replies
    sq  = seq(repl)[-1]-1 # number of replies
    txt    = c(txt,unlist(lapply(sq,function(x)repl[[x]][[2]][[14]]))) # this is what I want

    # next level down
    for(b in sq){
      repl  = tryCatch(repl[[b]][[2]][[5]][[2]][[2]],error=function(e) NULL) # getting all replies to reply b of comment a

      if(length(repl)>0){
        sq  = seq(repl)[-1]-1
        txt    = c(txt,unlist(lapply(sq,function(x)repl[[x]][[2]][[14]])))   
      }
    }
  }
}
在上面的例子中,获取所有评论,对每个评论的第一级回复和第二级回复,即对每个回复的回复,但这可能会深入得多,因此我试图找出一种有效的处理方法。要手动实现这一点,我需要做的是:

1从最后一个循环复制以下代码:

for(b in sq){
  repl  = tryCatch(repl[[b]][[2]][[5]][[2]][[2]],error=function(e) NULL)

  if(length(repl)>0){
    sq  = seq(repl)[-1]-1
    txt    = c(txt,unlist(lapply(sq,function(x)repl[[x]][[2]][[14]])))   
  }
}
2将该代码粘贴到以txt=。。。并将循环中的b更改为c

3重复此过程大约20次,以确保捕获所有内容,正如您可以想象的那样,这会创建一个巨大的循环。我希望一定有办法把这个环折起来,让它更优雅

如果您对如何改进这个循环有任何想法,如果您能分享您的想法,我将不胜感激


非常感谢

我相信这会在这里得到一个很好的答案,但是你应该知道还有一个codereview.stackexchange.com专门针对这样的问题。谢谢@ssdecontrol,我对codereview网站一无所知,所以我将在那里发布这个问题,但我现在也将它留在这里。这个问题在这里重新发布: