[R] For loop and using its index

Milan Bouchet-Valat nalimilan at club.fr
Fri Mar 9 14:54:37 CET 2012


Le vendredi 09 mars 2012 à 13:24 +0330, Hassan Eini Zinab a écrit :
> Dear All,
> 
> I have a data set with variables x1, x2, x3, ..., x20 and I want to
> create z1, z2, z3, ..., z20 with the following formula:
> 
> 
> z1 = 200 - x1
> z2 = 200 - x2
> z3 = 200 - x3
> .
> .
> .
> z20 = 200 - x20.
> 
> 
> I tried using a for loop and its index as:
> 
> for (i in 1:20) {
> z(i) = 200 - x(i)
> }
> 
> But R gives the following error message: "Error: could not find function "x"".
> 
> Is there any other way for a simple coding of my 20 lines of code?
This is very basic, please read the R intro.

The problem is that x(i) means "call function x with argument i", and no
function x exists (nor z, BTW). You need
x1 <- 1:10
x2 <- 11:20

for (i in 1:2) {
    assign(paste("z", i, sep=""), 200 - get(paste("x", i, sep="")))
}

But you'd better use a data frame to store these variables, in which
case you can do:
df <- data.frame(x1=1:10, x2=11:20)
for (i in 1:2) {
    df[[paste("z", i, sep="")]] <- 200 - df[[paste("x", i, sep="")]]
}

You can also create a new data frame:
xdf <- data.frame(x1=1:10, x2=11:20)
zdf <- 200 - xdf
colnames(zdf) <- paste("z", 1:2, sep="")
df <- cbind(xdf, zdf)


Regards



More information about the R-help mailing list