costebk08 costebk08 - 3 months ago 9
R Question

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!

Answer

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 
Comments