vendredi 14 juillet 2017

R: using ifelse statement to check if column exists, then perform calculation

I want to create a function that first looks to see if a column exists, then if that column exists, perform a calculation, and if not, then keep the original variable.

Here is some data and the approach I was thinking:

thisdata <-  data.frame(vara = seq(from = 1, to = 20, by = 2)
                     ,varb = seq(from = 1, to = 20, by = 1))

thisdata$varc <- with(thisdata, ifelse("vard" %in% colnames(thisdata), vara - vard, vara))

So obviously 'vard' is not in the dataframe, however I don't get the original 'vara' variable back for my new variable (only '1'). Of course, I might have another dataframe with the 'vard' variable.

Appreciate the help!

Aucun commentaire:

Enregistrer un commentaire