Home > other >  Flatten output of table whilst retaining names
Flatten output of table whilst retaining names

Time:03-03

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.

CodePudding user response:

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

  •  Tags:  
  • r
  • Related