Adding a row using Apply

Hello everyone,

I would need to add a row containing a function (MBI) to the matrix. I am using apply function, but it does not work...

BMI <- function(weight, height) {
vyp <- weight/(height^2)
return(vyp)
}
weight <- c(60,72,57,90,65,72)
height <- c(1.75,1.8,1.65,1.9,1.74,1.91)

table1 <- rbind(weight,height)
table1

colnames(table1) <- c("person1","person2","person3",
"person4","person5","person6")

mat1 <- as.matrix(table1)

apply(table1, 2, BMI)

Because you have some character and numeric data, I recommend storing your data in a data frame instead of a matrix. And storing each variable (height, weight, person) in columns instead of rows.

You don't really need to use apply in this case. But I gave example of BMI calculation with and without an apply() statement.

calc_BMI <- function(weight, height) {
  vyp <- weight/(height^2)
  return(vyp)
}

calc_BMI2 <- function(weight_height) {
  # calc BMI from a vector that contains both weight and height as elements 1, 2
  # apply() needs a function that accepts one argument
  weight <- weight_height[1]
  height <- weight_height[2]
  vyp <- weight/(height^2)
  return(vyp)
}


weight <- c(60,72,57,90,65,72)
height <- c(1.75,1.8,1.65,1.9,1.74,1.91)
id <- c("person1","person2","person3",
        "person4","person5","person6")

# this is a better way to store the data
table1 <- data.frame(id, weight, height)

table1$BMI <- calc_BMI(table1$weight, table1$height)

# calc instead with an apply
table1$BMI2 <- apply(table1[, c("weight", "height")], 1, calc_BMI2)

table1
#>        id weight height      BMI     BMI2
#> 1 person1     60   1.75 19.59184 19.59184
#> 2 person2     72   1.80 22.22222 22.22222
#> 3 person3     57   1.65 20.93664 20.93664
#> 4 person4     90   1.90 24.93075 24.93075
#> 5 person5     65   1.74 21.46915 21.46915
#> 6 person6     72   1.91 19.73630 19.73630

Created on 2021-09-10 by the reprex package (v1.0.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.