Skip to content
Prev 33115 / 398506 Next

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

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: