Как ввести числа в коллекцию в R с помощью цикла - PullRequest
0 голосов
/ 10 мая 2018

Я пытался ввести 9 номеров в коллекцию, а затем распечатать сумму коллекции, новичок в программировании на R.Но что-то не так с кодом, я не смог получить правильный результат.

homescore <- c()

for (homescore in 1:9) {
  score <- readline(prompt = "Enter Score: ")
  homescore <- append(homescore,score)
  homescore <- as.numeric(homescore)
}

1 Ответ

0 голосов
/ 10 мая 2018

Когда вы говорите for (homescore in 1:9), ваш цикл установит homescore <- 1 в начале первой итерации, homescore <- 2 в начале второй итерации и т. Д. Просто используйте for (i in 1:9) вместо.

# works:
homescore <- c()
for (i in 1:9) {
  score <- readline(prompt = "Enter Score: ")
  homescore <- append(homescore,score)
  homescore <- as.numeric(homescore)
}

# better - convert the input *before* adding it to your vector
# this way we don't risk converting the whole vector back and forth
homescore <- c()
for (i in 1:9) {
  score <- readline(prompt = "Enter Score: ")
  homescore <- append(homescore, as.numeric(score))
}

# much better - pre-allocate homescore instead of "growing" it each time
# change the loop to be get the length from the pre-allocated vector
homescore <- numeric(9)
for (i in seq_along(homescore)) {
  score <- readline(prompt = "Enter Score: ")
  homescore[i] <- as.numeric(homescore)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...