Converting a data frame to a matrix with plyr daply

后端 未结 2 1475
花落未央
花落未央 2021-02-09 11:18

I\'m trying to use the daply function in the plyr package but I cannot get it to output properly. Even though the variable that makes up the matrix is

2条回答
  •  不思量自难忘°
    2021-02-09 12:10

    If we take the OP at their word(s) in the title, then they may be looking for data.matrix() which is a standard function in the base package that is always available in R.

    data.matrix() works by converting any factors to their numeric coding before converting the data frame to a matrix. Consider the following data frame:

    dat <- data.frame(A = 1:10, B = factor(sample(c("X","Y"), 10, replace = TRUE)))
    

    If we convert via as.matrix() we get a character matrix:

    > head(as.matrix(dat))
         A    B  
    [1,] " 1" "X"
    [2,] " 2" "X"
    [3,] " 3" "Y"
    [4,] " 4" "Y"
    [5,] " 5" "Y"
    [6,] " 6" "Y"
    

    or if via matrix() one gets a list with dimensions (a list array - as mentioned in the Value section of ?daply by the way)

    > head(matrix(dat))
         [,1]      
    [1,] Integer,10
    [2,] factor,10 
    > str(matrix(dat))
    List of 2
     $ : int [1:10] 1 2 3 4 5 6 7 8 9 10
     $ : Factor w/ 2 levels "X","Y": 1 1 2 2 2 2 1 2 2 1
     - attr(*, "dim")= int [1:2] 2 1
    

    data.matrix(), however, does the intended thing:

    > mat <- data.matrix(dat)
    > head(mat)
         A B
    [1,] 1 1
    [2,] 2 1
    [3,] 3 2
    [4,] 4 2
    [5,] 5 2
    [6,] 6 2
    > str(mat)
     int [1:10, 1:2] 1 2 3 4 5 6 7 8 9 10 ...
     - attr(*, "dimnames")=List of 2
      ..$ : NULL
      ..$ : chr [1:2] "A" "B"
    

提交回复
热议问题