0

I'm trying to generate a matrix in R with rownames as a value in dataframe and colnames as so too. The values named by the row value and col value should match up with what's in the dataframe.

  p      photo filter     time
1  1 winter.png  edge1 94.51301
2  1  rocks.png  edge1 65.58044
3  1 pupper.png  edge1 47.72965
4  2 winter.png  edge1 57.73461
5  2  rocks.png  edge1 37.07482
6  2 pupper.png  edge1 26.07539
7  3 winter.png  edge1 39.93299
8  3  rocks.png  edge1 27.81006
9  3 pupper.png  edge1 18.99070
10 4 winter.png  edge1 33.10323
11 4  rocks.png  edge1 22.59480
12 4 pupper.png  edge1 15.38318

So for example I would like to produce something like:

             1          2          3        4
winter.png   94.51301   37.07482
rocks.png    65.58044   37.07482   27.81006     
pupper.png   47.72965   26.07539

(Not completely shown because I'm lazy)

Is there any good way for me to generate matrices as defined.

I want certain fields to placed in the rownames and colnames section of a matrix. That thing I can access with those functions.

HSchmale
  • 1,838
  • 2
  • 21
  • 48
  • Possible duplicate of [How to reshape data from long to wide format?](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format) – pogibas Dec 14 '18 at 01:00
  • @PoGibas I looked at that answer, it didn't have the information I needed, because I'm trying to build a matrix that's filtered. – HSchmale Dec 14 '18 at 01:03
  • Filtered how? You don't mention that in your question. – pogibas Dec 14 '18 at 01:04
  • 1
    @akrun You showed me the way to get it. Did not know about xtabs, That's a very cool function. You saved me a lot of work. – HSchmale Dec 14 '18 at 01:09

1 Answers1

2

We could use spread

library(tidyverse)
df1 %>% 
     select(-filter) %>% 
     spread(p, time)

Or using xtabs from base R

xtabs(time ~ photo + p, df1)
akrun
  • 874,273
  • 37
  • 540
  • 662