-1

Quite new to R and I have a dataset in this format:

A  B  C
1  1  1
2  2  2
3  3  3
4  4  4
5  5  5

But I want it in this format:

A  1
A  2
A  3
A  4
A  5
B  1
B  2
B  3
...etc.

Seems like such a simple issue but I need HELP! Thanks 

3 Answers3

2
df <- data.frame(
  A = 1:5,
  B = 1:5,
  C = 1:5
)

stack(df)
   values ind
1       1   A
2       2   A
3       3   A
4       4   A
5       5   A
6       1   B
7       2   B
8       3   B
9       4   B
10      5   B
11      1   C
12      2   C
13      3   C
14      4   C
15      5   C
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
1

Examples using dplyr's gather function:

library(tidyverse)
    
A <- c(1,2,3,4,5)
B <- c(1,2,3,4,5)
C <- c(1,2,3,4,5)
    
df <- data.frame(A,B,C)
    
df %>% gather(key = "key", value = "value")

   key value
1    a     1
2    a     2
3    a     3
4    a     4
5    a     5
6    b     1
7    b     2
8    b     3
9    b     4
10   b     5
11   c     1
12   c     2
13   c     3
14   c     4
15   c     5
denisafonin
  • 1,116
  • 1
  • 7
  • 16
1

You can use the package tidyr. This let's you choose, which columns you want to gather in the column "variable".

# if not installed yet
install.packages("tidyr")
library(tidyr)
data <- data.frame(
      A = 1:5,
      B = 1:5,
      C = 1:5
    )
data %>% pivot_longer(c(A, B, C), names_to = "variable", values_to = "value")

# Result    
   variable value
   <chr>    <int>
 1 A            1
 2 B            1
 3 C            1
 4 A            2
 5 B            2
 6 C            2
 7 A            3
 8 B            3
 9 C            3
10 A            4
11 B            4
12 C            4
13 A            5
14 B            5
15 C            5
elehna
  • 106
  • 5