将矩阵转换为数字数据框 [英] convert matrix to numeric data frame
问题描述
我有一些不方便使用的数据格式.它保存为矩阵,所有列向量均为字符.
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.
我尝试了以下过程:
1)
datamatrix2 <- as.data.frame(datamatrix)
datamatrix2 <- as.numeric(datamatrix2)
这给出了错误:
"Error: (list) object cannot be coerced to type 'double'"
2)所以我尝试了sapply:
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)当我对转换为数据帧(但仍然是字符向量)的数据使用2)中的apply函数时,它将取自第一列(1,2,3,4)的值并将其放入其他所有列(但按降序排列).
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))
推荐答案
转换矩阵的最佳方法是更改mode
.这样,您可以制作矩阵numeric
,然后可以轻松地将其转换为数据帧:
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
这篇关于将矩阵转换为数字数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!