-3

I have the following data

> df
X1  X2  X3 
1   3   4  
1   0   0  
1   1   0 

and I want to merge all the column so that the final output will be

new colName
1     X1
1     X1
1     X1
3     X2
0     X2
1     X2
4     X3
0     X3
0     X3
Dharman
  • 30,962
  • 25
  • 85
  • 135
Rahul Agrawal
  • 303
  • 3
  • 12

3 Answers3

1

You can try stack

> setNames(stack(df),c("new","colName"))
  new colName
1   1      X1
2   1      X1
3   1      X1
4   3      X2
5   0      X2
6   1      X2
7   4      X3
8   0      X3
9   0      X3

Data

> dput(df)
structure(list(X1 = c(1L, 1L, 1L), X2 = c(3L, 0L, 1L), X3 = c(4L, 
0L, 0L)), class = "data.frame", row.names = c(NA, -3L))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0
library (tidyverse)



pivot_longer(df,X1:X3)
Bruno
  • 4,109
  • 1
  • 9
  • 27
0

You can try gathering the column names with tidyr

library(tidyr)

X1 <- c(1,1,1)
X2 <- c(3,0,1)
X3 <- c(4,0,0)

df <- data.frame(X1, X2, X3)

df <- df %>%
  gather(new, colname, X1, X2, X3)

print(df)

  new colname
1  X1       1
2  X1       1
3  X1       1
4  X2       3
5  X2       0
6  X2       1
7  X3       4
8  X3       0
9  X3       0
Joe Marin
  • 61
  • 2