mardi 24 août 2021

Using Conditional Statement to Evaluate Column, Calculate, and Create New Colum in Dataframe

I've been working with combinations of if/else if statement for a bit and can't seem to get the desired outcome. I want the code to look at two columns in the dataframe top and bottom. If the data is missing for either, the new column should equal the value that is not 0. If both top and bottom values are present, the column should be populated with the average. Also, if both values are 0, the new value will also be 0.

df$new <- if (df$top > 0 
            && df$bottom == 0){
            (df[["top"]])  
} else if (df$top == 0 
          && df$bottom > 0){
          (df[["bottom"]])  
} else if (df$top > 0 
          && df$bottom > 0){
          (df[["top"]] + df[["bottom"]])/2
}

Currently, when I run the code it's creating a new column new but only populating with (top + bottom)/2 values.

Aucun commentaire:

Enregistrer un commentaire