0

I have a data frame which looks like this

beta1   beta2    beta3
 4       67       89
 33       7       78
 6       99       33
etc

Now I want to transform this data frame to a different dataframe which looks like

col1  col2
4     beta1
33    beta1
6     beta1
67    beta2 
etc

So, the columns have to be pasted below eachother and the second column should consist of the colnames of the first data frame. Does anyone know how to do this without loop?

Activation
  • 93
  • 6

3 Answers3

1

This is simply a reshaping (from wide to long) operation. You can use dplyr::gather() function:

library(dplyr)
dat <- data.frame(beta1 = c(4,33,6),beta2 = c(67,7,99), beta3= c(89,78,33))

dat %>% gather(Col1, Col2)
Ismail Müller
  • 395
  • 1
  • 7
1

and the usual data.table approach:

library( data.table )
data <- fread("beta1   beta2    beta3
4       67       89
33       7       78
6       99       33")



melt( data, 
      measure.vars = patterns( "^beta" ), 
      variable.name = "col2", 
      value.name = "col1" )

#     col2 col1
# 1: beta1    4
# 2: beta1   33
# 3: beta1    6
# 4: beta2   67
# 5: beta2    7
# 6: beta2   99
# 7: beta3   89
# 8: beta3   78
# 9: beta3   33
Wimpel
  • 26,031
  • 1
  • 20
  • 37
0
 do.call(rbind,
        lapply(names(df1), function(nm){
            data.frame(col1 = df1[[nm]],
                       col2 = nm)
        }))
#  col1  col2
#1    4 beta1
#2   33 beta1
#3    6 beta1
#4   67 beta2
#5    7 beta2
#6   99 beta2
#7   89 beta3
#8   78 beta3
#9   33 beta3

DATA

df1 = structure(list(beta1 = c(4L, 33L, 6L),
                     beta2 = c(67L, 7L, 99L),
                     beta3 = c(89L, 78L, 33L)),
                class = "data.frame",
                row.names = c(NA, -3L))
d.b
  • 32,245
  • 6
  • 36
  • 77