If I have two vectors of the same length A<-c(5,10)
and B<-c(7,13)
how can I easily turn these two vectors into a single tuple vector i. e. <
I'm not certain this is exactly what you're looking for, but:
list(A, B)
which gives you a structure like this:
> str(list(A, B))
List of 2
$ : num [1:2] 5 10
$ : num [1:2] 7 13
and is literally represented like this:
dput(list(A, B)) list(c(5, 10), c(7, 13))
... which is about as close to the suggested end result as you can get, I think.
A list in R is essentially a vector of whatever you want it to be.
If that isn't what you're looking for, it might be helpful if you could expand on what exactly you'd like to do with this vector.
I see what you want to accomplish (because I had the same problem)!
Why not use complex numbers because they are basically nothing else but two dimensional numbers and they are an official data type in R with all the necessary methods available:
A <- complex(real=5,imaginary=10)
B <- complex(real=7,imaginary=13)
c(A,B)
## [1] 5+10i 7+13i
matrix(c(A,B),ncol=1)
## [,1]
## [1,] 5+10i
## [2,] 7+13i
Others have mentioned lists. I see other possibilities:
cbind(A, B) # makes a column-major 2x2-"vector"
rbind(A, B) # an row major 2x2-"vector" which could also be added to an array with `abind`
It is also possible to preserve their "origins"
AB <- cbind(A=A, B=B)
array(c(AB,AB+10), c(2,2,2) )
, , 1
[,1] [,2]
[1,] 5 7
[2,] 10 13
, , 2
[,1] [,2]
[1,] 15 17
[2,] 20 23
> abind( array(c(AB,AB+10), c(2,2,2) ), AB+20)
, , 1
A B
[1,] 5 7
[2,] 10 13
, , 2
A B
[1,] 15 17
[2,] 20 23
, , 3
A B
[1,] 25 27
[2,] 30 33
Your tuple vector c((5,7),(7,13))
is not valid syntax. However, your phrasing makes me think you are thinking of something like python's zip
. How do you want your tuples represented in R? R has a heterogeneous (recursive) type list
and a homogenous type vector
; there are no scalar types (that is, types that just hold a single value), just vectors of length 1 (somewhat an oversimplification).
If you want your tuples to be rows of a matrix (all the same type, which they are here):
rbind(A,B)
If you want a list of vectors
mapply(c, A, B, SIMPLIFY=FALSE)
If you want a list of lists (which is what you would need if A
and B
are not the same type)
mapply(list, A, B, SIMPLIFY=FALSE)
Putting this all together:
> A<-c(5,10)
> B<-c(7,13)
>
> cbind(A,B)
A B
[1,] 5 7
[2,] 10 13
> mapply(c, A, B, SIMPLIFY=FALSE)
[[1]]
[1] 5 7
[[2]]
[1] 10 13
> mapply(list, A, B, SIMPLIFY=FALSE)
[[1]]
[[1]][[1]]
[1] 5
[[1]][[2]]
[1] 7
[[2]]
[[2]][[1]]
[1] 10
[[2]][[2]]
[1] 13