简体   繁体   中英

Combine two consecutive rows in a dataframe

I have a dataframe price.hierarchy

 read.table(header=TRUE, text=
"  WEEK PRICE  QUANTITY SALE_PRICE TYPE
1  4992  3.49 11541.600       3.49    1
2  5001  3.00 38944.000       3.00    1
3  5002  3.49 10652.667       3.49    1
4  5008  3.00 21445.000       3.00    1
5  5009  3.49 10039.667       3.49    1
6  5014  3.33 22624.000       3.33    1
7  5015  3.49  9146.500       3.49    1
8  5027  3.33 14751.000       3.33    1
9  5028  3.49  9146.667       3.49    1
10 5034  3.33 18304.000       3.33    1
11 5035  3.49 10953.500       3.49    1")

I want output like

read.table(header=F, text=
"1  4992 3.49 11541.600 3.49  1 5001 3.00 38944.000 3.00   1
 2  5001 3.00 38944.000 3.00  1 5002 3.49 10652.667 3.49   1
 3  5002 3.49 10652.667 3.49  1 5008 3.00 21445.000 3.00   1
 4  5008 3.00 21445.000 3.00  1 5009 3.49 10039.667 3.49   1
 5  5009 3.49 10039.667 3.49  1 5014 3.33 22624.000 3.33   1
 6  5014 3.33 22624.000 3.33  1 5015 3.49  9146.500 3.49   1
 7  5015 3.49  9146.500 3.49  1 5027 3.33 14751.000 3.33   1
 8  5027 3.33 14751.000 3.33  1 5028 3.49  9146.667 3.49   1
 9  5028 3.49  9146.667 3.49  1 5034 3.33 18304.000 3.33   1
 10 5034 3.33 18304.000 3.33  1 5035 3.49 10953.500 3.49   1")

I am trying to combine first and second row, second and third row etc at the end from the same data frame.

I tried

price.hierarchy1 <- price.hierarchy[c(1: (nrow(price.hierarchy)-1)), ] 
price.hierarchy2 <- price.hierarchy[c(2: nrow(price.hierarchy)), ] 
price.hierarchy3 <- cbind(price.hierarchy1, price.hierarchy2) 
price.hierarchy3 <- unique(price.hierarchy3)

另一个变体是

cbind(df1[-nrow(df1),], df1[-1,])

First dispart the rows, then cbind()

cbind(df[1:(nrow(df)-1),], df[2:nrow(df),])

or

cbind(head(df,-1), tail(df,-1))

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