简体   繁体   中英

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

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

我希望这就是你的意思:

tabl <- structure(c(2254L, 3399L, 3163L, 2040L, 7710L, 2368L), .Dim = 6L, .Dimnames = structure(list(AAAAAAA", "BBBBBBB", "CCCCCCC", "DDDDDDD", "EEEEEEE", "FFFFFFF")), .Names = ""), class = "table") data.frame(tabl)

Var1 Freq 1 AAAAAAA 2254 2 BBBBBBB 3399 3 CCCCCCC 3163 4 DDDDDDD 2040 5 EEEEEEE 7710 6 FFFFFFF 2368

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM