将字符串转换为数值向量 [英] Convert String to numeric vector
本文介绍了将字符串转换为数值向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数,它接受一个由 0 和 1 组成的向量,例如:
I have a function which takes a vector of zeros and ones for example:
foo(c(1,1,1,0,1,1))
但在某些情况下,有超过 100 个数字,我必须手动添加所有逗号.是否有任何预定义的函数可以将字符串转换为这样的向量?像这样:
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"))
推荐答案
我们可以使用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
或者可能是 OP 的意思
Or may be the OP meant
dput(res)
这篇关于将字符串转换为数值向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文