遍历 data.frame 的行并将它们用作函数的输入
loop over rows of a data.frame and use them as input for a function
我的 foo()
函数的 input
值(a
和 b
)来自 expand.grid()
调用。
我想知道如何遍历 input
data.frame 的行,以便在每一轮中,input
的一行中的一个 a
和 b
=] data.frame 在 foo()
中用作命名 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
# .
# .
# .
假设 foo
函数比 b-a
更复杂,您可以使用 Map
.
Map(foo, input$a, input$b)
我的 foo()
函数的 input
值(a
和 b
)来自 expand.grid()
调用。
我想知道如何遍历 input
data.frame 的行,以便在每一轮中,input
的一行中的一个 a
和 b
=] data.frame 在 foo()
中用作命名 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
# .
# .
# .
假设 foo
函数比 b-a
更复杂,您可以使用 Map
.
Map(foo, input$a, input$b)