Search code examples
riteratoradditioncol

R: Adding new columns iteratively


I am trying to write a code which evaluates 3 columns of my dataframe rowwise and iteratively, and produces a new column with the minimum value found in the evaluation. Here's what my data looks like:

  mydata
  Jan  Feb  Mar  Apr  May  Jun  Jul  Aug
1 .25  .50  .50  .25  .75  .50  .25  .25
2 .75  .25  .75  .50  .25  .50  .50  .50
3 .50  .50  .50  .50  .25  .25  .75  .25
4 .25  .75  .75  .50  .75  .75  .75  .75

And this is what i want to produce:

  mydata
  Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  -Mar  ...  -Aug
1 .25  .50  .50  .25  .75  .50  .25  .25  .25   ...  .25
2 .75  .25  .75  .50  .25  .50  .50  .50  .25   ...  .50
3 .50  .50  .50  .50  .25  .25  .75  .25  .50   ...  .25
4 .25  .75  .75  .50  .75  .75  .75  .75  .25   ...  .75

With -Mar showing the minimum valuess of (Jan:Mar), -Apr showing the minimum value of (Feb:Apr), and so on.

I tried the following:

> for (i in 3:8)

{ 
  Newcolname <- as.name(paste("-",i,sep=""))
  mydata$Newcolname<- pmin(mydata[,i-2],mydata[,i-1],mydata[,i])
}

But this only gives my 1 new column, containing the minimum values for (jun:aug), being the last 3 columns of mydata. What I want instead is 5 new columns as depicted above, but I cannot figure out how to do this. Anybody?

Please let me know if i'm not clear. Thanks in advance!


Solution

  • You can try this:

    for (i in 3:8) {
      Newcolname <- paste0("-", names(mydata)[i]) 
      mydata[[Newcolname]] <- pmin(mydata[,i-2],mydata[,i-1],mydata[,i])
    }
    

    where names(mydata)[i] is the i'th name from mydata, e.g. names(mydata)[3] is Mar. To create a new column you have to put the variable in [[ ]]. The way you had it, it created a new column named Newcolname.