costebk08
costebk08

Reputation: 1359

Counting the number of individual letters in a string in R

I have the following string of characters:

pig<-c("A","B","C","D","AB","ABC","AB","AA","CD","CA",NA)

I am trying to get R to tell me how many of each total letters there are and how many total NAs there are. Thus, in this case I would like to the result to look like this:

print(cow)
A  B  C  D  NA
6  3  4  2  1

I have tried table in combination with strsplit but cannot figure out exactly how to do it. Any thoughts? Thanks!

Upvotes: 0

Views: 90

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99381

You would need to use NULL (or the empty character "") for the split value in strsplit(), then unlist it. Then, in table() you'll want to use the useNA argument to include any NA values. Here we'll use "ifany", so that if there are any NA values they will be shown in the table and if there are not, NA will not be shown in the result at all.

table(unlist(strsplit(pig, NULL)), useNA = "ifany")
#
#   A    B    C    D <NA> 
#   7    4    4    2    1 

Upvotes: 2

Related Questions