我有一个data.table,它是17个矩阵的总和。但是我需要将data.table转换为矩阵。
这是我用来制作数据表的代码:
countphij <- rbindlist(lapply(list(all.crossings,count.mat969798,
count.mat979899,
count.mat989900,
count.mat990001,
count.mat000102,
count.mat010203,
count.mat020304,
count.mat030405,
count.mat040506,
count.mat050607,
count.mat060708,
count.mat070809,
count.mat080910,
count.mat091011,
count.mat101112,
count.mat111213,
count.mat121314), function(x) setDT(as.data.frame(x),
keep.rownames = TRUE)), fill = TRUE)[, lapply(.SD, sum, na.rm = TRUE), by = rn]
得出下表:
rn Aa A Baa Ba B Caa
1: A-A 1 4 4 6 2 1
2: A-Aa 1 1 0 2 0 0
3: A-B 0 1 0 2 3 0
4: A-Ba 0 1 4 11 8 1
5: A-Baa 1 3 11 4 6 0
6: A-Caa 0 1 0 0 3 1
7: Aa-A 1 6 1 0 0 0
8: Aa-Aa 1 0 1 0 1 0
9: Aa-B 0 0 0 3 2 0
10: Aa-Ba 0 0 1 6 1 1
11: Aa-Baa 0 2 1 4 1 0
12: Aa-Caa 0 0 0 0 0 1
13: B-A 0 2 2 4 0 3
14: B-Aa 0 1 1 3 2 0
15: B-B 2 3 19 45 181 117
16: B-Ba 0 5 13 42 56 32
17: B-Baa 0 0 16 5 20 5
18: B-Caa 3 3 8 29 91 149
19: Ba-A 1 2 7 5 1 0
20: Ba-Aa 0 1 1 0 1 0
21: Ba-B 0 1 10 38 60 38
22: Ba-Ba 1 4 29 49 39 17
23: Ba-Baa 1 7 17 20 20 7
24: Ba-Caa 0 2 5 11 27 39
25: Baa-A 1 6 7 7 1 0
26: Baa-Aa 0 2 0 2 1 0
27: Baa-B 3 2 5 21 17 17
28: Baa-Ba 1 4 19 18 13 10
29: Baa-Baa 1 8 32 25 13 6
30: Baa-Caa 0 0 1 6 9 6
31: Caa-A 0 1 1 3 2 1
32: Caa-Aa 1 0 1 1 0 1
33: Caa-B 2 5 14 38 105 107
34: Caa-Ba 1 1 6 22 25 22
35: Caa-Baa 1 1 4 5 5 3
36: Caa-Caa 1 2 5 33 149 362
rn Aa A Baa Ba B Caa
data.table中“ rn”列中的值必须是我的矩阵的行名,而“ Aa”到“ Caa”列应按我的矩阵的列名。
所需的输出是:
Aa A Baa Ba B Caa
A-A 1 4 4 6 2 1
A-Aa 1 1 0 2 0 0
A-B 0 1 0 2 3 0
A-Ba 0 1 4 11 8 1
A-Baa 1 3 11 4 6 0
A-Caa 0 1 0 0 3 1
Aa-A 1 6 1 0 0 0
Aa-Aa 1 0 1 0 1 0
Aa-B 0 0 0 3 2 0
Aa-Ba 0 0 1 6 1 1
Aa-Baa 0 2 1 4 1 0
Aa-Caa 0 0 0 0 0 1
B-A 0 2 2 4 0 3
B-Aa 0 1 1 3 2 0
B-B 2 3 19 45 181 117
B-Ba 0 5 13 42 56 32
B-Baa 0 0 16 5 20 5
B-Caa 3 3 8 29 91 149
Ba-A 1 2 7 5 1 0
Ba-Aa 0 1 1 0 1 0
Ba-B 0 1 10 38 60 38
Ba-Ba 1 4 29 49 39 17
Ba-Baa 1 7 17 20 20 7
Ba-Caa 0 2 5 11 27 39
Baa-A 1 6 7 7 1 0
Baa-Aa 0 2 0 2 1 0
Baa-B 3 2 5 21 17 17
Baa-Ba 1 4 19 18 13 10
Baa-Baa 1 8 32 25 13 6
Baa-Caa 0 0 1 6 9 6
Caa-A 0 1 1 3 2 1
Caa-Aa 1 0 1 1 0 1
Caa-B 2 5 14 38 105 107
Caa-Ba 1 1 6 22 25 22
Caa-Baa 1 1 4 5 5 3
Caa-Caa 1 2 5 33 149 362
我该怎么办?
答案 0 :(得分:2)
我们在删除第一列后将其转换为let array = {
"parent": [{
"child": {
"0": 1,
"1": 1,
"2": 1
}
}]
};
console.log(Object.keys(array.parent[0].child).length);
,并将行名设置为第一列
matrix