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

Flatten output of table whilst retaining names

How can I flatten the output of R’s base::table function (applied to columns of a dataframe) in order to return an integer vector with names according to the convention specified below?

set.seed(123); N <- 100
df <- data.frame(A = sample(c("GOOD", "BAD"), N, TRUE, c(0.4, 0.6)), 
                 B = sample(c("GOOD", "BAD"), N, TRUE, c(0.7, 0.3)))
table(df)
#       B
# A      BAD GOOD
# BAD   16   44
# GOOD  10   30

# Desired output (naming convention: A-B)
# BAD-BAD  GOOD-BAD  BAD-GOOD  GOOD-GOOD
#      16        10        44         30

Using as.vector(table(df)) drops names, which I’d like to retain in one step for use downstream for example, in case the ordering of factors changes or to enable "toggling" of useNA = "always" when calling table whilst not having to manually track the positions of the respective cells in the output vector.

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

>Solution :

From memory (currently no access to R):

table(interaction(df$A, df$B, sep = "-"))

Could be that you need to specify the correct separator to interaction

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