0

Anyway, I simplfy my question. We have a dataframe like this:

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.
}

So I need to use f function like the following:

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

I know I can use for-loop as the following:

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

But it seems stupid and ugly. Is there any better way to do such work?

kanpu
  • 251
  • 2
  • 10
  • What are you expecting as a result of the function `f` ? – Rich Scriven Jan 19 '15 at 05:13
  • This previous question might be worth a read: [how to call apply-like function on each row of dataframe with multiple arguments from each row of the df](http://stackoverflow.com/questions/15059076/r-how-to-call-apply-like-function-on-each-row-of-dataframe-with-multiple-argum/15059295) – thelatemail Jan 19 '15 at 06:04

1 Answers1

1

one option would be to vectorize the function f which works nicely in some cases (i.e. vector return values), as in:

# 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)

but not in others (i.e. compound return values [lists]), as in:

# 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)
Jthorpe
  • 9,756
  • 2
  • 49
  • 64