简体   繁体   中英

How to extract 2 pairwise vectors from a matrix?

I have seen a post on How to combine 2 pairwise vectors into a matrix . I wonder if it is possible to do it reversely?

If I am understanding your question I think the the gather function from dplyr package will help a lot here.

library(dplyr)

x <- c('A','B','C')
dat <- expand.grid(x, x)
dat$Var3 <- rnorm(9)
df <- reshape(dat, idvar = "Var1", timevar = "Var2", direction = "wide")

df
   Var1     Var3.A     Var3.B      Var3.C
    A    -0.6600467 -0.3104995  0.09838619
    B    -0.7893837  1.1798629  1.07563953
    C    -1.8380682  0.5383169 -0.40365158

gather(df,"col_names",'values',2:4)
   Var1   col_names      values
     A    Var3.A     -0.66004667
     B    Var3.A     -0.78938370
     C    Var3.A     -1.83806815
     A    Var3.B     -0.31049949
     B    Var3.B      1.17986293
     C    Var3.B      0.53831689
     A    Var3.C      0.09838619
     B    Var3.C      1.07563953
     C    Var3.C     -0.40365158

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM