0

I am investigating dairy stable types which have a certain code. I want to display, per farm, which types of stables there are present. In my data, every stable has it's own row, so there are multiple rows per farm when a farm has multiple stables. But I want to transform it so that every farm has one row, and each stable has it's own column.

Farm ID Stable type
1 A10
1 A20
1 A30
2 A10
2 A20
3 A10

Desired output =

Farm ID Stable1 Stable2 Stable3
1 A10 A20 A30
2 A10 A20 NA
3 A10 NA NA

Gijs
  • 1
  • use `pivot_wider` from the `tidyr` package – Cettt Jul 13 '23 at 13:43
  • Here's all you need: https://tidyr.tidyverse.org/reference/pivot_wider.html, and welcome to stack overflow. – Paul Stafford Allen Jul 13 '23 at 13:43
  • 1
    With `library(dplyr)` and `library(tidyr)` you can do `your_data |> mutate(row_id = row_number(), .by = FarmID) |> pivot_wider(names_from = row_id, values_from = Stable_type, names_prefix = "Stable")`, updating to your actual data and column names, of course. – Gregor Thomas Jul 13 '23 at 13:45
  • Hi, you're looking into reshaping your data structure from long format to wide format. There are several functions that can do this and it has been asked before (by many others, too), so this is a duplicated question. Here is a link to the same question with many solutions: https://stackoverflow.com/q/5890584/6288065 – LC-datascientist Jul 13 '23 at 13:46

0 Answers0