-4

Hello i have a 3 x 2 with the age and the weight.

I have to find the maximum of the age and the weight with a loop.

can somebody help me?

Karrob
  • 1
  • 2

2 Answers2

2

Doing this with a loop in R is not how one would usually approach this but here is a way to achieve the colmax using a for loop :

set.seed(1)
# matrix
m <- matrix(rnorm(6), nrow = 3)
# storage for colmax
l <- NULL
# for loop across columns
for( i in 1:ncol(m)){
  l[i] <- max(m[,i])
}
# colmax
l
[1] 0.1836433 1.5952808



fabla
  • 1,806
  • 1
  • 8
  • 20
1

You don't need a loop R has vectorised functions

sample_matrix <- matrix(c(30,22,40,70,80,50),nrow = 3)


apply(sample_matrix,MARGIN = 2,FUN = max)
#> [1] 40 80

Created on 2020-01-05 by the reprex package (v0.3.0)

Bruno
  • 4,109
  • 1
  • 9
  • 27
  • our teacher wrote in the assigment we have to do it with a loop.... – Karrob Jan 05 '20 at 16:01
  • 2
    Hi @Bruno, kinda common misconception. The `apply()` function is not vectorized. You can read about it here : [R Inferno](http://www.burns-stat.com/pages/Tutor/R_inferno.pdf) or in this great SO post here : [Is the “*apply” family really not vectorized?](https://stackoverflow.com/questions/28983292/is-the-apply-family-really-not-vectorized) – fabla Jan 05 '20 at 16:42
  • 2
    @Base_R_Best_R That is actually really interesting, I am on a new quest to write less tidyverse code, this was a book that my professor recommended back in 2017 I guess I should have paid more attention. I know that ColMeans should be vectorized... well Thanks! – Bruno Jan 05 '20 at 16:51