Burton Guster -4 years ago 137

R Question

I apologize for this question in advance, but I've looked pretty hard and haven't been able to find a solution.

How do I values generated by a for loop in a variable?

For example:

`myfunction <- function(x=1:5) {`

for(i in 1:length(x)) {

r<-x[i]

}

print(r)

}

If I run the above code, I only get the last value for x, in this case 5. I understand that this is because I'm overwriting r each time through the for loop.

I've also tried:

`myfunction <- function(x=1:5) {`

for(i in 1:length(x)) {

r[i]<-x[i]

}

print(r)

}

But I still just get the last value.

The only solution I've found is to specify the length of the variable that will hold the generated values before using r<-numeric(length):

`myfunction <- function(x=1:5) {`

r<-numeric(5)

for(i in 1:length(x)) {

r[i]<-x[i]

}

print(r)

}

But this solution will obviously be insufficient if I don't know the length of the vector to be returned beforehand.

Thanks for any help!

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Your loop only goes through once and it is with i = length(x). You probably want

```
for(i in seq(length(x))){
# code here
}
# or
for(i in seq_along(x)){
# code here
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**

Latest added