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

Time:10-25

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.

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

CodePudding user response:

You can use attr to extract the labels.

attr(ft, "col.vars")$data
#attr(ft, "col.vars")[[1]] #Alternative
#[1] "a" "b" "c"
  •  Tags:  
  • r
  • Related