当df还包含字符串时,将data.frame转换为数字矩阵的正确方法是什么?

Pik*_*tja 49 if-statement r numeric matrix

我有一个.csv文件中的数据框,其中包含数字和字符值.我想将此数据帧转换为矩阵.所有包含信息的都是数字(我删除的非数字行),因此应该可以将数据帧转换为数字矩阵.但是,我确实得到了一个字符矩阵.

我发现解决这个问题的唯一方法是使用as.numeric每一行,但这非常耗时.我很确定有一种方法可以用某种形式来做到这一点if(i in 1:n),但我无法弄清楚它是如何工作的.或者是真正开始使用数值的唯一方法,如此处提出的(制作矩阵数字和名称顺序)?

对大多数人来说,这可能是一件非常容易的事:P

矩阵要大很多,这只是前几行......这是代码:

cbind(
as.numeric(SFI.Matrix[ ,1]),
as.numeric(SFI.Matrix[ ,2]),
as.numeric(SFI.Matrix[ ,3]),
as.numeric(SFI.Matrix[ ,4]),
as.numeric(SFI.Matrix[ ,5]),
as.numeric(SFI.Matrix[ ,6]))  

# to get something like this again:

Social.Assistance Danger.Poverty GINI S80S20 Low.Edu        Unemployment 
0.147             0.125          0.34    5.5   0.149        0.135 0.18683691
0.258             0.229          0.27    3.8   0.211        0.175 0.22329362
0.207             0.119          0.22    3.1   0.139        0.163 0.07170422
0.219             0.166          0.25    3.6   0.114        0.163 0.03638525
0.278             0.218          0.29    4.1   0.270        0.198 0.27407825
0.288             0.204          0.26    3.6   0.303        0.211 0.22372633
Run Code Online (Sandbox Code Playgroud)

感谢您的任何帮助!

Ric*_*rta 55

编辑2:请参阅@ flodel的回答.好多了.

尝试:

# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))  
Run Code Online (Sandbox Code Playgroud)

编辑:或者@ CarlWitthoft在评论中建议:

matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))
Run Code Online (Sandbox Code Playgroud)

  • 为什么不简单地`矩阵(as.numeric(unlist(SFI)),nr = nrows(SFI))`? (3认同)

flo*_*del 52

data.matrix(SFI)
Run Code Online (Sandbox Code Playgroud)

来自?data.matrix:

Description:

 Return the matrix obtained by converting all the variables in a
 data frame to numeric mode and then binding them together as the
 columns of a matrix.  Factors and ordered factors are replaced by
 their internal codes.
Run Code Online (Sandbox Code Playgroud)

  • 这会将“123”解释为一个因子并将其转换为相关的整数级别。 (3认同)

TPA*_*row 7

如果数据框只包含数字,这是另一种方法.

apply(as.matrix.noquote(SFI),2,as.numeric)
Run Code Online (Sandbox Code Playgroud)

但是将数据帧转换为矩阵的最可靠方法是使用data.matrix()函数.