Przekształć trzy kolumnową ramkę danych w matrycę (format" długi "na" szeroki")

Mam data.frame, który wygląda tak.

x a 1 
x b 2 
x c 3 
y a 3 
y b 3 
y c 2 

Chcę to w postaci matrycy, więc mogę go nakarmić heatmap, aby stworzyć wykres. Wynik powinien wyglądać mniej więcej tak:

    a    b    c
x   1    2    3
y   3    3    2

Próbowałem cast z pakietu reshape i próbowałem napisać ręczną funkcję, aby to zrobić, ale wydaje się, że nie jestem w stanie zrobić tego dobrze.

Author: majom, 2012-03-08

4 answers

Jest na to wiele sposobów. Ta odpowiedź zaczyna się od moich ulubionych sposobów, ale także zbiera różne sposoby od odpowiedzi na podobne pytania rozsiane po tej stronie.

tmp <- data.frame(x=gl(2,3, labels=letters[24:25]),
                  y=gl(3,1,6, labels=letters[1:3]), 
                  z=c(1,2,3,3,3,2))

Użycie reshape2:

library(reshape2)
acast(tmp, x~y, value.var="z")

Użycie indeksowania macierzy:

with(tmp, {
  out <- matrix(nrow=nlevels(x), ncol=nlevels(y),
                dimnames=list(levels(x), levels(y)))
  out[cbind(x, y)] <- z
  out
})

Używając xtabs:

xtabs(z~x+y, data=tmp)

Możesz również użyć reshape, jak sugerowano tutaj: Konwertuj tabelę na macierz według nazw kolumn , chociaż musisz potem wykonać małą manipulację, aby usunąć dodatkowe kolumny i uzyskać nazwy właściwe (Nie pokazane).

> reshape(tmp, idvar="x", timevar="y", direction="wide")
  x z.a z.b z.c
1 x   1   2   3
4 y   3   3   2

Istnieje również sparseMatrix w pakiecie Matrix, Jak widać tutaj: R-konwersja dużej tabeli na macierz przez nazwy kolumn

> with(tmp, sparseMatrix(i = as.numeric(x), j=as.numeric(y), x=z,
+                        dimnames=list(levels(x), levels(y))))
2 x 3 sparse Matrix of class "dgCMatrix"
  a b c
x 1 2 3
y 3 3 2

Można również użyć funkcji daply z biblioteki plyr, Jak tutaj: https://stackoverflow.com/a/7020101/210673

> library(plyr)
> daply(tmp, .(x, y), function(x) x$z)
   y
x   a b c
  x 1 2 3
  y 3 3 2

dcast od reshape2 działa również, jak tutaj: przekształcanie danych dla wartości w jednej kolumnie , ale otrzymujesz dane.ramka z kolumną do x wartość.

> dcast(tmp, x~y, value.var="z")
  x a b c
1 x 1 2 3
2 y 3 3 2

Podobnie, spread z "tidyr" również działałoby dla takiej transformacji:

library(tidyr)
spread(tmp, y, z)
#   x a b c
# 1 x 1 2 3
# 2 y 3 3 2
 156
Author: Aaron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:50

Pytanie ma kilka lat, ale być może niektórzy ludzie nadal są zainteresowani alternatywnymi odpowiedziami.

Jeśli nie chcesz ładować żadnych pakietów, możesz użyć tej funkcji:

#' Converts three columns of a data.frame into a matrix -- e.g. to plot 
#' the data via image() later on. Two of the columns form the row and
#' col dimensions of the matrix. The third column provides values for
#' the matrix.
#' 
#' @param data data.frame: input data
#' @param rowtitle string: row-dimension; name of the column in data, which distinct values should be used as row names in the output matrix
#' @param coltitle string: col-dimension; name of the column in data, which distinct values should be used as column names in the output matrix
#' @param datatitle string: name of the column in data, which values should be filled into the output matrix
#' @param rowdecreasing logical: should the row names be in ascending (FALSE) or in descending (TRUE) order?
#' @param coldecreasing logical: should the col names be in ascending (FALSE) or in descending (TRUE) order?
#' @param default_value numeric: default value of matrix entries if no value exists in data.frame for the entries
#' @return matrix: matrix containing values of data[[datatitle]] with rownames data[[rowtitle]] and colnames data[coltitle]
#' @author Daniel Neumann
#' @date 2017-08-29
data.frame2matrix = function(data, rowtitle, coltitle, datatitle, 
                             rowdecreasing = FALSE, coldecreasing = FALSE,
                             default_value = NA) {

  # check, whether titles exist as columns names in the data.frame data
  if ( (!(rowtitle%in%names(data))) 
       || (!(coltitle%in%names(data))) 
       || (!(datatitle%in%names(data))) ) {
    stop('data.frame2matrix: bad row-, col-, or datatitle.')
  }

  # get number of rows in data
  ndata = dim(data)[1]

  # extract rownames and colnames for the matrix from the data.frame
  rownames = sort(unique(data[[rowtitle]]), decreasing = rowdecreasing)
  nrows = length(rownames)
  colnames = sort(unique(data[[coltitle]]), decreasing = coldecreasing)
  ncols = length(colnames)

  # initialize the matrix
  out_matrix = matrix(NA, 
                      nrow = nrows, ncol = ncols,
                      dimnames=list(rownames, colnames))

  # iterate rows of data
  for (i1 in 1:ndata) {
    # get matrix-row and matrix-column indices for the current data-row
    iR = which(rownames==data[[rowtitle]][i1])
    iC = which(colnames==data[[coltitle]][i1])

    # throw an error if the matrix entry (iR,iC) is already filled.
    if (!is.na(out_matrix[iR, iC])) stop('data.frame2matrix: double entry in data.frame')
    out_matrix[iR, iC] = data[[datatitle]][i1]
  }

  # set empty matrix entries to the default value
  out_matrix[is.na(out_matrix)] = default_value

  # return matrix
  return(out_matrix)

}

Jak to działa:

myData = as.data.frame(list('dim1'=c('x', 'x', 'x', 'y','y','y'),
                            'dim2'=c('a','b','c','a','b','c'),
                            'values'=c(1,2,3,3,3,2))) 

myMatrix = data.frame2matrix(myData, 'dim1', 'dim2', 'values')

myMatrix
>   a b c
> x 1 2 3
> y 3 3 2
 2
Author: daniel.neumann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-29 18:29:16

Pakiet tidyr z tidyverse ma doskonałą funkcję, która to robi.

Zakładając, że Twoje zmienne mają nazwy v1, v2 i v3, od lewej do prawej, a ramka danych ma nazwę dat:

dat %>% 
spread(key = v2,
       value = v3)
Ta da!
 0
Author: Ahsen Omar Majid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-12 19:38:19

Baza R, unstack

unstack(df, V3 ~ V2)
#   a b c
# 1 1 2 3
# 2 3 3 2

To może nie być ogólne rozwiązanie, ale działa dobrze w tym przypadku.

Dane

df<-structure(list(V1 = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("x", 
"y"), class = "factor"), V2 = structure(c(1L, 2L, 3L, 1L, 2L, 
3L), .Label = c("a", "b", "c"), class = "factor"), V3 = c(1L, 
2L, 3L, 3L, 3L, 2L)), .Names = c("V1", "V2", "V3"), class = "data.frame", row.names = c(NA, 
-6L))
 0
Author: lebatsnok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-05 20:11:50