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?

Upvotes: 2

Views: 214

Answers (2)

ndoogan
ndoogan

Reputation: 1925

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()

Upvotes: 6

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Here is another possibility:

x <- 1234
as.numeric(sapply(sequence(nchar(x)), function(y) substr(x, y, y)))
# [1] 1 2 3 4

nchar tells us how many characters long the "string" is. Wrapping that in sequence generates the positions we need for substr. substr will automatically convert your input to character before extracting based on the start and end position.

Upvotes: 2

Related Questions