maxie maxie - 1 month ago 7
R Question

R: Combine entries of contingency table in character vector

I have a data.frame and made a contingency table of one column

> table(data$COLX)

AAAAAAA BBBBBBB CCCCCCC DDDDDDD EEEEEEE FFFFFFF
2254 3399 3163 2040 7710 2368


With
unique(data$COLX)
I get a character vector with
AAAAAAA BBBBBBB ...


How can I create a character vector that also contains the amount of occurences?

What I want to achieve is a character vector that looks like this

AAAAAAA (2254x) BBBBBBB (3399x) ...

Answer

This is what you are looking for:

x <- table(data$COLX)
paste(names(x), paste0("(", x, ")") )

Example

f <- gl(4, 4, labels = letters[1:4])
x <- table(f)
paste(names(x), paste0("(", x, ")") )
# [1] "a (4)" "b (4)" "c (4)" "d (4)"
Comments