[R] Help with creating some loops

Vadlamani, Satish {FLNA} SATISH.VADLAMANI at fritolay.com
Fri Oct 30 16:24:32 CET 2009

In general, how to I cast a character to the class that I am trying to change.

For example, if I have a data frame df1. df1 has a column x. suppose I want to a substring of x (the first 3 chars). Then I want to do something like

df1$new = substring(of x)

Data frame df1

Now df1$new should be


From:   Vadlamani, Satish {FLNA}
Sent:   Friday, October 30, 2009 8:40 AM
To:     R-help at r-project.org
Subject:        Help with creating some loops

Hi All:

I have a data frame called all_corn. This has 31 columns. The first column is a character key. The next 15 columns (stat1,stat2,...,stat15) are the statistical forecast. The last 15 columns (sls1,sls2,...,sls5) are actual sales.
I want to calculate textbook tracking signal and cuulative percent error.

1) I am showing some of the calculations below. How can I make a loop out of this instead of manually doing this 15 times?
2) Once All these calculations are done, how do I put all these columns (err1,err2, etc.) into the same data frame?



cum_sls1 <- sls1
err1 <- sls1-stat1
cum_err1 <- sls1-stat1
cum_abs_err1 <- abs(err1)
mad1 <- abs(cum_err1)/1
cum_pct_err1 <- (ifelse(cum_sls1 > 0, cum_err1/cum_sls1, 1))*100
ts1 <- ifelse(mad1 > 0, cum_err1/mad1, 0)

cum_sls2 <- cum_sls1 + sls2
err2 <- sls2-stat2
cum_err2 <- cum_err1 + sls2-stat2
cum_abs_err2 <- cum_abs_err1 + abs(err2)
mad2 <- cum_abs_err2/2
cum_pct_err2 <- (ifelse(cum_sls2 > 0, cum_err2/cum_sls2, 1))*100
ts2 <- ifelse(mad2 > 0, cum_err2/mad2, 0)

More information about the R-help mailing list