mercredi 29 novembre 2017

Conditional replace and delete column

I have a dataframe like so:

replaceanddropcolumn <- data.frame("avariable"=10,
                                   "bvariable"=5,
                                   "cvariable"=2)

  avariable bvariable cvariable
1        10         5         2

I want to use the grep function to find if 'cvariable' exists in the dataframe, then replace 'cvariable' with 'bvariable', and finally delete 'cvariable' from the dataframe. So the final output would look like this:

replaceanddropcolumn[["bvariable"]] <- replaceanddropcolumn[["cvariable"]]
replaceanddropcolumn[["cvariable"]] <- NULL

  avariable bvariable
1        10         2

The reason I need the if statement is that I want to keep the original dataframe if 'cvariable' does not exist eg. I have a dataframe like this:

replaceanddropcolumn <- data.frame("avariable"=10,
                                   "bvariable"=5,
                                   "dvariable"=14)

Thanks!

Aucun commentaire:

Enregistrer un commentaire