Count each character and store as pair


Count each character and store as <K,V> pair



How can I count the unique characters from a given string and store it as a key - value pair in R programming using the base package? Here key will be the distinct character and value will be the occurrence of the character within the string.



Let's say I have the input string as "hello". The expected output would be:


"hello"


h -> 1
e -> 1
l -> 2
o -> 1




2 Answers
2



We can use table to count the frequencies after we split the string in letters. A simple sapply can convert it to a list if needed, i.e.


table


sapply


table(strsplit('hello', ''))
#e h l o
#1 1 2 1

#or

sapply(table(strsplit('hello', '')), list)
#$`e`
#[1] 1

#$h
#[1] 1

#$l
#[1] 2

#$o
#[1] 1



R does not have any native hashmap support, although there is a hashmap package. However, we can easily enough use a list here to simulate hashing functionality:


hashmap


lst <- list()
for (i in strsplit('hello', '')[[1]]) {
lst[[i]] <- ifelse(is.null(lst[[i]]), 1, lst[[i]] + 1)
}

lst
$h
[1] 1

$e
[1] 1

$l
[1] 2

$o
[1] 1




Demo



Note that now accessing a key in the map just means accessing an entry in the list, e.g. lst$l returns 2, because l occurs twice in the string hello.


lst$l


l


hello






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

PHP contact form sending but not receiving emails