在R中的矩阵列表中分配暗号

时间:2018-11-27 12:34:03

标签: r get assign

我有一个新的矩阵列表,对于这些矩阵,其(缺失的)暗名称必须替换为先前列表的暗名称。 由于每个列表的矩阵数是可变的,因此我需要通过循环(对于loop,apply等)进行操作。

示例数据:

export class Class1 extends Component {
   render() {
      return (
         <div onClick={this.props.getData()}>Click to Call API</div>
      );
   }
}

export class Class2 extends Component {
   state = {
    data: null,
   };
   
   callApi = () => {
      // Get API data
      const data = {
        hello: 'world',
      };
      
      this.setState({ data });
   }
   
   render {
      return (
         <Class1 getData={this.callApi} />
         {JSON.stringify(this.state.data)}
      )    
   }   
}

手动显示如下:

new_list <- list(
    matrix1=matrix(
        sample(20,24,T),
        6
    ),
    matrix2=matrix(
        sample(20,24,T),
        6
    ),
    matrix3=matrix(
        sample(20,24,T),
        6
    )
)

old_list <- list(
    matrix1=matrix(
        sample(10,24,T),
        6,
        dimnames=list(sprintf("Row_%d", 1:6), sprintf("Col_%d", 1:4))
    ),
    matrix2=matrix(
        sample(10,24,T),
        6,
        dimnames=list(sprintf("Row_%d", 1:6), sprintf("Col_%d", 5:8))
    ),
    matrix3=matrix(
        sample(10,24,T),
        6,
        dimnames=list(sprintf("Row_%d", 1:6), sprintf("Col_%d", 9:12))
    )
)

new_list
$matrix1
     [,1] [,2] [,3] [,4]
[1,]    2   18    2    5
[2,]   17   20   12    4
[3,]    5    9   18    4
[4,]   15   13    5   20
[5,]    7   13   10   13
[6,]   14    7    6   12

$matrix2
     [,1] [,2] [,3] [,4]
[1,]   16    6   16    7
[2,]   17   10    6   13
[3,]    9    9   18   14
[4,]    7    7    7   19
[5,]   19   20   13    9
[6,]   12   20   13   18

$matrix3
     [,1] [,2] [,3] [,4]
[1,]    3   14   15   10
[2,]    9   18   15   15
[3,]    4   13   20    2
[4,]   15   10    2    6
[5,]   15    9    1    1
[6,]    5   20    9   18

old_list
$matrix1
      Col_1 Col_2 Col_3 Col_4
Row_1     2     4     3     5
Row_2     6     8     1     3
Row_3     5     1     9    10
Row_4     2     8     8     7
Row_5     5     8     8     8
Row_6    10     5     9     8

$matrix2
      Col_5 Col_6 Col_7 Col_8
Row_1     9     4     6     4
Row_2     1     1     4     1
Row_3     5     6     1     7
Row_4     9    10     2    10
Row_5     4     9     1     6
Row_6    10     2     9     7

$matrix3
      Col_9 Col_10 Col_11 Col_12
Row_1     2      8     10      2
Row_2     4     10      3      3
Row_3     8      8      6      5
Row_4     2      8      8      3
Row_5     4      7     10      8
Row_6     9      9      9      2

我尝试了以下操作,但返回了错误:

dimnames(new_list$matrix1) = dimnames(old_list$matrix1)
dimnames(new_list$matrix2) = dimnames(old_list$matrix2)
dimnames(new_list$matrix3) = dimnames(old_list$matrix3)

1 个答案:

答案 0 :(得分:1)

我们可以使用Map进行分配

Map(function(x, y) {dimnames(x) <- dimnames(y); x}, new_list, old_list)