# use of tapply?

 Classic List Threaded
2 messages
Reply | Threaded
Open this post in threaded view
|

## use of tapply?

 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? Many thanks Tom 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 } ______________________________________________ [hidden email] mailing list https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Reply | Threaded
Open this post in threaded view
|

## Re: use of tapply?

 [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______________________________________________ [hidden email] mailing list https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide! http://www.R-project.org/posting-guide.html