简体   繁体   中英

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)

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

We can use pivot_longer

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM