[R] [FORGED] Need Help - R Programming - Using iteration value to change field names for processing for every iteraion

Rolf Turner r.turner at auckland.ac.nz
Tue May 30 10:44:02 CEST 2017


On 30/05/17 19:02, Vijaya Kumar Regati wrote:
> Hi,
> 
> I am new to R programming, I am trying to work on below requirement. But could not achieve desired result.
> Appreciate if someone can help me on this :
> 
> test dataframe :
>    Day1.balc Day2.balc Day3.balc Day4.balc
> x       100        20        30        40
> y       100        10        10        10
>> class(test)
> [1] "data.frame"
> 
> My Goal is to accomplish :
> Day2.balc <- Day2.balc + Day1.balc
> Day3.balc <- Day3.balc + Day2.balc
> .
> .
> .
> Day30.balc <- Day30.balc + Day29.balc
> 
>      # Testing for first 4 days
>      for (i in 1:4 ) {
>      test$Day[i].balc <- test$Day[i].balc + test$Day[i-1].balc
>      }
> 
> I identified the line I have written inside the loop is not the correct one, can someone help me how I can use iteration value(i), for every iteration, as a basis for changing field names since field consists of 1,2,3... for each different day( Day1.balc Day2.balc Day3.balc Day4.balc etc.,).

(1) Learn some R (read "An Introduction to R" from the R web page; 
manuals).  Don't use iteration when you don't need to; i.e. use 
vectorised operations whenever possible.  (Much faster and clearer.)

(2) Distinguish between data frames and matrices; they are *NOT* the 
same thing!  What you need here are matrices.

(3) I think this will work for you:

     M <- as.matrix(test)
     Mnew <- cbind(0,M[,-ncol(M)]) + M

cheers,

Rolf Turner

-- 
Technical Editor ANZJS
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276



More information about the R-help mailing list