Deependra Dhakal Deependra Dhakal - 2 months ago 14
R Question

How is "for" loop written to label elements of a numeric vector in R

I tried to write a loop that would, say, return me a vector of ten numeric entries. It went well, until i attempted to label each element of the output generated by the block with another line. The naming is supposed to produce each entry with their unique label characters: "number"[n] where n is number in the sequence of repeats which was used in the generation of numeric vector.

multiples <- c()
i <- c(1:10)
for (n in i) {
print (n * 10)
multiples[n] <- n * 10
names(multiples)[n] <- "number"[n]
}
multiples


The execution is successful but the result is not what i'm expecting. Is there a way to name the elements correctly using the same
for
loop?

Answer

I dont think you need loop here.

Are you trying to do this?

i <- 1:10
multiples <- i * 10
names(multiples) <- paste0("number", i)

multiples
#number1  number2  number3  number4  number5  number6  number7  number8  
#  10       20       30       40       50       60       70       80 
#number9 number10 
#  90      100 

If you want to stick to for loop, you can

i <- c(1:10)
multiples <- numeric(10)
names(multiples) <- ""
for (n in i) {
multiples[n] <- n * 10
names(multiples)[n] <- paste0("number", n)
}