1

I have a function which takes a vector of zeros and ones for example:

foo(c(1,1,1,0,1,1))

But in some cases, there are more then 100 numbers and I have to add all commas manually. Is there any predefined function to convert a string to such a vector? Something like this:

foo(unknown_function("111011"))
Deep-Learner
  • 109
  • 1
  • 3
  • 14

1 Answers1

3

We can use paste

foo <- function(vec){
   paste(vec, collapse="")
  }

foo(c(1,1,1,0,1,1))
#[1] "111011"

If we need to do the reverse

foo1 <- function(str1){
      as.integer(unlist(strsplit(str1, "")))
  }
res <- foo1("111011")
res
#[1] 1 1 1 0 1 1

Or may be the OP meant

dput(res)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Hi, thanks for your answer, but I mean the other direction. foo should still take the vector c(1,1,1,0,1,1). But I'm looking for another function which converts the string "111011" to a vector c(1,1,1,0,1,1). – Deep-Learner Jun 05 '17 at 12:56
  • 1
    Awesome. That's what I'm looking for. Thanks a lot. – Deep-Learner Jun 05 '17 at 12:59