[R] use of tapply?

François Pinard pinard at iro.umontreal.ca
Fri Dec 30 01:58:23 CET 2005


[tom wright]

> I'm still learning how to program with R and I was hoping someone 
> could take the time to show me how I can rewrite this code?

I'll try! :-)

>data.intersects<-data.frame(
>    x=c(0.230,0.411,0.477,0.241,0.552,0.230),
>    y=c(0.119,0.515,0.261,0.431,0.304,0.389),
>    angle=vector(length=6),
>    length=vector(length=6),
>    row.names=c('tbr','trg','dbr','dbg','pbr','pbg'))


>calcDist<-function(x,y){
>    #calcualates distance from origin (C)
>    origin<-data.frame(x=0.34,y=0.36)
>    dx<-origin$x-x
>    dy<-origin$y-y

>    length<-sqrt(dx^2+dy^2)
>    angle<-asin(dy/length)
>    return(list('length'=length,'angle'=angle))
>}

>for(iLoc in 1:length(data.intersects[,1])){
>    result<-calcDist(data.intersects[iLoc,]$x,data.intersects[iLoc,]$y)
>    data.intersects[iLoc,]$angle<-result$angle
>    data.intersects[iLoc,]$length<-result$length
>}

Using `di' instead of `data.intersects' for short:

    di <- data.frame(x=c(0.230, 0.411, 0.477, 0.241, 0.552, 0.230),
                     y=c(0.119, 0.515, 0.261, 0.431, 0.304, 0.389),
                     row.names=c('tbr', 'trg', 'dbr', 'dbg', 'pbr', 'pbg'))
    di.c <- with(di, data.frame(x=x-0.34,  y=y-0.36))
    di$length <- with(di.c, sqrt(x^2 + y^2))
    di$angle <- with(di.c, atan2(y, x))

-- 
François Pinard   http://pinard.progiciels-bpi.ca




More information about the R-help mailing list