What is the difference between matrix() and as.matrix() in r?

后端 未结 3 1642
死守一世寂寞
死守一世寂寞 2021-02-04 09:01

I ran the following in R and received the same output for both matrix() and as.matrix() and now I am not sure what the difference between them is:

3条回答
  •  我在风中等你
    2021-02-04 09:48

    matrix takes data and further arguments nrow and ncol.

    ?matrix
     If one of ‘nrow’ or ‘ncol’ is not given, an attempt is made to
     infer it from the length of ‘data’ and the other parameter.  If
     neither is given, a one-column matrix is returned.
    

    as.matrix is a method with different behaviours for different types, but mainly to give back an n*m matrix from an n*m input.

    ?as.matrix
     ‘as.matrix’ is a generic function.  The method for data frames
     will return a character matrix if there is only atomic columns and
     any non-(numeric/logical/complex) column, applying ‘as.vector’ to
     factors and ‘format’ to other non-character columns.  Otherwise,
     the usual coercion hierarchy (logical < integer < double <
     complex) will be used, e.g., all-logical data frames will be
     coerced to a logical matrix, mixed logical-integer will give a
     integer matrix, etc.
    

    The difference between them comes primarily from the shape of the input, matrix doesn't care about the shape, as.matrix does and will maintain it (though the details depend on the actual methods for the input, and in your case a dimensionless vector corresponds to a single column matrix.) It doesn't matter if the input is raw, logical, integer, numeric, character, or complex, etc.

提交回复
热议问题