Home > Software design >  for loop-only answer find the mean and maximum difference between elements in a vector in R
for loop-only answer find the mean and maximum difference between elements in a vector in R

Time:08-08

how find the mean and maximum difference between elements of the vector (numbers) using loops in r:

num <- sample(1:1000,50,replace = TRUE)
count <- 0
for (i in 1:length(num)) {
if(i%%4==0){
count <- count 1
numbers <- c(num[num%%4==0])
}
}
print(count)

for example : numbers <- c(700, 748, 364, 288, 896, 960, 624, 712, 340, 564, 828, 68, 948, 524)

without using loops:

diff(numbers) [1] 48 -384 -76 608 64 -336 88 -372 224 264 -760 880 -424

max(diff(numbers)) [1] 880

I want the same solution using loops

CodePudding user response:

You can try this

n_mean <- 0
n_diff <- 0
for(i in 1:length(num)){
    n_mean <- n_mean   num[i]/length(num)
    if(num[i 1]- num[i] > n_diff & i != length(num)) n_diff <- num[i 1]- num[i]
    
}
  • output
> n_mean
[1] 487.02
> n_diff
[1] 576
  • data
num <- c(58L, 355L, 154L, 427L, 608L, 314L, 890L, 35L, 572L, 316L, 765L, 
574L, 788L, 476L, 286L, 240L, 708L, 387L, 946L, 125L, 154L, 503L, 
949L, 249L, 676L, 642L, 833L, 88L, 577L, 928L, 756L, 905L, 20L, 
291L, 307L, 675L, 110L, 580L, 748L, 253L, 550L, 27L, 100L, 222L, 
382L, 928L, 525L, 913L, 508L, 928L)
  •  Tags:  
  • r
  • Related