I have one character vectors and one binary number vectors like:
char <- paste("item", 1:4, sep="")
bnum <- c(1, 0, 0, 1)
And i would like to have a result like belows:
[1] "item1" 0 0 "item4"
Indeed my ultimate goal is to generate:
[1] "item1-item4"
And i suppose task one generate vector "ans", then the code for second task would be:
ans<- c("item1",0,0,"item4","item5")
ans2<-ans[ans!=0]
n<-length(ans2)
ans3<-ans2[1]
for (i in 2:n){
ans3 <- paste(ans3,ans2[i],sep="-")
}
Thanks for your help.
char[as.logical(bnum)]
paste(char[as.logical(bnum)], collapse="-")
#[1] "item1-item4"
char <- paste("item", 1:4, sep="")
bnum <- c(1, 0, 0, 1)
paste(char[bnum == 1], collapse = '-')
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.