0

Suppose I've a data frame that look as following:

# Animal    Food    2015    2016

Monkey      Banana   54     65
Monkey      Hotdog   43     76
## # ... with 54 more rows

And I would like to separate the Banana and Hotdog variable so the data frame looks like this:

# Animal    Year   Banana  Hotdog

Monkey      2015    54      43
Monkey      2016    65      76
## # ... with 54 more rows

What function should I use in the tidyverse package?

  • `library(tidyr); pivot_longer(dat, -c(Animal, Food), names_to = "Year") %>% pivot_wider(names_from = "Food", values_from = "value")` – r2evans Jul 22 '22 at 20:02
  • I closed as a dupe because it is a perfect dupe of two separate but strongly-related questions. The comment above works perfectly. (I deleted my answer with it because providing an answer and closing as a dupe can be seen as an under-handed way to keep others from providing competing answers while still allowing the answer to be accepted and get the rep-points. I don't care about the points, tbh, so I transferred to the above comment. Lmk if it doesn't work as well for you.) – r2evans Jul 22 '22 at 20:04
  • 1
    Thanks @r2evans . I'll try this code and come back with my results. – Joseph Carthof Jul 22 '22 at 20:05
  • @r2evans Everything works fine except for the second data frame in the new columns "Banana" and "Hotdog" where there is "" instead of the desired numbers. Any ideas? – Joseph Carthof Jul 22 '22 at 20:29
  • 1
    I figured it out, it was my excel data that had a minor error. – Joseph Carthof Jul 22 '22 at 20:53
  • FYI, the `` means that you have more than 1 value for each of your "id" columns. It highlights a missed assumption. In some ways, it suggests one could aggregate the data (pick the min or mean or something), but if you should "never" have dupes, then it means something is wrong, either another id column is needed or the data is messed up. Glad you got it working! – r2evans Jul 22 '22 at 20:58

0 Answers0