I want to create new table which is pair of 2 continue rows from my old table.
我想创建一个新表,它是我旧表中的2对连续行。
A B
1 a
2 b
3 c
4 d
5 e
I want to create new table as below.
我想创建如下的新表。
A1 B1 A2 B2
1 a 2 b
2 b 3 c
3 c 4 d
4 d 5 e
I want to find simple solution for this case.
我想为这种情况找到简单的解决方案。
3 个解决方案
#1
From your problem statement, I think this should be a solution
从您的问题陈述中,我认为这应该是一个解决方案
newtable <- cbind(oldtable[-nrow(oldtable), ], oldtable[-1, ])
colnames(newtable) <- paste0(c("A", "B"), rep(1:2, each = 2))
#2
You may also use shift
from the devel version of data.table
ie. v1.9.5+
. Instructions to install are here
你也可以使用devel版本的data.table来换班。 v1.9.5 +。安装说明在这里
library(data.table)
setDT(df1)[, paste0(names(df1),2):= shift(.SD, type='lead')][-.N]
# A B A2 B2
#1: 1 a 2 b
#2: 2 b 3 c
#3: 3 c 4 d
#4: 4 d 5 e
data
df1 <- structure(list(A = 1:5, B = c("a", "b", "c", "d", "e")),
.Names = c("A", "B"), class = "data.frame", row.names = c(NA, -5L))
#3
I found the answer for my question
我找到了问题的答案
DT <- data.table(A=c(1:5), B=letters[1:5])
DT[, data.table(.SD, DT[.I + 1][, .(A1=A, B1=B)]), by=.I][-.N]
Update to add the short version of @B.Shankar
更新以添加@ B.Shankar的简短版本
cbind(DT[-.N], DT[-1][, .(A1=A, B1=B)])
#1
From your problem statement, I think this should be a solution
从您的问题陈述中,我认为这应该是一个解决方案
newtable <- cbind(oldtable[-nrow(oldtable), ], oldtable[-1, ])
colnames(newtable) <- paste0(c("A", "B"), rep(1:2, each = 2))
#2
You may also use shift
from the devel version of data.table
ie. v1.9.5+
. Instructions to install are here
你也可以使用devel版本的data.table来换班。 v1.9.5 +。安装说明在这里
library(data.table)
setDT(df1)[, paste0(names(df1),2):= shift(.SD, type='lead')][-.N]
# A B A2 B2
#1: 1 a 2 b
#2: 2 b 3 c
#3: 3 c 4 d
#4: 4 d 5 e
data
df1 <- structure(list(A = 1:5, B = c("a", "b", "c", "d", "e")),
.Names = c("A", "B"), class = "data.frame", row.names = c(NA, -5L))
#3
I found the answer for my question
我找到了问题的答案
DT <- data.table(A=c(1:5), B=letters[1:5])
DT[, data.table(.SD, DT[.I + 1][, .(A1=A, B1=B)]), by=.I][-.N]
Update to add the short version of @B.Shankar
更新以添加@ B.Shankar的简短版本
cbind(DT[-.N], DT[-1][, .(A1=A, B1=B)])