[R] For loop and using its index

Petr Savicky savicky at cs.cas.cz
Fri Mar 9 15:36:37 CET 2012


On Fri, Mar 09, 2012 at 01:24:00PM +0330, Hassan Eini Zinab wrote:
> 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)
> }

Hi.

Try this.

  x <- 21:40
  z <- 200 - x
  x[1] # [1] 21
  x[2] # [1] 22
  z[1] # [1] 179
  z[2] # [1] 178

Hope this helps.

Petr Savicky.



More information about the R-help mailing list