Add elements into a vector using loops and inputs

Asked

Viewed 702 times

2

I tried to write a simple command on R where the program asks 5 numbers for the user (input) and adds each one to a list. The problem is that the array is empty. I’ve tried lists too.

Follow the code below:

a <- c()

for(numero in 1:5){
  num <- as.numeric(readline(prompt = 'Numero: '))
  append(a,num)
}

print(a)

3 answers

4

vetor <- rep(NA, 5)

for (indice in seq_along(vetor)) {
  vetor[indice] <- as.numeric(readline(prompt = 'Numero: '))
}

print(vetor)

It is good practice in R not to create objects that expand in size; it is better to create the object already with the final size and use indexing to fill it.

  • And if I do not know a priori how much data I will store in the vector? For example, let’s assume that I will filter all averages with size may 15 of a given vector but I don’t know how many are a priori? In this case, the only way I see to store these values greater than 15 is to add them to an array. I don’t know if it’s because I’m more used to Python where it’s common to add elements in lists, but my reasoning is this.

  • 1

    This is a very long topic to answer here. If you read English, see chapter 2 of The R Inferno. Take advantage and read chapter 3, because it is also good to avoid loops in R. Well, read the whole book, which is excellent.

3

a <- c()

for(numero in 1:5){
  a <- append(a,numero)
}

print(a)

-You have to store the vector inside somewhere when you are running the "append". The function gives a return, this return needs to be stored somewhere.

  • In this case what I would like to do is different. I would like to add 5 numbers typed by the user in the list, and not simply number 1 to 5

  • I just managed to input and add elements to the array, disregard the previous question, thank you.

2

A way without cycles for is to read from stdin() with the function scan. Just pass the total numbers read in the argument n.

a <- scan(stdin(), what = character(), n = 5, quiet = TRUE)
a <- as.numeric(a)
print(a)

Note that scan reads numbers if the argument what does not change this. The problem is that if the user deceives and type something non-numerical the scan ends with error. If characters are read and then transformed into numbers this error no longer occurs.

Browser other questions tagged

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