0

I am trying to transform a data frame (treating as a vector) with locational data and a value onto a matrix that uses locational data as it's row and column names.

(Run snippets to see layout examples.)

Example of the vector:

 <table>
  <tr>
    <th>"Longitude"</th>
    <th>"Latitude"</th>
    <th>"Value"</th>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>10</td>
  </tr>
  <tr>
    <td>3</td>
    <td>3</td>
    <td>100</td>
  </tr>
  <tr>
    <td>2</td>
    <td>1</td>
    <td>65</td>
  </tr>
</table> 

Example of the matrix:

 <table>
  <tr>
    <th></th>
    <th>1</th>
    <th>2</th>
    <th>3</th>
  </tr>
  <tr>
    <th>1</th>
    <td>0.00</td>
    <td>0.00</td>
    <td>0.00</td>
  </tr>
  <tr>
    <th>2</th>
    <td>0.00</td>
    <td>0.00</td>
    <td>0.00</td>
  </tr>
  <tr>
    <th>3</th>
    <td>0.00</td>
    <td>0.00</td>
    <td>0.00</td>
  </tr>
</table> 

The result I want is:

 <table>
  <tr>
    <th></th>
    <th>1</th>
    <th>2</th>
    <th>3</th>
  </tr>
  <tr>
    <th>1</th>
    <td>0.00</td>
    <td>65.00</td>
    <td>0.00</td>
  </tr>
  <tr>
    <th>2</th>
    <td>10.00</td>
    <td>0.00</td>
    <td>0.00</td>
  </tr>
  <tr>
    <th>3</th>
    <td>0.00</td>
    <td>0.00</td>
    <td>100.00</td>
  </tr>
</table> 

Essentially, I want to treat the data frame as a series of vectors and transform them onto the matrix but my past attempts have resulted in the matrix transforming itself into a list instead.

Does anyone know how to do this?

Thank you in advance.

1 Answers1

0

We can do this easily with xtabs from base R

out <- xtabs(Value ~ Latitude + Longitude, df1)
names(dimnames(out)) <- NULL
out
#    1   2   3
#1   0  65   0
#2  10   0   0
#3   0   0 100
akrun
  • 874,273
  • 37
  • 540
  • 662