Home > database >  Categorizing data from 7 columns into 2
Categorizing data from 7 columns into 2

Time:12-17

This is my first question from stackoverflow community. I have 7 columns of numerical data with their respective variable names in R. They belong to the same variable i.e. income data collected for 7 years. I want to categorize the data in a way so I have all the numerical data in one column and their respective variable name in the second. How do I do that?

CodePudding user response:

Welcome to stackoverflow: Please see this for the future How to make a great R reproducible example

We could use pivot_longer from the tidyr package:

library(dplyr)
library(tidyr)

# example data
df <- mtcars %>%
  select(1:7) %>% 
  `colnames<-`(LETTERS[1:7])
  
df %>% 
  pivot_longer(
    cols = everything()
  )

output:

   name   value
   <chr>  <dbl>
 1 A      21   
 2 B       6   
 3 C     160   
 4 D     110   
 5 E       3.9 
 6 F       2.62
 7 G      16.5 
 8 A      21   
 9 B       6   
10 C     160   
# ... with 214 more rows
  •  Tags:  
  • r
  • Related