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.