Kaja
Kaja

Reputation: 3057

converting a dataframe to a matrix

I have a data frame like this:

         V1 V2        V3
    1    1  1 0.0000000
    2    2  1 1.6646331
    3    3  1 1.6649136
    4    4  1 1.7420642
    5    5  1 1.4441743
    6    6  1 0.7544465
    7    7  1 1.9796860
    8    8  1 1.0744425
    9    9  1 2.1503288
    10  10  1 1.0408388
    11  11  1 2.0822162
    ....
    841 29 29 0.0000000

I want to convert this data frame to a matrix. In this matrix V2 should be the row and V1 should be column

    [1]         [2]        [3]        [4] ....
[1]  0.0000000  1.6646331  1.664936    1.7420642...

How can I do that in r?

Upvotes: 2

Views: 125

Answers (3)

Simon O'Hanlon
Simon O'Hanlon

Reputation: 60000

Assuming you have contiguous values for your matrix (i.e. no gaps in the matrix) and the running order of values is continuous (i.e. row1;columns1:10,row2;columns1:10... etc), then....

Take the values in the appropriate column (V3 in your case) and reshape them according to your paramters of matrix size...

m <- matrix( df$V3 , ncol = max(df$V1) , nrow = max(df$V2) , byrow = TRUE )
#[,1]     [,2]     [,3]     [,4]     [,5]      [,6]     [,7]     [,8]     [,9]    [,10]    [,11]
#[1,]    0 1.664633 1.664914 1.742064 1.444174 0.7544465 1.979686 1.074442 2.150329 1.040839 2.082216

If you need to match the values (i.e. running order is not continuous) then you can take advantage of vectorised matrix subscripting like so....

#  Create empty matrix
m <- matrix( NA, ncol = max(df$V1) , nrow = max(df$V2) )   
#  Then fill with values at defined locations
m[ cbind( df$V2 , df$V1 ) ] <- df$V3

Upvotes: 4

nico
nico

Reputation: 51680

This should do the job (where df is your data frame)

m <- do.call(cbind, df)

Upvotes: 0

csgillespie
csgillespie

Reputation: 60492

You need to do two things:

  1. Reorder your columns
  2. Transpose (using the t function)

So first create some example data

d = data.frame(V1=runif(5), V2= 5+runif(5), V3 = 10+runif(5))

then

t(d[, ncol(d):1])

or

t(d)[ncol(d):1, ]

Upvotes: 2

Related Questions