0

I have a vector

s <- "111000"
v <- as.character(unlist(strsplit(s,"")))

I need to take vector v, turn into an 8-bit long string, and swap the 3rd and 4th variable.

So for example: Input Vector:

1 2 3 4 5 6 

Output Vector:

1 2 4 3 4 3 5 6

EDIT, so a lot of people misunderstanding the input/output. The numbers simply indicated the variable placement and where it is being switched.

As to the actual vector in the problem: "111000".

Input Value: "1" "1" "1" "0" "0" "0"
Output Value: "1" "1" "0" "1" "0" "1" "0" "0"

EDIT: Sorry for the question, it's how it was worded to me. But basically I am trying to do a block expansion. I am trying to create a function to take a 6-bit vector and return an 8 bit-value with the values being the output above. I have added a photo diagraming what is going on:

enter image description here

Zaid Islam
  • 29
  • 3
  • Not clear, what is the expected output. – akrun Mar 25 '20 at 18:17
  • Does the "Output Vector" is right? – vpz Mar 25 '20 at 18:19
  • I don't understand what you're going for here. Based on your first code block, I have a `character` vector named `v` that contains strings 1, 1, 1, 0, 0, and 0. How do your *"Input Vector"* and *"Output Vector"* relate to this? – r2evans Mar 25 '20 at 18:25
  • Yeah, I'm still confused. "swap" usually means switch positions without changing the length. If I swapped the 3rd and 4th positions of "111000" I would expect "110100". Seems like you want to swap and repeat the swapped values? Is it always one repetition, or is it based on your target length of 8? – Gregor Thomas Mar 25 '20 at 18:37
  • You imply that "turn it into an 8-bit long string" happens before the swap, but it seems like it happens by repeating the swap. – Gregor Thomas Mar 25 '20 at 18:45

1 Answers1

1

According to your diagram, x[c(1, 2, 4, 3, 4, 3, 5, 6)] is what you want.

As a function,

# works on first 6 variables
foo = function(x) x[c(1, 2, 4, 3, 4, 3, 5, 6)]
foo(1:6)
# [1] 1 2 4 3 4 3 5 6

foo(1:10) # only the first 6
# [1] 1 2 4 3 4 3 5 6

s <- "111000"
v <- as.character(unlist(strsplit(s,"")))
foo(v)
# [1] "1" "1" "0" "1" "0" "1" "0" "0"
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294