Adding new columns

Assignment operator (=) in DataSailr creates or update a column that is corresponding to left hand side variable. If the column does not exist yet, new column is created. If the column already exists, it is updated with new values.

Example: Calculating body mass index (BMI)

In this example, I will create BMI column and categorize subjects using the BMI. BMI is calculated using body weight and height. The fomula is BMi = Weight / (Height * Height). (Weight is in kilograms, and Height is in meters)

BMI categorization is as follows,

Original data

df = data.frame(us=c(1,1,1,1,1,0,0,0,0), weight=c(150,120,175,160,240,80,60,50,90), height=c(70,60,60,70,65,1.7,1.6,1.7,1.9))

Sailr Code

code = '
// When calculating BMI, multipllication of 703 is required in the U.S. (using lbs and inches)
// In other countires using meter and kilograms in units, 703 should be omitted.
if( us == 1){
  bmi = weight / (height * height) * 703
}else{
  bmi = weight / (height * height)
}

if(bmi >= 40){ weight_level = . } 
else if( bmi >= 35 ){ weight_level = 3 } 
else if( bmi >= 30 ){ weight_level = 2 } 
else if( bmi >= 25 ){ weight_level = 1 }
else if( bmi >= 20 ){ weight_level = 0 }
else { weight_level = . }
'

Execute

library(datasailr)
sail(df, code)
##   us weight height      bmi weight_level
## 1  1    150   70.0 21.52041            0
## 2  1    120   60.0 23.43333            0
## 3  1    175   60.0 34.17361            2
## 4  1    160   70.0 22.95510            0
## 5  1    240   65.0 39.93373            3
## 6  0     80    1.7 27.68166            1
## 7  0     60    1.6 23.43750            0
## 8  0     50    1.7 17.30104           NA
## 9  0     90    1.9 24.93075            0