Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract the column names of a (flat) contingency table?

Assume we have the following:

data = c("a", "b", "a", "a", "b", "c", "a", "b")
ft = ftable(data)

# This yields:
#   data a b c
#            
#       4 3 1 

I would like to extract the labels "a", "b" and "c" from ft. How?

I know that there is colnames(), or rownames(), or names(), but neither works. I also know that I could convert the ftable into a data frame, and read it from there. But it seems a bit odd to me to convert a data object before I can access its own data.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# Things that seem to work, but require a "detour":

# Convert to data frame and read column
as.data.frame(ft)$data
as_tibble(ft)$data

# Use table instead of ftable
rownames(as.table(ft))
rownames(table(data))

>Solution :

You can use attr to extract the labels.

attr(ft, "col.vars")$data
#attr(ft, "col.vars")[[1]] #Alternative
#[1] "a" "b" "c"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading