costebk08 costebk08 - 1 year ago 61
R Question

Counting the number of individual letters in a string in R

I have the following string of characters:


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:

6 3 4 2 1

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

Answer Source

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 I 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 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download