将值从矩阵导入另一个矩阵

时间:2014-10-14 15:19:51

标签: r csv matrix

我正在尝试将某些列的值从矩阵Att_table_S01_E031传输到矩阵Att_table_S01_E031_Mod。但似乎矩阵Att_table_S01_E031的结构不适合其他矩阵。请在下面找到我一直使用的脚本。

必须从中导出值的矩阵

Deforested_areas<- readShapePoly("S01_E031_FC")`
proj4string(Deforested_areas) <- "+proj=longlat +datum=WGS84"
write.table(Deforested_areas, file = "S01_E031_FC.csv", sep=",") 
Att_Table_Deforested_areas= read.csv("S01_E031_FC.csv")
Att_table_S01_E031 <- as.matrix(Att_Table_Deforested_areas) 
colnames (Att_table_S01_E031)
[1] "ID"         "LU_1990"    "LU_2000"    "CHLU_90_00" "LU_2005"    "CHLU_00_05" "Tile"       "UNIQ_ID"   
 [9] "AREA"       "D_90_00"    "D_00_05"    "Sour_90_00" "Sour_00_05"

 row.names(Att_table_S01_E031)

 [1] "0"  "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15"

必须导入前一个矩阵的值的矩阵

Att_table_S01_E031_Mod <- matrix(NA, nrow = 16, ncol = 13)
colnames (Att_table_S01_E031_Mod) <- c("ID", "AREA", "LU_1990", "LU_2000", "LU_2005", "CHLU_90_00", "CHLU_00_05", "Tile", "UNIQ_ID", "D_90_00", "D_00_05", "Sour_90_00", "Sour_00_05")

colnames(Att_table_S01_E031_Mod)
[1] "ID"         "AREA"       "LU_1990"    "LU_2000"    "LU_2005"    "CHLU_90_00" "CHLU_00_05" "Tile"

[9] "UNIQ_ID"    "D_90_00"    "D_00_05"    "Sour_90_00" "Sour_00_05"  

 row.names(Att_table_S01_E031_Mod)
NULL

值转移过程

columnsToTransfer1 <- c('ID', 'Area', 'LU_1990', 'Tile', 'UNIQ_ID')
Att_table_S01_E031_Mod[,columnsToTransfer1] <- Att_table_S01_E031[,columnsToTransfer1]

The error message is : Error in Att_table_S01_E031[, columnsToTransfer1] : subscript out of bounds

1 个答案:

答案 0 :(得分:0)

我猜错误消息是因为Att_table_S01_E031_Mod的列名与columnsToTransfer1不匹配。检查AREAArea

  colnames(Att_table_S01_E031_Mod)
  #[1] "ID"         "AREA"       "LU_1990"    "LU_2000"    "LU_2005"   
  #[6] "CHLU_90_00" "CHLU_00_05" "Tile"       "UNIQ_ID"    "D_90_00"   
  #[11] "D_00_05"    "Sour_90_00" "Sour_00_05"

   columnsToTransfer1
  #[1] "ID"      "Area"    "LU_1990" "Tile"    "UNIQ_ID"

  Att_table_S01_E031_Mod[,columnsToTransfer1] 
  #Error in Att_table_S01_E031_Mod[, columnsToTransfer1] : 
  #subscript out of bounds

Area更改为AREA中的columnsToTransfer1(或者您可以更改数据集的列名称)

 columnsToTransfer1[2] <- "AREA"

现在,您执行导入

 Att_table_S01_E031_Mod[,columnsToTransfer1] <- Att_table_S01_E031[,columnsToTransfer1]
 Att_table_S01_E031_Mod[1:3,1:3]
 #     ID AREA LU_1990
 #[1,]  1   76      92
 #[2,]  2   46      94
 #[3,]  3   54      29

数据

set.seed(42)
Att_table_S01_E031 <- cbind(ID=1:16, matrix(sample(1:100, 12*16,replace=TRUE), 
 ncol=12, dimnames=list(NULL, c("LU_1990", "LU_2000", "CHLU_90_00", "LU_2005",
"CHLU_00_05", "Tile", "UNIQ_ID",  "AREA", "D_90_00", "D_00_05",
"Sour_90_00",   "Sour_00_05") ) ) )