Accessing a global vector component using a logical condition inside a function

Viewed 47

This function returns people's BMIs. The function the returns the BMIs does what I want but I cannot figure out how to print the WEIGHTS of those people that have a BMI over 25. I feel like I should be subscripting but how do I get that association? Thanks in advance.

heights_in_cms <- c(180, 165, 160, 193)
weights_in_kg  <- c(87, 58, 65, 100)

bmi_calc <- function(h, w) {
  bmi = w / (h / 100)^2
  cat("BMIs are:", bmi, "\n")

  for (b in bmi) {
    if (b > 25) {
      print(b)
    }
  }
}
bmi_seq <- bmi_calc(heights_in_cms, weights_in_kg)
2 Answers

using the same method as tmfmnk's answer you can get make the output of the function a dataframe if you prefer.

bmi_calc <- function(h, w) {
    bmi <- w/(h/100)^2
    return(data.frame(BMI=bmi[bmi > 25], Weight = w[bmi > 25]))
}

> bmi_calc(heights_in_cms, weights_in_kg)

       BMI Weight
1 26.85185     87
2 25.39062     65
3 26.84636    100

Edit: from the discussion in the comments

data.frame(Height.cm=heights_in_cms, Weight.kg=weights_in_kg, BMI=weights_in_kg*(heights_in_cms/100)^2)

  Height.cm Weight.kg     BMI
1       180        87 281.880
2       165        58 157.905
3       160        65 166.400
4       193       100 372.490

You can do:

bmi_calc <- function(h, w) {
 bmi = w/(h/100)^2
 print(list(`BMIs are:` = bmi[bmi > 25], 
            `Weights are:` = w[bmi > 25]))
}

bmi_calc(heights_in_cms, weights_in_kg)

$`BMIs are:`
[1] 26.85185 25.39062 26.84636

$`Weights are:`
[1]  87  65 100
Related