Java Mailing List Archive

http://www.r-help.com/

Home » R Help for Statistical Computing »

Re: [R] Looping column names

Rui Barradas

2012-01-28

Replies: Find Java Web Hosting

Author LoginPost Reply
Hello,

> But I keep getting this error:
> Error in model.frame.default(formula = i ~ GC, data = gc2) :
>  variable lengths differ (found for 'GC')

Simple: you are using a variable's name, not the variable itself
Your code corrected should be


res <- NULL
for(i in colnames(gc2[,-1])){
 temp <- loess(gc2[, i]~GC,gc2) # fit the vector, NOT it's name
 temp2 <- predict(temp)
 res <- cbind(res, temp2)
}
colnames(res) <- colnames(gc2[,-1])
res

But even better, without the loop,

apply(gc2[,-1], 2, function(x) predict(loess(x~GC, data=gc2)))

> For the second step (dividing column after I divide gc2/res), I really am
> unsure of where to even start. I would guess that it would be something
> along the lines of
> for(i in colnames(gc[,-1])){
>      res[i]/res[i+2]}
> But that would only get me A/C, then B/D, etc.

Create indexes on the columns:


res2 <- gc2[, -1]/res
n <- ncol(res2)

ainx <- seq(1, n, 3)
binx <- seq(2, n, 3)
cinx <- seq(3, n, 3)

res2[, ainx]/res2[, cinx]
res2[, binx]/res2[, cinx]

One final note.
You've named your data.frame 'gc' but since this is the name of a function
in R, it's a bad choice.
I've renamed it 'gc1'.

Hope this helps,

Rui Barradas



--
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help@(protected)
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
©2008 r-help.com - Jax Systems, LLC, U.S.A.