0

Can somebody please help me find a solution.

So what I am trying to do here is to break down a wide table into a 3 column table as such:

  1. the first column is simply the ID
  2. The second column is the header of the wide column
  3. The thirdt column is the value associated to the ID in the relevant column.

for exemple, say that I have a table looking like this:

id    first_name  last_name    
1     John        Doe
2     Luke        Skywalker

And I would like to make it something like this:

id    field            value
1     first_name       John
1     last_name        Doe
2     first_name       Luke
2     last_name        Skywalker

I am sure that there is a basic function doing that, but I really can't find it... Thanks for your help!

Trajiko
  • 3
  • 1

1 Answers1

0

You could use the gather() function from the tidyr package.

df <- tribble(
  ~id, ~first_name, ~last_name,
  1, "John",  "Doe",
  2, "Luke", "Skywalker"
)

df %>% 
  gather(field, value, first_name:last_name) %>%
  arrange(id)

You can also read about other methods of converting wide to long data sets on the Cookbook for R.

tonybot
  • 643
  • 2
  • 10