convert matrix to numeric data frame
Solution 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
Solution 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)
SCW16
Updated on June 20, 2022Comments
-
SCW16 almost 2 years
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))
-
SCW16 over 6 yearsThank you! I have tried both of your suggestions. Unfortunately both change the values in the data. The first column stays the same, but the columns 2-7 get the values (4,3,2,1). The change of values in the first suggestion happens in the second line of code (datamatrix = lapply(datamatrix, as.numeric)) and in the second suggestion it also happens in the second line (datamatrix = map_df(datamatrix, as.numeric)).
-
Phil over 6 years@SCW16 Yes, sorry, forgot
stringsAsFactors = FALSE
. See edited answer.