0
votes

I'm a programming novice trying to calculate some ideal body weight numbers from a large dataset of height, sex, and actual body weight. I would like to create a new column in the data frame (df$ibw) based on the ideal body weight calculation for each individual.

Ideal body weight (IBW) is calculated differently for men and women.

For males... IBW = 50 + 0.91((Height in cm)-152.4)

For females... IBW = 45.5 + 0.91((Height in cm)-152.4)

set.seed(1000)

weight <- rnorm(10, 100, 20) # weight in kilograms
sex <- (0:1) # 0 for Male, 1 for Female
height <- rnorm(10, 150, 10) # height in centimeters


df <- data.frame(weight, sex, height)
df

I've been reading other posts using if else statements and other conditional formats, but I keep getting errors. This is something I will be frequently doing for datasets and I'm trying to figure out the best way to accomplish this task.

3
what about df$IBW <- 0.91 * (df$height - 152.4) + 50 - 4.5 * df$sex ?etienne

3 Answers

1
votes

This should do it

df$ibw <- ifelse(df$sex == 0, 50 + 0.91 * (df$height - 152.4),
             45.5 + 0.91 * (df$height - 152.4))
1
votes

You could use a one-liner:

df$IBW <- 0.91 * (df$height - 152.4) + 50 - 4.5 * df$sex

df
#       weight sex   height      IBW
# 1   91.08443   0 140.1757 38.87591
# 2   75.88287   1 144.4551 38.27015
# 3  100.82253   0 151.2138 48.92057
# 4  112.78777   1 148.7913 42.21606
# 5   84.26891   0 136.6396 35.65803
# 6   92.29021   1 151.7006 44.86352
# 7   90.48264   0 151.5508 49.22722
# 8  114.39501   1 150.2493 43.54288
# 9   99.62989   0 129.5341 29.19207
# 10  72.53764   1 152.1315 45.25570

If sex = 1 (female), then we just substract 50 - 45.5 = 4.5

1
votes

Something like this should work.

df$ibw <- 0 
df[df$sex == 0,]$ibw <- 50 + 0.91*df[df$sex == 0,]$height - 152.4
df[df$sex == 1,]$ibw <- 45.5 + 0.91*df[df$sex == 1,]$height - 152.4