0

I am writing a function made up of ifelse statements that depends on values in different columns of the that are the function's input:

counter=function(df){
df$total2=ifelse(df$x>=100,df$total+10,df$total)
df$total3=ifelse(df$y>=200,df$total2+10,df$total2)
}

It seems like the way I'm doing it is quite inefficient, but I haven't thought of a way to avoid overwriting the calculations.

But more pressingly, some of the dfs I'd like to use this function on do not have both column x and column y. When I run it on these, the following error sappears;

Error in $<-.data.frame(*tmp*, "total3", value = logical(0)) : replacement has 0 rows, data has 74

Is there a way to rewrite this to allow for dataframes that don't have all of the columns?

Thank you.

joran
  • 169,992
  • 32
  • 429
  • 468
Z_D
  • 797
  • 2
  • 12
  • 30
  • What is the behavior you desire when the columns are missing? Please provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output. – MrFlick Nov 25 '14 at 23:13
  • Side note: It looks like you could benefit from using `with` – Rich Scriven Nov 25 '14 at 23:14
  • I'd like it do not do anything - so if the column does not exist, the function basically ignores that command. – Z_D Nov 25 '14 at 23:17

1 Answers1

3

You can just use a standard if to see if a column exists

counter <- function(df) {
    if ("x" %in% names(df) ) {
        df<- transform(df, total2=ifelse(x>=100,total+10,total)
    }
    if("y" %in% names(df) ) {
        df <- transform(df, total3=ifelse(y>=200,total2+10,total2)
    }
}

Though it seems like your data might be in a "wide" format when it may be easier to work with in the a "tall" format. You might want to look into reshaping your data.

MrFlick
  • 195,160
  • 17
  • 277
  • 295