Creating tuples from two vectors

后端 未结 4 2037
余生分开走
余生分开走 2020-12-31 00:46

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. <

4条回答
  •  一个人的身影
    2020-12-31 01:48

    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
    

提交回复
热议问题