[英]concatenate each element of character vector with all elements of a second vector r
I am trying to concatenate two character vectors in a way that the following output is produced 我试图以产生以下输出的方式连接两个字符向量
aggmodes<-c("17x8","17x7x8","17x28x8")
listdata<-c("Motion.Age","res.Context.Only")
The output should be like this 输出应该是这样的
"Motion.Age,17x8"
"Motion.Age,17x7x8"
"Motion.Age,17x28x8"
"res.Context.Only,17x8"
"res.Context.Only,17x7x8"
"res.Context.Only,17x28x8"
I have written following code: 我写了以下代码:
c<-as.vector(sapply(1:length(listdata), function(i){
sapply(1:length(aggmodes),function(j){paste(aggmodes,listdata)})
}))
but it gives me an a 10 dimensional vector. 但这给了我一个10维向量 I am sorry if it is a duplicate, but i couldnot find a correct answer for solving my problem 很抱歉,如果它是重复的,但是我找不到解决问题的正确答案
c(sapply(listdata,paste,aggmodes,sep=","))
# [1] "Motion.Age,17x8" "Motion.Age,17x7x8" "Motion.Age,17x28x8"
# [4] "res.Context.Only,17x8" "res.Context.Only,17x7x8" "res.Context.Only,17x28x
We paste each element of listdata
to all of aggmodes
with sapply, and then unwrap it all. 我们使用listdata
将aggmodes
每个元素粘贴到所有aggmodes中,然后将其全部解包。
Your code is suboptimal because you don't leverage the fact paste
is vectorized, however it can work with a slight modification: 您的代码是次优的,因为您没有利用paste
矢量化的事实,但是可以稍作修改就可以工作:
as.vector(sapply(1:length(listdata), function(i){
sapply(1:length(aggmodes),function(j){paste(aggmodes[j],listdata[i])})
}))
as.character(outer(listdata, aggmodes, paste, sep = ","))
outer
takes three arguments: x
, y
, and FUN
. outer
采用三个参数: x
, y
和FUN
。 It applies FUN
to all elements of x
and y
- in this case, pasting them together. 它将FUN
应用于x
和y
所有元素-在这种情况下,将它们粘贴在一起。 Since outer
returns a matrix, wrap it in as.character
to return a vector! 由于outer
返回一个矩阵,敷在as.character
返回一个向量!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.