fquaker
fquaker

Reputation: 23

Modify a data frame converting colnames into factor

I´m analyzing some data structured as "df" in the example and I need to convert it into something like the "example" object below:

a<- c(1:3)
b<- c(1:3)
c<- c(1:3)

df<- data.frame(a, b, c)

col1<- c("a","a","a", "b", "b", "b", "c", "c", "c")
col2<- rep(1:3,3)

example<- data.frame(col1, col2)

Upvotes: 2

Views: 35

Answers (3)

nsinghphd
nsinghphd

Reputation: 2022

You can also use gather() from tidyr package

gather(df, colnames(df), key = "col1", value = "col2")

key and value serves as new column names in the resulting dataframe. Use in tidyverse syntax as follows

df %>%
   gather(colnames(df), key = "col1", value = "col2")

Upvotes: 0

akrun
akrun

Reputation: 887168

We can use pivot_longer

library(dplyr)
library(tidyr)
df %>% 
    pivot_longer(cols = everything())

Upvotes: 1

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

A quick base R solution is stack:

stack(df)
  values ind
1      1   a
2      2   a
3      3   a
4      1   b
5      2   b
6      3   b
7      1   c
8      2   c
9      3   c

Upvotes: 1

Related Questions