简体   繁体   中英

R data.table pick 2 continue rows to create new table

I want to create new table which is pair of 2 continue rows from my old table.

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.

You may also use shift from the devel version of data.table ie. v1.9.5+ . Instructions to install are here

 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))

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))

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

cbind(DT[-.N], DT[-1][, .(A1=A, B1=B)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM