【问题标题】:How to pass a record of data.frame to a function as parameter? [duplicate]如何将 data.frame 的记录作为参数传递给函数? [复制]
【发布时间】:2015-03-17 01:59:55
【问题描述】:

无论如何,我简化了我的问题。我们有一个这样的数据框:

dt <- data.frame(x=c(1,2,3), y=c("a", "b", "c"))
f <- function(x, y){
  #f is a function that only take vector whose length is one.
}

所以我需要像下面这样使用 f 函数:

  f(1, "a")
  f(2, "b")
  f(3, "c")

我知道我可以像下面这样使用 for 循环:

  for (i in 1:3) {
    f(dt$x[i], dt$y[i])
  }

但它看起来既愚蠢又丑陋。 有没有更好的方法来做这样的工作?

【问题讨论】:

标签: r


【解决方案1】:

一种选择是vectorize 函数f 在某些情况下工作得很好(即向量返回值),如下所示:

# returs a vector of length 1
f = function(x,y)paste(x[1],y[1])
# returs a vector with length == nrow(dt)
Vectorize(f)(dt$x,dt$y)

# returs a vector of length 2
f = function(x,y)rep(x[1],1)
# returns a matrix with 2 rows and nrow(dt) columns
Vectorize(f)(dt$x,dt$y)

f = function(x,y)rep(y[1],x[1])
# returns a list with length == nrow(dt)
Vectorize(f)(dt$x,dt$y)

但不是在其他情况下(即复合返回值 [列表]),如:

# returns a list
f = function(x,y)list(x[1],y[1])
# returns a matrix but the second row is not useful
Vectorize(f)(dt$x,dt$y)

【讨论】:

  • 对于多列的数据框,使用do.call(Vectorize(f),dt)会比较方便
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-06
  • 2022-01-09
  • 1970-01-01
  • 2013-01-27
  • 2015-11-08
相关资源
最近更新 更多