0

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?

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.