tags:

views:

102

answers:

2

Hi all,

I am looking to recode a large number of variables, and figure I can probably use some sort of loop to do so. What throws me is how to programmatically name each variable (I just want to keep the var name and append ".rc".

Here is an example. Lets say I have a set of variables, var.1 to var.5. I am looking to create a new variable in my dataframe that is var.1.rc <- var.1 / sum(var.1 to var1.5). Ill do the same for the next variable, and so on.

I am new to R but this would be a HUGE step forward for me.

Is it possible. Best ways to do it? Any help will be much appreciated!

Regards,

Brock

+2  A: 

You could try the following loop.

Here the eval(parse(text="")) allows you evaluate a pasted together string containing the various static and dynamic portions of the expression to create each new variable.

for (i in 1:5) {
 X<-paste("var.",i,".rc<-var.",i,"/(var.1+var.2+var.3+var.4+var.5)",sep="")
 eval(parse(text=X))
}
Brian
+9  A: 

If I understand you correctly, there is actually a pretty easy way to do this. Assuming your original data frame is called dat, you can do this:

dat.rc <- dat/rowSums(dat)
names(dat.rc) <- paste(names(dat), ".rc", sep="")
dat <- data.frame(dat,dat.rc)
Fojtasek
An elegant approach, I must admit... =)
aL3xa