简体   繁体   中英

R table function: how to coerce order of column names output of table()

I would like to change the column order output from the table function in R . I can only find information about manipulating column order for data.table (not what I want). The order of the columns ("No" and "Yes") has always been the consistent when I use R (alphabetical order?) but for some reason some of my tables have come back in a different order ("Yes" and "No"). I need these to be consistent (as I am combining some tables) and ordered so that "Yes" is last. I'm making several hundred of these tables with associated statistics and have some custom made formulas to help me out - but I can't afford to double check the order of every table - so I want to tell R what to do specifically. As I am doing chi-square tests I don't want to have to change each table into a data.frame, reorder the columns, and then change back to a table somehow. The order of the table columns is important as I am combining some tables (and R coerces these incorrectly), and also doing odds ratios so I need "Yes" to come last consistently. Out of curiosity (not necessary), someone could explain to me why some of my data produces table columns in alphabetical order but other data doesn't. I've attached a simplified version of my data.

df <- data.frame(treatment = c("A","A","B","A","B","A","B","B"),
    symptom = c("Yes","Yes","No","No","Yes","Yes","Yes","No"))
table(df)

As this example produces my desired table column order please write code to change the column order from "No", "Yes" to "Yes", "No"

We can use factor with levels specified because the order ing is based on the alphabetic order where "N" comes before "Y" (first letter and so on). This could be changed by converting to factor with levels in the custom order.

table(df$treatment, factor(df$symptom, levels = c("Yes", "No")))
#     Yes No
#  A   3  1
#  B   2  2

Or use transform and then do the table

table(transform(df, symptom = factor(symptom, levels = c("Yes", "No"))))
#         symptom
#treatment Yes No
#       A   3  1
#       B   2  2

However, we can do this after the table by specifying the order (either column index or column names) but this would become more tedious if we don't know which are the levels

table(df)[, 2:1]
#        symptom
#treatment Yes No
#       A   3  1
#       B   2  2

You can order it the way you want:

table(df)[,2:1]
         symptom
treatment Yes No
        A   3  1
        B   2  2
table(df)[,c("Yes","No")]
         symptom
treatment Yes No
        A   3  1
        B   2  2

 levels=c("Yes","No")
 table(df)[,levels]
             symptom
    treatment Yes No
            A   3  1
            B   2  2

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