我觉得有点可耻地提出这个问题,但是我没有使用datatables
几个月而且我忘记了丢失的东西。我花了两个小时来搜索文档,但没有成功。然而,这是一个微不足道的问题。
我有这个数据表:
DT = data.table(CJ(r=c(0,1,2),phi=c(1,2,3),theta=c(10,11,12)))
DT
> DT
r phi theta
1: 0 1 10
2: 0 1 11
3: 0 1 12
4: 0 2 10
5: 0 2 11
6: 0 2 12
7: 0 3 10
8: 0 3 11
9: 0 3 12
10: 1 1 10
11: 1 1 11
12: 1 1 12
13: 1 2 10
14: 1 2 11
15: 1 2 12
16: 1 3 10
17: 1 3 11
18: 1 3 12
19: 2 1 10
20: 2 1 11
21: 2 1 12
22: 2 2 10
23: 2 2 11
24: 2 2 12
25: 2 3 10
26: 2 3 11
27: 2 3 12
r phi theta
如你所见,它有27行。现在我想对每一行应用矢量值。天真地:
f <- function(r, phi, theta) (2*r, 2*phi 3*theta)
然后
> DT[,f(r, phi, theta), by="r,phi,theta"]
r phi theta V1
1: 0 1 10 0.00000
2: 0 1 10 0.00000
3: 0 1 10 0.00000
4: 0 1 11 0.00000
5: 0 1 11 0.00000
6: 0 1 11 0.00000
7: 0 1 12 0.00000
8: 0 1 12 0.00000
9: 0 1 12 0.00000
10: 0 2 10 0.00000
11: 0 2 10 0.00000
12: 0 2 10 0.00000
13: 0 2 11 0.00000
14: 0 2 11 0.00000
15: 0 2 11 0.00000
16: 0 2 12 0.00000
17: 0 2 12 0.00000
18: 0 2 12 0.00000
19: 0 3 10 0.00000
20: 0 3 10 0.00000
21: 0 3 10 0.00000
22: 0 3 11 0.00000
23: 0 3 11 0.00000
24: 0 3 11 0.00000
25: 0 3 12 0.00000
26: 0 3 12 0.00000
27: 0 3 12 0.00000
28: 1 1 10 -0.29394
29: 1 1 10 -0.45778
30: 1 1 10 -0.83907
31: 1 1 11 -0.54030
32: 1 1 11 -0.84146
33: 1 1 11 0.00443
34: 1 1 12 -0.28991
35: 1 1 12 -0.45151
36: 1 1 12 0.84385
37: 1 2 10 0.22639
38: 1 2 10 -0.49468
39: 1 2 10 -0.83907
40: 1 2 11 0.41614
41: 1 2 11 -0.90929
42: 1 2 11 0.00443
43: 1 2 12 0.22329
44: 1 2 12 -0.48790
45: 1 2 12 0.84385
46: 1 3 10 0.53858
47: 1 3 10 -0.07677
48: 1 3 10 -0.83907
49: 1 3 11 0.98998
50: 1 3 11 -0.14112
51: 1 3 11 0.00443
52: 1 3 12 0.53120
53: 1 3 12 -0.07572
54: 1 3 12 0.84385
55: 2 1 10 -0.58787
56: 2 1 10 -0.91556
57: 2 1 10 -1.67814
58: 2 1 11 -1.08059
59: 2 1 11 -1.68293
60: 2 1 11 0.00885
61: 2 1 12 -0.57982
62: 2 1 12 -0.90302
63: 2 1 12 1.68771
64: 2 2 10 0.45279
65: 2 2 10 -0.98935
66: 2 2 10 -1.67814
67: 2 2 11 0.83229
68: 2 2 11 -1.81858
69: 2 2 11 0.00885
70: 2 2 12 0.44659
71: 2 2 12 -0.97581
72: 2 2 12 1.68771
73: 2 3 10 1.07715
74: 2 3 10 -0.15354
75: 2 3 10 -1.67814
76: 2 3 11 1.97997
77: 2 3 11 -0.28224
78: 2 3 11 0.00885
79: 2 3 12 1.06241
80: 2 3 12 -0.15144
81: 2 3 12 1.68771
r phi theta V1
resulat有81列。这不是我想要的。我想要27列,每列有3个值。该怎么做?
答案 0 :(得分:1)
首先,让f返回一个列表:
f <- function(r, phi, theta) list(2*r, 2*phi, 3*theta)
接下来,如果要为新列命名f1,f2和f3:
DT[,c('f1','f2','f3'):=f(r,phi,theta)]
DT
r phi theta f1 f2 f3
1: 0 1 10 0 2 30
2: 0 1 11 0 2 33
3: 0 1 12 0 2 36
4: 0 2 10 0 4 30
5: 0 2 11 0 4 33
6: 0 2 12 0 4 36
7: 0 3 10 0 6 30
8: 0 3 11 0 6 33
9: 0 3 12 0 6 36
10: 1 1 10 2 2 30
11: 1 1 11 2 2 33
12: 1 1 12 2 2 36
13: 1 2 10 2 4 30
14: 1 2 11 2 4 33
15: 1 2 12 2 4 36
16: 1 3 10 2 6 30
17: 1 3 11 2 6 33
18: 1 3 12 2 6 36
19: 2 1 10 4 2 30
20: 2 1 11 4 2 33
21: 2 1 12 4 2 36
22: 2 2 10 4 4 30
23: 2 2 11 4 4 33
24: 2 2 12 4 4 36
25: 2 3 10 4 6 30
26: 2 3 11 4 6 33
27: 2 3 12 4 6 36
r phi theta f1 f2 f3