【问题标题】:loop over rows of a data.frame and use them as input for a function遍历 data.frame 的行并将它们用作函数的输入
【发布时间】:2021-06-19 18:25:58
【问题描述】:

我的foo() 函数的input 值(ab)来自expand.grid() 调用。

我想知道如何循环 input data.frame 的行,以便在每一轮中,input data.frame 的一行中的一个 abfoo() 中使用一个名为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(input$a, input$b) ,R 会自动对所有行执行此操作,并返回与 a 和 b 长度相同的向量。
  • @Elin,我想知道我是否可以获得list 输出?

标签: r function dataframe loops lapply


【解决方案1】:

假设foo 函数比b-a 更复杂,您可以使用Map

Map(foo, input$a, input$b)

【讨论】:

  • 如果我需要data.frame 输出而不是list 输出怎么办?
  • data.frame(a = mapply(foo, input$a, input$b))
  • 这要看实际函数foo是怎么写的。
猜你喜欢
  • 2020-11-02
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
相关资源
最近更新 更多