Skip to content

Basic question on applying a function to each row of a da taframe

4 messages · Liaw, Andy, Ramzi Feghali, Sundar Dorai-Raj +1 more

#
Another neat way is:

  with(DF, foo(x, w))

HTH,
Andy
------------------------------------------------------------------------------
Notice: This e-mail message, together with any attachments, cont... {{dropped}}
#
Yes, but very slow for this example when the data.frame gets large....

R> DF <- data.frame(x = rnorm(40000), y = rnorm(40000))
R> foo <- function(z, x, y) z[x] + z[y]
R> bar <- function(x, y) x + y
R> system.time(x <- apply(DF, 1, foo, x = "x", y = "y"))
[1] 6.94 0.04 7.37   NA   NA
R> system.time(y <- with(DF, bar(x, y))) # from A. Liaw
[1] 0.01 0.00 0.01   NA   NA
R> all(x == y)
[1] TRUE
R> system.time(z <- mapply("bar", DF[,1], DF[,2]))

Timing stopped at: 145.49 0.26 156.74 NA NA
R> # not sure why mapply doesn't work here...

Best,
Sundar
Ramzi Feghali wrote:
#
On Mon, 9 Jun 2003, Sundar Dorai-Raj wrote:

            
Indeed. However, it works when the function is not already vectorised, and
if the function is already vectorised it is unnecessary.


	-thomas