Reputation: 23
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
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
Reputation: 887168
We can use pivot_longer
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = everything())
Upvotes: 1
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