convert matrix to numeric data frame

寵の児 提交于 2020-04-29 09:50:14

问题


I have some data in a somewhat inconvenient format. It is saved as a matrix, with all column vectors being characters.

datamatrix <- structure(c("1", "2", "3", "4", "0.9301", "0.93", "0.9286", "0.9209", 
                          "0.9", "0.8064", "0.7947", "0.7607", "0.8042", "0.7847", "0.7832", 
                          "0.7578", "0.7487", "0.7105", "0.6566", "0.5951", "0.6951", "0.677", 
                          "0.6588", "0.5922", "0.6889", "0.6471", "0.6524", "0.5932"), .Dim = c(4L, 
                                                                                                7L))

My aim is to convert this matrix to a dataframe and the column vectors to the class numeric.

I have tried following procedures:

1)

datamatrix2 <- as.data.frame(datamatrix)
datamatrix2 <- as.numeric(datamatrix2)

This gives the error:

"Error: (list) object cannot be coerced to type 'double'"

2) So I try it with sapply:

datamatrix3 <- as.data.frame(sapply(datamatrix, as.numeric))

This puts all the columns I had before in only long column.

3) When I use the apply function from 2) on the data already transformed into a dataframe (but still character vectors), it takes the values from the first column (1,2,3,4) and puts it in all other columns (but in a descending order).

datamatrix4 <- as.data.frame(sapply(datamatrix2, as.numeric))

回答1:


Nicest way to convert matrices is to change the mode. This way you can make the matrix numeric, then you can convert to data frame easily:

mode(datamatrix) = "numeric"
data.frame(datamatrix)
#   X1     X2     X3     X4     X5     X6     X7
# 1  1 0.9301 0.9000 0.8042 0.7487 0.6951 0.6889
# 2  2 0.9300 0.8064 0.7847 0.7105 0.6770 0.6471
# 3  3 0.9286 0.7947 0.7832 0.6566 0.6588 0.6524
# 4  4 0.9209 0.7607 0.7578 0.5951 0.5922 0.5932



回答2:


There are a couple of ways to do this. The easiest is probably with purrr::map_df():

library("purrr")
datamatrix = as.data.frame(datamatrix, stringsAsFactors = FALSE)
datamatrix = map_df(datamatrix, as.numeric)
datamatrix
# A tibble: 4 x 7
#      V1     V2     V3     V4     V5     V6     V7
#   <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
# 1     1 0.9301 0.9000 0.8042 0.7487 0.6951 0.6889
# 2     2 0.9300 0.8064 0.7847 0.7105 0.6770 0.6471
# 3     3 0.9286 0.7947 0.7832 0.6566 0.6588 0.6524
# 4     4 0.9209 0.7607 0.7578 0.5951 0.5922 0.5932

This explicitly asks to return a data frame.

Base R way would be:

datamatrix = as.data.frame(datamatrix)
datamatrix = lapply(datamatrix, as.numeric)
datamatrix = as.data.frame(datamatrix)
str(datamatrix)


来源:https://stackoverflow.com/questions/47022865/convert-matrix-to-numeric-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!