Converting from a list to numeric in R

前端 未结 1 1095
余生分开走
余生分开走 2021-01-31 05:44

I recently had a problem in which everytime I read a csv file containing a table with values, R read it as a list format instead of numeric. As no thread provided me the entire

1条回答
  •  再見小時候
    2021-01-31 06:35

    Here is a shorter/faster way to turn your data.frame into a numeric matrix:

    data <- data.matrix(data)
    

    There is also

    data <- as.matrix(data)
    

    but one important difference is if your data contains a factor or character column: as.matrix will coerce everything into a character matrix while data.matrix will always return a numeric or integer matrix.

    data <- data.frame(
      logical   = as.logical(c(TRUE, FALSE)),
      integer   = as.integer(c(TRUE, FALSE)),
      numeric   = as.numeric(c(TRUE, FALSE)),
      factor    = as.character(c(TRUE, FALSE))
    )
    
    data.matrix(data)
    #      logical integer numeric factor
    # [1,]       1       1       1      2
    # [2,]       0       0       0      1
    
    as.matrix(data)
    #      logical integer numeric factor 
    # [1,] " TRUE" "1"     "1"     "TRUE" 
    # [2,] "FALSE" "0"     "0"     "FALSE"
    

    0 讨论(0)
提交回复
热议问题