Search code examples
rdigitsnumber-theory

Is there an R function for deriving digits?


I have seen the solution in the past but forgot where: is there an R function that turns x=1234 into its digits (1,2,3,4) and vice-versa?


Solution

  • a <- c("1234")
    res <- strsplit(a,"")
    res
    #[[1]]
    #[1] "1" "2" "3" "4"
    

    Note that if a is a numeric vector, you should cast it as a character string first. You can recast the result back to numeric later if you need to. The following command does this for you so long as you left res in the list form it was originally returned as.

    lapply(res,as.numeric)
    #[[1]]
    #[1] 1 2 3 4
    

    res will contain a list with one item per input string with each character assigned to its own element in a vector. In this case, there is just one input string, and therefore just one list item (which contains a vector) in the output.

    The reverse operation can be done with the paste() function:

    a<-c(5,2,8,0)
    paste(a,collapse="")
    

    You may want to wrap the paste up in as.numeric()