0

I have the following data frame:

a<-c(1,3,5,6)
b<-c(5,8,9,10)
df<-data.frame(a,b)
colnames(df)<-c('tata','toto')
> df
  tata toto
1    1    5
2    3    8
3    5    9
4    6   10

Now, I would like to create a new data.frame, which would look like this:

> df1
  all  rep
1   1 toto
2   3 toto
3   5 toto
4   6 toto
5   5 tata
6   8 tata
7   9 tata
8  10 tata

if df has 2 columns it is easy to do so with

rep1<-c(rep('toto',length(a)))
rep2<-c(rep('tata',length(a)))
rep<-c(rep1,rep2)
all<-c(a,b)
df1<-data.frame(all,rep)

As I have 98 columns, I am wondering if there is a efficient to do it. Many thanks

2 Answers2

0

you can also use gather maybe

library(tidyr)
gather(df,key="rep", value = "all")
Senzeybek
  • 151
  • 5
0

Or, with the newest verson of tidyr::gather() since it is not "retired":

pivot_longer(df, cols = everything(), names_to = "rep", values_to = "all")
meriops
  • 997
  • 7
  • 6