Home > Net >  How to split a column into different columns in R
How to split a column into different columns in R

Time:11-10

I have data in which the education column takes the form from 1 to 3. Payment column - also accepts values from 1 to 3 I wanted to group them in pairs

I have an education and payment column. How can I convert the table so that the payment is divided into 3 different columns enter image description here

I would like the table to look like this: enter image description here

CodePudding user response:

The function pivot_wider from the tidyr package is the way to go:

library(dplyr)
library(dplyr)
df %>%
   pivot_wider(names_from = Education,
               values_from = count,
               names_glue = "Education = {.name}")
# A tibble: 3 × 4
  PaymentTier `Education = 1` `Education = 2` `Education = 3`
        <dbl>           <dbl>           <dbl>           <dbl>
1           1            1000             666            6543
2           2              33            2222            9999
3           3             455            1111            5234

Data:

df <- data.frame(
  Education = c(1,1,1,2,2,2,3,3,3),
  PaymentTier = c(1,2,3,1,2,3,1,2,3),
  count = c(1000,33,455,666,2222,1111,6543,9999,5234)
)
  • Related