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))
Convert a Data Frame into a Numeric Matrix in R Programming – data. matrix() Function. data. matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.
numeric() function with the name of the given character matrix as its parameter and this will help the user to convert the character matrix to numeric vector and in the next step user has to call another function matrix() with the numeric vector (which was created by the as.
To convert columns of an R data frame from integer to numeric we can use lapply function. For example, if we have a data frame df that contains all integer columns then we can use the code lapply(df,as. numeric) to convert all of the columns data type into numeric data type.
If we have a matrix that contains character columns and we want to convert a single column to numeric then we first need to convert the matrix into a data frame using as. data. frame function after that as. numeric function can be used to change the particular column to numeric type as shown in the below examples.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With