0

我有带有数字的 3D 矩阵,但 R 以某种方式将数字数据视为字符。我加载的文件是数字向量。但是一旦我将它们放入 3D 向量中,所有数据编号都会显示为“字符”,如下所示:

     [,1]   [,2]   [,3]   [,4]   [,5]   [,6]  
  [1,] "3.79" "3.79" "2.33" "2.33" "2.79" "2.79"
  [2,] "3.79" "3.79" "2.33" "2.33" "2.79" "2.79"
  [3,] "3.02" "3.02" "4.94" "4.94" "4.33" "4.33"
  [4,] "3.02" "3.02" "4.94" "4.94" "4.33" "4.33"
  [5,] "4.25" "4.25" "4.06" "4.06" "4.98" "4.98"
  [6,] "4.25" "4.25" "4.06" "4.06" "4.98" "4.98"
  [7,] "4.25" "4.25" "4.06" "4.06" "4.98" "4.98"
  [8,] "2.07" "2.07" "2.09" "2.09" "2.92" "2.92"

但在我放入 3D 矩阵之前,数据显示如下:

[39965] 3.68230769 3.68230769 3.68230769 2.96454545
[39969] 2.96454545 3.93600000 3.93600000 3.93600000
[39973] 3.67769231 3.67769231 3.67769231 5.12750000
[39977] 5.12750000 5.12750000 3.05083333 3.05083333
[39981] 3.05083333 1.94166667 1.94166667 1.69000000
[39985] 1.69000000 1.69000000 2.01769231 2.01769231
[39989] 2.01769231 3.05692308 3.05692308 3.05692308
[39993] 3.72916667 3.72916667 3.72916667 2.65454545
[39997] 2.65454545 2.45583333 2.45583333 2.45583333

这是我的代码:

for (i in 1: length(precipitation)) {
    precip <- read.csv(precipitation[i])
    precip[is.na(precip)] <- 0

    precip2<- precip[,-1]
    precip3<-as.vector(unlist(precip2))
    prep_data[,,i]<-matrix(precip3,ncol=200,nrow=200)
}

是否可以添加一些编码来解决这个问题,所以我所有的 3D 矩阵元素都是数字,而不是“数字”。

4

2 回答 2

1

用于as.numeric将某些内容转换为数字。通常,as.class转换为该类(数字、字符、因子、日期、data.frame、矩阵等等)。

于 2013-03-02T20:29:36.320 回答
0

您可以使用 colClasses 参数将输入数据强制到特定类。下面的代码可能会在您的代码中替代 read.csv 调用,如果遇到非数字条目,它将生成警告,但将确保好的数据是数字的:

precip <- read.csv(precipitation[i], colClasses="numeric" )
于 2013-03-02T19:04:50.210 回答