简体   繁体   English

是否有用于导出数字的 R 函数?

[英]Is there an R function for deriving digits?

我过去看过这个解决方案,但忘了在哪里:是否有一个 R 函数可以将 x=1234 变成它的数字(1、2、3、4),反之亦然?

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.请注意,如果a是数字向量,则应先将其转换为字符串。 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.只要您将res保留在最初返回的列表形式中,以下命令就会为您执行此操作。

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. res将包含一个列表,每个输入字符串有一个项目,每个字符分配给向量中的自己的元素。 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:可以使用paste()函数完成相反的操作:

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

You may want to wrap the paste up in as.numeric()您可能希望将paste包裹在as.numeric()

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. nchar告诉我们“字符串”有多少个字符长。 Wrapping that in sequence generates the positions we need for substr .sequence包装它会生成我们需要substr的位置。 substr will automatically convert your input to character before extracting based on the start and end position. substr将在根据开始和结束位置提取之前自动将您的输入转换为character

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM