Home > Back-end >  How to set levels of a factor to be columns in R?
How to set levels of a factor to be columns in R?

Time:12-08

Here I have a table

tab <- matrix(c('AL', 'Accident', 14, 19, 'AR', 'Accident', 17, 6, 'AL', 'Disease', 14, 19, 'AR', 'Disease', 17, 6), ncol=4, byrow=TRUE)
colnames(tab) <- c('State','Cause','under30', 'above30')
rownames(tab) <- c(1,2,3,4)
tab <- as.table(tab)
tab

which looks like

enter image description here

I want to make it to be

enter image description here

But I don't know how to do it, is there any hint or help? Thanks in advance. (This is only a simplified version of my dataset, the actual dataset is much bigger. What I am looking for is a generalized method.)

CodePudding user response:

Consider converting to data.frame and then use pivot_wider

library(tidyr)
pivot_wider(as.data.frame.matrix(tab), names_from = Cause,
      values_from = c(under30, above30), names_glue = "{Cause}_{.value}")

-output

# A tibble: 2 × 5
  State Accident_under30 Disease_under30 Accident_above30 Disease_above30
  <chr> <chr>            <chr>           <chr>            <chr>          
1 AL    14               14              19               19             
2 AR    17               17              6                6          

CodePudding user response:

In base R:

reshape(as.data.frame.matrix(tab),
     dir='wide', idvar = 'State', timevar = 'Cause', sep='_')

  State under30_Accident above30_Accident under30_Disease above30_Disease
1    AL               14               19              14              19
2    AR               17                6              17               6
  • Related