Home > Blockchain >  Convert dataframe to matrix?
Convert dataframe to matrix?

Time:06-24

How do I convert this data frame into a matrix of values with rows as cell line and columns as deg?

> dput(final_values)
structure(list(cell_line = c("NUGC3_c9", "NUGC3_c9", "NUGC3_c9", 
"NUGC3_c9", "NUGC3_c9", "NUGC3_c9", "GCIY_c9", "GCIY_c9", "GCIY_c9", 
"GCIY_c9", "GCIY_c9", "GCIY_c9", "RCCFG2_c9", "RCCFG2_c9", "RCCFG2_c9", 
"RCCFG2_c9", "RCCFG2_c9", "RCCFG2_c9", "X769P_c9", "X769P_c9", 
"X769P_c9", "X769P_c9", "X769P_c9", "X769P_c9", "X786O_c9", "X786O_c9", 
"X786O_c9", "X786O_c9", "X786O_c9", "X786O_c9"), deg = c(3L, 
4L, 5L, 6L, 7L, 8L, 3L, 4L, 5L, 6L, 7L, 8L, 3L, 4L, 5L, 6L, 7L, 
8L, 3L, 4L, 5L, 6L, 7L, 8L, 3L, 4L, 5L, 6L, 7L, 8L), value = c(15.8151547340145, 
14.6981941137388, 14.0815336206517, 13.7853872530634, 13.6937688752229, 
13.7367668873381, 6.28574152356235, 7.20174811171657, 7.20397940493138, 
6.96970273617373, 6.64696258503419, 6.37711585074684, 4.92532850005957, 
6.24889418222532, 6.37016307572278, 6.14297629739634, 5.81903170250912, 
5.6652027595413, 26.9891162063465, 24.3362801325012, 23.3217063534995, 
23.1498923718838, 23.3762790270914, 23.37809836191, 7.3424970563227, 
7.89854654756756, 7.75963016048237, 7.43507107802584, 7.01627110789221, 
6.69482680775165)), row.names = c("1", "2", "3", "4", "5", "6", 
"7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", 
"18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", 
"29", "30"), class = "data.frame")

CodePudding user response:

We could use xtabs

out <- xtabs(value ~ cell_line   deg, final_values)

-output

out
        deg
cell_line           3         4         5         6         7         8
  GCIY_c9    6.285742  7.201748  7.203979  6.969703  6.646963  6.377116
  NUGC3_c9  15.815155 14.698194 14.081534 13.785387 13.693769 13.736767
  RCCFG2_c9  4.925329  6.248894  6.370163  6.142976  5.819032  5.665203
  X769P_c9  26.989116 24.336280 23.321706 23.149892 23.376279 23.378098
  X786O_c9   7.342497  7.898547  7.759630  7.435071  7.016271  6.694827

If we want to remove the xtabs attribute

out1 <- unclass(out)
attributes(out1)$call <- NULL
> str(out1)
 num [1:5, 1:6] 6.29 15.82 4.93 26.99 7.34 ...
 - attr(*, "dimnames")=List of 2
  ..$ cell_line: chr [1:5] "GCIY_c9" "NUGC3_c9" "RCCFG2_c9" "X769P_c9" ...
  ..$ deg      : chr [1:6] "3" "4" "5" "6" ...

CodePudding user response:

Alternatively, tapply returns a matrix directly.

out <- with(final_values, tapply(value, list(cell_line, deg), identity))
  • Related