Home > database >  Getting an error in using foreach in R - no applicable method for 'filter' applied to an o
Getting an error in using foreach in R - no applicable method for 'filter' applied to an o

Time:12-02

I am getting in using foreach. Can someone please explain the reason.

Error in UseMethod("filter") : 
  no applicable method for 'filter' applied to an object of class "list"
library(dplyr)
library(doFuture)
library(foreach)

# PARALLEL PROCESSING
registerDoFuture()
plan(multicore, workers = 1)

tbl <- tibble(id = 1:10)

res <- foreach(ID = 1:10) %do%
  tbl %>% filter(id == ID)

# it simply works with for loop
l = list()
for (ID in 1:10)
{
  l[[ID]] <- tbl %>% filter(id == ID)
}

CodePudding user response:

You need to be careful of operator precedence here. Enclose your loop body here in braces to be clear

res <- foreach(ID = 1:10) %do%
  { tbl %>% filter(id == ID) } 

Otherwise you are running

res <- (foreach(ID = 1:10) %do% tbl) %>% 
  filter(id == ID)

which isn't what you seem to want in this case.

  • Related