简体   繁体   中英

How to set levels of a factor to be columns in R?

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

在此处输入图像描述

I want to make it to be

在此处输入图像描述

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.)

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          

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM