如何将data.frame的记录作为参数传递给函数?

时间:2015-01-19 05:09:05

标签: r

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

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])
  }

但这看起来很愚蠢。 有没有更好的方法来做这样的工作?

1 个答案:

答案 0 :(得分: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)