0

I am trying take a valuable from the rows and make them into columns in are.

Unit      Position    count
hospital  fulltime    20
hospital  parttime    100
hospital  volunteer   50
Police    fulltime    20
police    parttime    5
police    volunteer   10
fire      fulltime    20
fire      parttime    1
fire      volunteer   5

Unit      Fulltime    Parttime   Volunteer Total
Hospital  20          100        50        170
Police    20          5          10        35
Fire      20          1          5         26

Thank you all for your assistance

Kit
  • 27
  • 5
  • 2
    Hi Kit. This is known as reshaping your data from long format to wide format. It is a common data manipulation in R and has been answered many times before on Stack Overflow. There are are many ways to do it, and you will find some in the linked duplicate. – Allan Cameron Nov 22 '20 at 19:57
  • 1
    We could use `xtabs(count ~ Unit + Position, df1)` from `base R` – akrun Nov 22 '20 at 20:03

1 Answers1

0

What you're trying to do is pivot the data into wide shape this can be easily achieved with the tidyr::pivot_wider function, all you need to do is specify the columns from where the values will be taken and columns that contain the name for those values:

library(tidyverse)
df %>% pivot_wider(names_from=Position, values_from=count)
# A tibble: 4 x 4
  Unit     fulltime parttime volunteer
  <fct>       <int>    <int>     <int>
1 hospital       20      100        50
2 Police         20       NA        NA
3 police         NA        5        10
4 fire           20        1         5

data

read.table(text="Unit,Position,count
hospital,fulltime,20
hospital,parttime,100
hospital,volunteer,50
Police,fulltime,20
police,parttime,5
police,volunteer,10
fire,fulltime,20
fire,parttime,1
fire,volunteer,5", header=T, sep=',') -> df

One thing to keep in mind is when asking a question you need to provide the data in code form not in screenshots, one handy function to achieve this is the dput function after running dput(data.f) paste it to your question.

Abdessabour Mtk
  • 3,895
  • 2
  • 14
  • 21