[R] Basic question on applying a function to each row of a da taframe
Sundar Dorai-Raj
sundar.dorai-raj at pdf.com
Mon Jun 9 16:02:14 CEST 2003
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:
> Another another neat way is:
>
>
>>DF <- data.frame(x=1:4, y=rep(1,4))
>>foo <- function(z,x,y)z[x]+z[y]
>>apply(DF,1,foo,x="x",y="y")
>
> 1 2 3 4
> 2 3 4 5
>
> or
>
>
>>DF <- data.frame(x=1:4, y=rep(1,4))
>>foo <- function(z)z<-x+y
>>foo(DF)
>
> [1] 2 3 4 5
>
>
> "Liaw, Andy" <andy_liaw at merck.com> wrote:
> Another neat way is:
>
> with(DF, foo(x, w))
>
> HTH,
> Andy
>
>
>>-----Original Message-----
>>From: peter leonard [mailto:pfleonard at hotmail.com]
>>Sent: Sunday, June 08, 2003 4:35 PM
>>To: r-help at stat.math.ethz.ch
>>Subject: [R] Basic question on applying a function to each row of a
>>dataframe
>>
>>
>>Hi,
>>
>>I have a function foo(x,y) and a dataframe, DF, comprised of
>>two vectors, x
>>& w, as follows :
>>
>>x w
>>1 1 1
>>2 2 1
>>3 3 1
>>4 4 1
>>
>>etc
>>
>>
>>I would like to apply the function foo to each 'pair' within DF e.g
>>foo(1,1), foo(2,1), foo(3,1) etc
>>
>>I have tried
>>
>>
>>>apply(DF,foo)
>>>apply(DF[,],foo)
>>>apply(DF[DF$x,DF$w],foo)
>>
>>
>>However, none of the above worked. Can anyone help ?
>>
>>Thanks in advance,
>>Peter
>>
>>______________________________________________
>>R-help at stat.math.ethz.ch mailing list
>>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>>
>
>
> ------------------------------------------------------------------------------
> Notice: This e-mail message, together with any attachments, cont... {{dropped}}
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
>
> ---------------------------------
>
>
> [[alternate HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
More information about the R-help
mailing list