简体   繁体   中英

R generate matrix from linear table with column and row numbers

I am new in R and struggle with arrays.My question is very simple but I didnt find easy answer on the web or in R documentation.

I have a table with column and row number that I want to use to generate a new matrix

Original table:

    V1  V2     pval
1    1    2    5.914384e-13
2    1    3    8.143390e-01
3    1    4    7.587818e-01
4    1    5    9.734698e-12
5    1    6    7.812521e-19

I want to use:

  • V1 as the column number for the new matrix;
  • V2 as the row number
  • pvals as the value

Targeted matrix:

     1         2       3       4
1    0         5e-1    8e-1    7e-1
2    5e-13     0
3    8e-1              0
4    7e-1                      0
#some data
set.seed(42)
df <- data.frame(V1=rep(1:6,each=3),V2=rep(1:3,6),pval=runif(18,0,1))
df <- df[df$V1!=df$V2,]

#   V1 V2        pval
#2   1  2 0.560332746
#3   1  3 0.904031387
#4   2  1 0.138710168
#6   2  3 0.946668233
#7   3  1 0.082437558
#8   3  2 0.514211784
# ...

#use dcast to change to wide format
library(reshape2)
df2 <- dcast(df,V2~V1,fill=0)

#  V2         1         2          3         4         5           6
#1  1 0.0000000 0.1387102 0.08243756 0.9057381 0.7375956 0.685169729
#2  2 0.5603327 0.0000000 0.51421178 0.4469696 0.8110551 0.003948339
#3  3 0.9040314 0.9466682 0.00000000 0.8360043 0.3881083 0.832916080

#in case you really want a matrix object
m <- as.matrix(df2[,-1])

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