我有带有数字的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矩阵元素都是数字,而不是“数字”。
答案 0 :(得分:1)
使用as.numeric
将内容转换为数字。通常,as.class
会转换为该类(数字,字符,因子,日期,数据框,矩阵等等)。
答案 1 :(得分:0)
您可以使用colClasses参数将输入数据强制转换为特定类。下面的代码可能代替代码中的read.csv调用,如果遇到非数字条目,将生成警告,但确保良好的数据为数字:
precip <- read.csv(precipitation[i], colClasses="numeric" )