How to make multiple columns of independent values into 2 column in R

35 Views Asked by At

If I have data that looks like this

Condition 1 Condition 2
11 41
17 45

where the numeric values are length.

Is there a way to change the data so that it looks like this instead

Condition length
Condition 1 11
Condition 1 17
Condition 2 41
Condition 2 45

I've looked at transpose, unite, and pivot_longer. But it seemed like it wouldn't give me the results I was looking for. Does anybody have any suggestions?

1

There are 1 best solutions below

0
IRTFM On

The base function stack is a straightforward way to accomplish this:

inp <- read.table(text="Condition_1 | Condition_2 # remove the extraneous "pipes"
  11          | 41 
      17          | 45 " , head=T,sep="|")
stack(inp)
  values         ind
1     11 Condition_1
2     17 Condition_1
3     41 Condition_2
4     45 Condition_2

stack(inp)[2:1]   # swap columns with "["
          ind values
1 Condition_1     11
2 Condition_1     17
3 Condition_2     41
4 Condition_2     45

I'm sure that there must be a pivot_longer approach that will work as well.