Find all unique characters in a data frame in R

Viewed 123

I am wondering what is the most efficient way to find all unique characters from a data frame in R.

i.e for example:- [0-9,a-z,A-Z,",","$","&","#" etc]

> k
  cola colb
1 1&3#   %^
2 A4C%  89&

The output I am expecting is a list containing all unique characters including special characters. i.e 123#%^AC89&

1 Answers

There's nothing really efficient about this, but ... demonstrating on the diamonds dataset from the ggplot2 library,

library(ggplot2)
unique(unlist(lapply(diamonds, function(x) unlist(strsplit(as.character(x), "")))))
#  [1] "0" "." "2" "3" "1" "9" "4" "6" "5" "8" "7" "I" "d" "e" "a" "l" "P" "r" "m" "i" "u" "G" "o"
# [24] "V" "y" " " "F" "E" "J" "H" "D" "S"

If you're curious about how many of each?

table(unlist(lapply(diamonds, function(x) unlist(strsplit(as.character(x), "")))))
#             .      0      1      2      3      4      5      6      7      8      9      a 
#  12082 261929  81785 142173 135042 108355 121267 157242 161862  91438  71904  67144  23161 
#      d      D      e      E      F      G      H      i      I      J      l      m      o 
#  38539   6775  47424   9797  12942  28280   8304  15401  51763   2808  21551  27582  33976 
#      P      r      S      u      V      y 
#  13791  27483  51409  13791  49953  12082 

(This is effectively akrun's answer ... posted before I saw his comment-edit.)

Using your sample frame:

k <- data.frame(cola = c("1&3#", "A4C%"), colb = c("%^", "89&"), stringsAsFactors = FALSE)
unique(unlist(lapply(k, function(x) unlist(strsplit(as.character(x), "")))))
#  [1] "1" "&" "3" "#" "A" "4" "C" "%" "^" "8" "9"

And if you want them in a sorted no-space string,

paste(sort(unique(unlist(lapply(k, function(x) unlist(strsplit(as.character(x), "")))))), collapse = "")
# [1] "#%&^13489AC"

Since your question suggests you're considering using this in a regex somewhere, you can sandwich this in brackets. I wouldn't go through the pain of finding character ranges (e.g., AD-GW-Z24-9), since that buys you very little regex efficiency but would take a bit more effort to generate.

Related