[英]How to combine two character vectors in r to form a new vector?
I have two vectors as shown below.我有两个向量,如下所示。
a<-c("a","b","c","d")
b<-"constant"
Now I need to combine above two vectors and the final output should be in the form as I showed below.现在我需要结合上面的两个向量,最终的 output 应该是如下所示的形式。
list(a="constant",b="constant",c="constant",d="constant")
Thanks in advance.提前致谢。
You can try the following:您可以尝试以下方法:
l <- as.list(rep(b, length(a)))
names(l) <- a
We can repeat b
, length(a)
times gives them names with setNames
and convert it into list.我们可以重复b
, length(a)
次用setNames
给它们命名并将其转换为列表。
as.list(setNames(rep(b, length(a)), a))
#$a
#[1] "constant"
#$b
#[1] "constant"
#$c
#[1] "constant"
#$d
#[1] "constant"
Here is an other way that might be simpler:这是另一种可能更简单的方法:
l <- list()
l[a] <- b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.