[R] Looping column names

Rui Barradas ruipbarradas at sapo.pt
Sat Jan 28 06:14:05 CET 2012


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



--
View this message in context: http://r.789695.n4.nabble.com/Looping-column-names-tp4334211p4335454.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list