massa - 2 months ago 31

R Question

I've got this code:

`n<-5`

for (i in 1:n) {

for (k in 1:n) {

print (i-k)

}

}

So, results are scalar vectors. But I need to get one vector with all results in it, like this:

`[1] 0 -1 -2 -3 -4 1 0 -1 -2`

etc.

How can i get it? Trying

`unlist()`

Answer

Try this vectorized:

```
n <- 5
as.vector(t(outer(1:n,1:n,'-')))
#[1] 0 -1 -2 -3 -4 1 0 -1 -2 -3 2 1 0 -1 -2 3 2 1 0 -1 4 3 2 1 0
```

OR

```
as.vector(sapply(1:n, function(i) i-(1:n)))
```

OR

```
as.vector(sapply(1:n,'-',1:n))
```