简体   繁体   中英

Multiplying characters in a vector in R

Suppose I have the vector:

x = c("a","b","c")

I would like to create a function that returns the following:

[1] "a*b" "a*c" "b*c"

I assume we would use the paste0() function or use some sort of for loop to loop through the characters in the vector but I am not fully sure how to go about this. Just to clarify, I am looking for an output that takes two characters from the vector at a time and uses some sort of paste0(...,sep="*") to get the desired output above. I do not want to multiply all the characters in the vector at once, just two characters at a time.

We can use combn from base R

combn(x, 2, FUN = paste, collapse="*")
#[1] "a*b" "a*c" "b*c"

You can use a recursion function which may be faster.

foo = function(x, sep = "*") {
    if (length(x) < 2) {
        return(x)
    }

    ans = paste(x[1], x[-1], sep = sep)

    if (length(x) > 2) {
        ans = c(ans, Recall(x[-1]))
    }

    return(ans)
}

foo(c("a", "b", "c"))
#[1] "a*b" "a*c" "b*c"

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