2

I would like to recode some strings into binary mode for codifing them into matrices, in R. Let's say I have the following strings in a data frame:

strings  code
ABC       1
BCA       2
CAB       1

After extracting them I have the following strings:

"ABC" "BCA" "CAB"

And I would like to implement the next transformation:

A = 100
B = 010
C = 001

So that transforming "ABC" into the next matrix

100
010
001

And so, "BCA" into:

010
001
100

And "CAB" into:

001
100
010

And, after this transformation, getting a vector for "ABC" that is:

100010001

which represents ABC, an so on.

Basically, what I want to do is defining an algorithm with binary dictionary for letters characters so that it converts each letter into a binary sequence using R.

I've tried some aproaches but could not get a nice function...

Any help?

2 Answers 2

2

Make a named vector, then split and match.

dictionary <- setNames(c("100", "010", "001"), LETTERS[1:3])

x <- c("ABC", "BCA", "CAB")

sapply(strsplit(x, ""), function(i)
  paste(dictionary[ i ], collapse = ""))

# [1] "100010001" "010001100" "001100010"

Or instead of creating custom dictionary, why not use real binary?

sapply(x, function(i)
  paste(rawToBits(charToRaw(i)), collapse = ""))

# ABC 
# "010000000000010000010000000001000101000000000100" 
# BCA 
# "000100000000010001010000000001000100000000000100" 
# CAB 
# "010100000000010001000000000001000001000000000100"
Sign up to request clarification or add additional context in comments.

Comments

1

We could use a gsub. Create a key/value list ('lst'), Loop through the sequence of 'lst', use gsub to match the names of the 'lst', replace with the 'value' and assing it back to 'strings' column

lst <- list(A = '100', B = '010', C = '001')
for(i in seq_along(lst)) df1$strings <- gsub(names(lst)[[i]], lst[[i]], df1$strings)
df1
#    strings code
#1 100010001    1
#2 010001100    2
#3 001100010    1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.