cs0815
cs0815

Reputation: 17388

transform output similar to table to string

I have:

df <- data.frame(x = c("a", "a", "b"))

This:

table(df$x)

produces this:

a b 
2 1 

I would like to produce a string with the same information as table like so:

a:2 b:1

So given a vector (column of a dataframe I suppose). Is this possible?

Upvotes: 0

Views: 362

Answers (2)

Karthik S
Karthik S

Reputation: 11584

does this work:

library(dplyr)
df %>% group_by(x) %>% summarise(cnt = n()) %>% mutate(str = paste0(x,':',cnt)) %>% pull(str)
`summarise()` ungrouping output (override with `.groups` argument)
[1] "a:2" "b:1"

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388907

You can use paste :

tmp <- table(df$x)
paste(names(tmp), tmp, sep = ':')
#[1] "a:2" "b:1"

Or as one string :

paste(names(tmp), tmp, sep = ':', collapse = ' ')
[1] "a:2 b:1"

Upvotes: 2

Related Questions