0

The input values (a and b) for my foo() function come from a expand.grid() call.

I was wondering how to loop over the rows of input data.frame such that at each round, one a and b from one row of input data.frame is used in foo() as a named list?

foo <- function(a, b) { 
  b-a
  }

input <- rev(expand.grid(b=1:4,a=1:4))

#   a b
#1  1 1  # at round one, `a = 1`, `b = 1`
#2  1 2
#3  1 3
#4  1 4  # at round four, `a = 1`, `b = 4`
#.  . .
#.  . .
#.  . .

foo(a=, b=)

# Desired output:

[[1]] `a=1, b=1` 
     [1]  0

[[2]] `a=1, b=2`
     [1]   1
# .
# .
# .
2
  • You don't need to do that,you would say foo(input$a, input$b) and R will automatically do it for all rows and return a vector of the same length as a and b. Commented Mar 23, 2021 at 4:58
  • @Elin, I was wondering if I could get a list output? Commented Mar 23, 2021 at 5:00

1 Answer 1

1

Assuming that the foo function is more complicated than just b-a you can use Map.

Map(foo, input$a, input$b)
Sign up to request clarification or add additional context in comments.

3 Comments

What if I need a data.frame output instead of a list output?
data.frame(a = mapply(foo, input$a, input$b))
It depends on how the actual function foo is written.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.