Loop to fill data returns only the last values

Asked

Viewed 50 times

-2

I need to create a program with functions, but I could not fix the repetition commands.

Program: Read the number of students in the classroom. For each of the n students you must do the following: Read the name, the notes of 3 tests P1, P2 and Psub and the notes of 3 exercises-program EP1, EP2 and EP3. Then calculate and print P (the average of the tests) and EP (the average of the exercises-program), MF (the final grade) and finally the situation (approved, in recovery or failed in note).

I am fine at the beginning, but my program when inserting a repeat command, and when putting to print, it only print the last data inserted

n <- as.numeric(readline("Digite o numero de alunos: "))

for (i in 1:n) {
  nome <- readline("Digite o nome do aluno: ")

  p1<- as.numeric(readline("Digite a nota da P1: "))
  p2<- as.numeric(readline("Digite a nota da P2: "))
  p3<- as.numeric(readline("Digite a nota da P3: "))
}

print(paste0(n, nome, p1, p2, p3))

1 answer

2

The way you wrote it, every turn of the loop the name objects, P1, P2 and P3 have their values rewritten. Rotate lenght(nome) (or P1, etc.), you will see that it contains only one value. Create vectors or a date.frame of the appropriate size to receive the data before the loop:

n <- as.numeric(readline("Digite o numero de alunos: "))

dados <- data.frame(matrix(nrow = n, ncol = 4))
names(dados) <- c("nome", "p1", "p2", "p3")

for (i in 1:n) {
  dados$nome[i] <- readline("Digite o nome do aluno: ")
  dados$p1[i] <- as.numeric(readline("Digite a nota da P1: "))
  dados$p2[i] <- as.numeric(readline("Digite a nota da P2: "))
  dados$p3[i] <- as.numeric(readline("Digite a nota da P3: "))
}

print(dados)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.