简体   繁体   中英

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. 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.

Your code is suboptimal because you don't leverage the fact paste is vectorized, however it can work with a slight modification:

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 . It applies FUN to all elements of x and y - in this case, pasting them together. Since outer returns a matrix, wrap it in as.character to return a vector!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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