Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top