R 卷起数据表
我有一个数据表:R 卷起数据表,r,data.table,R,Data.table,我有一个数据表: > (mydt <- data.table(id=c(1,1,1,1,2,2), time=1:6, v1=letters[1:6], v2=LETTERS[1:6], key=c("id","time"))) id time v1 v2 1: 1 1 a A 2: 1
> (mydt <- data.table(id=c(1,1,1,1,2,2),
time=1:6,
v1=letters[1:6],
v2=LETTERS[1:6],
key=c("id","time")))
id time v1 v2
1: 1 1 a A
2: 1 2 b B
3: 1 3 c C
4: 1 4 d D
5: 2 5 e E
6: 2 6 f F
感谢您提供了可复制的示例!这是一个机会 首先,请注意,您可以使用以下头尾习惯用法将相隔一定距离的向量项彼此相邻放置:
x <- letters[1:5]
cbind(head(x, -1), tail(x, -1))
# [,1] [,2]
# [1,] "a" "b"
# [2,] "b" "c"
# [3,] "c" "d"
# [4,] "d" "e"
cbind(head(x, -2), tail(x, -2))
# [,1] [,2]
# [1,] "a" "c"
# [2,] "b" "d"
# [3,] "c" "e"
+1但是你应该解释它是如何工作的。你可能会得到更多的投票,这将是非常有用的。@SimonO101我已经对我使用的
头部
/尾部
技巧写了一个小解释。我还可以输入什么?请注意,如果
不是必需的(但会增加速度)。谢谢优秀的格式;可读性强;你用什么编辑器?它能自动缩进吗?@ClaytonStanley换行和缩进是用手工完成的。从一行到下一行“对象”不能“改变”(=时间戳保持不变?)吗?@eddi:不,每个对象的时间戳都是唯一的,也就是说,它们会改变。rollup可能不是最好的名称,google rolllup sql
x <- letters[1:5]
cbind(head(x, -1), tail(x, -1))
# [,1] [,2]
# [1,] "a" "b"
# [2,] "b" "c"
# [3,] "c" "d"
# [4,] "d" "e"
cbind(head(x, -2), tail(x, -2))
# [,1] [,2]
# [1,] "a" "c"
# [2,] "b" "d"
# [3,] "c" "e"
mydt[,{
## if there's just one row in the group of ID's, return nothing
if (.N == 1) return(NULL)
else {
list(
## head and tail take the first and last parts of a vector
## this will place an element next to its subsequent element
beg.time = head(time, -1),
end.time = tail(time, -1),
v1 = head(v1, -1),
v2 = tail(v2, -1)
## group by ID
)}}, by = id]
# id beg.time end.time v1 v2
# 1: 1 1 2 a B
# 2: 1 2 3 b C
# 3: 1 3 4 c D
# 4: 2 5 6 e F