简体   繁体   中英

how to transpose different groups from column to row in R or excel

I searched a few answers but it seems none can answer my question

I have a data look like this (2 columns, 2 groups group"1" and group"2")

  • 1 10
  • 1 20
  • 1 50
  • 2 40
  • 2 30
  • 2 60

and I want to transpose it from column to row by each group the result will look like this

  • 1 1 1
  • 10 20 50
  • 2 2 2
  • 40 30 60

Since I have a lot of groups, I cannot manually do it one by one. Could anyone please help me? Thank you.

Thanks guys, since all groups have the same length (inspired by the comment from Floris), actually I can simply just use matrix to solve the problem

    x=read.table(header=F,text="10 20 50 40 30 60")
    matrix(x,nrow=2,byrow=T)
x <- read.table(header=F, text="1 10
1 20
1 50
2 40
2 30
2 60")

do.call(rbind, by(x, x$V1, FUN=t))
##     1  2  3
## V1  1  1  1
## V2 10 20 50
## V1  2  2  2
## V2 40 30 60

If you know how to use VBA, it's pretty trivial to write a short sub() that will do this for you. I am hard coding the address - you can figure out how to move it around. I am assuming your data is on the active sheet when you call this macro, and you want the copies to appear to the right of the original (which are in columns A and B, starting in row 2 - giving you space for a label above). Also I am going to assume that your groups are numbered 1, 2, 3... and that you don't need their values copying. Then the code looks like this (press F-11 to open the VBA editor, insert a module, and copy this)

Sub bigSwap()
dim R as Range, c as Range
dim grp
dim grpCount(1 To 100) ' assuming no more than 100 groups, or adjust this number
dim i

' just making sure it's properly initialized
for i=1 To 100
  grpCount(ii)=0
next i


Set R = Range("B2", [B2].End(xlDown)) ' this finds all the cells with values
' note - I am using [B2] as shorthand for Range("B2")

For each c in R.cells
  grp = c.offset(0, -1).value  ' find the corresponding group
  [D1].offset(grp, grpCount(grp)).value = c.value
  grpCount(grp) = grpCount(grp)+1  ' keep track of # in this row
next

End Sub

I was not able to test this, but I believe it's good. If you run into issues, just leave a comment.

Transpose cluster of cell from column to rows

Assuming that A2:A16 contains the data, try...

C2, copied across and down:

=INDEX($A$2:$A$16,ROWS(C$2:C2)*3-3+COLUMNS($C2:C2))

Adjust the references, accordingly.

Try for one row first then do the next and then merge

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