0

I'm working on r. I would like to ask for help converting my df into a different df1 to work with it: The current df look like this:

|--------|----|-----------|-----------|-----------|
| Entity | ID | Category1 | Category2 | Category3 |
|--------|----|-----------|-----------|-----------|
|   AB   | 01 |     00    |     01    |     01    |
|   AC   | 02 |     00    |     01    |     00    |
|--------|----|-----------|-----------|-----------|

I need to convert it in something like this:

Entity ID  Categories  Value
AB     01  Category1     00
AB     01  Category2     01
AB     01  Category3     01
AC     02  Category1     00
AC     02  Category2     01
AC     02  Category3     00

The transposing function does not help because as you can see I need the categories to be copied vertically one after the other. I really need help with this as my df is extremely big to do it manually, and I would highly appreciate your help R community. Please!!

Data in dput format

data <-
structure(list(Entity = c("AB", "AC"), ID = c(1, 2), Category1 = c(0, 
0), Category2 = c(1, 1), Category3 = c(1, 0)), row.names = c(NA, 
-2L), class = "data.frame")
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66

1 Answers1

1

Assuming your data looks like this:

#   Entity ID Category1 Category2 Category3
# 1     AB 01        00        01        01
# 2     AC 02        00        01        00

You can do:

library(tidyr)

gather(data, key = "Category", value = "Value", Category1, Category2, Category3)

#   Entity ID  Category Value
# 1     AB 01 Category1    00
# 2     AC 02 Category1    00
# 3     AB 01 Category2    01
# 4     AC 02 Category2    01
# 5     AB 01 Category3    01
# 6     AC 02 Category3    00

where data is your data frame.

Count Orlok
  • 997
  • 4
  • 13
  • Thanks so much, it is working, I'm super grateful for your so super-fast help. Thank you count orlok you did my day, I have been struggling with this like crazy. Thank you! – Diana Carolina Suarez Jul 05 '20 at 16:42