I'm trying to fill a a vector through a loop in R.

```
# variables
vector1 <- c("aaaa", "bbbb", "ccccc", "ddddd")
vector2 <- c("bbbb", "eeeee", "fffff", "ddddd")
# function
total <- numeric(length(vector1)*length(vector2))
subtotal <- numeric(length(vector1))
aux <- 0
for(i in 1:length(vector2)){
subtotal = mapply(levenshteinSim, vector1, vector2[[i]])
total[(length(vector1)*aux)+1:length(vector1)*i] <- subtotal
inc(aux) <- 1
}
```

For 2 vectors with 4 lengths, i have a total vector with length 16.

However i got the following output:

```
> total [1] 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 NA NA 0 NA NA NA 0 NA NA NA 1
```

What am I doing wrong?

EDIT: The Levensthein function i got from RecordLinkage package, and inc function, from Hmisc package. The first compares two strings, and the other just increments value to some variable.

EDIT2: I'm using some strange functions, but my objetive is only to fill the total vector though the loop, with the subtotals values. Let's get some other example:

```
# variables
vector1 <- c("a", "b", "c", "d")
vector2 <- c("a", "b", "c", "d")
# function
total <- numeric(length(vector1)*length(vector2))
subtotal <- numeric(length(vector1))
aux <- 0
for(i in 1:length(vector2)){
subtotal = mapply(paste, vector1, vector2[[i]])
total[(length(vector1)*aux)+1:length(vector1)*i] <- subtotal
aux <- aux + 1
print(subtotal)
}
```

I expected the following result: a vector Total with length 16, filled with the subtotals vectors from the loop. Something like this:

```
a b c d
"a a" "b a" "c a" "d a"
a b c d
"a b" "b b" "c b" "d b"
a b c d
"a c" "b c" "c c" "d c"
a b c d
"a d" "b d" "c d" "d d"
```

However I got this: a vector with 28 positions, and many N/As:

```
[1] "a a" "b a" "c a" "d a" "0" "a b" "0" "b b" "0" "c b" "a c" "d b" "0" "b c" "0" "a d" "c c" NA NA
[20] "b d" NA NA NA "c d" NA NA NA "d d"
```

rloopsvector
answered 5 years ago Miff #1

Your problem comes from the ':' operator having higher precedence than the other operators, try adding brackets:

```
total[((length(vector1)*aux)+1):(length(vector1)*i)] <- subtotal
```

Alternatively, you might prefer to replace the whole code with:

```
as.vector(outer(vector1,vector2,paste))
```