Saving R code in a list

I make a number of conditional assignments in most of the data. (here is an example with compiled numbers)

x<-data.frame(average=c(2,6,7,4,9),bill=c(3,7,5,2,5),averagebill=c(8,2,5,3,4),averagecost=c(1,6,4,7,8),xcount=c(4,5,2,8,1),ycount=c(7,4,2,8,8))

In pseudocode, a short version of what I am doing:

if xcount > 3
   newaverage<-averagecost
   newbill<-averagebill
else if ycount > 3
   newaverage<-average
   newbill<-bill

One way to do this is with ifelse () nested functions

y<-within(x, { newaverage<-ifelse(xcount > 3,averagecost,
                      ifelse(ycount > 3,average,NA))

               newbill<-ifelse(xcount > 3,averagebill,
                      ifelse(ycount > 3,bill,NA))
    })

This works, but my actual code assigns a lot more than two variables, and it becomes repetitive and hard to read. In addition, ifelse () is not required. This is another way:

y<-within(x, { newaverage[xcount > 3] <- averagecost[xcount > 3]
               newbill[xcount > 3] <- averagebill[xcount > 3]

               newaverage[xcount <= 3 & ycount > 3] <- average[xcount <= 3 & ycount > 3]
               newbill[xcount <= 3 & ycount > 3] <- bill[xcount <= 3 & ycount > 3]
    })

This is better, but "xcount <= 3 and ycount> 3" is still too repeated. I found that I can simplify the list:

z<-list("xcon"=x$xcount>3,"ycon"=x$xcount<=3 & x$ycount>3)
y<-within(x, { newaverage[z[["xcon"]]] <- averagecost[z[["xcon"]]]
               newbill[z[["xcon"]]]    <- averagebill[z[["xcon"]]]

               newaverage[z[["ycon"]]] <- average[z[["ycon"]]]
               newbill[z[["ycon"]]]    <- bill[z[["ycon"]]]
    })

As you can see, it is easier to read and simplify. If I need to change the conditions, I just edit the list once instead of going through each task.

, ? , , , , . ?

edit: x $

+3

All Articles