Search code examples
rdplyrtidyr

Converting rows to columns with meaningful duplicate rows


I am trying to convert rows to columns using the tidyverse package, but I am getting an error message about duplicate data. However, I need to keep this data.

My data frame looks like this :

Agent Job
Agent A Job 1
Agent B Job 1
Agent A Job 2
Agent C Job 2
Agent B Job 3

I would like to put the agents as rows, so it would have a single row per agent. However, it is important that I see that both job 1 and job 2 have the agent A.

Any help is greatly appreciated!

Here is a sample data frame:

library(tidyverse)
sample.df <- data.frame(Agent = c("Agent A", "Agent B", "Agent A", "Agent C ", "Agent B"),
           Job = c(1,1,2,2,3))

sample.df %>%
  rownames_to_column(sample.df$Agent)

Solution

  • The easiest solution would be to pivot wide. You would see each column that the agent has.

    library(tidyverse)
    sample.df %>%
        pivot_wider(
            names_from = Job,
            values_from = c(Job)
        )