Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia equivalent of R's paste() function

Tags:

julia

Is there a function in Julia that behaves like R's paste() function? In particular, if we give the function two vectors, it would return a single vector with the element-wise concatenation of the two input vectors.

I've looked around and can't seem to find the answer for this in the docs or otherwise. An older post by John Myles White suggests that Julia's join() function is the closest analogue, but it seems to work only on pairs of strings, not element-wise on vectors of strings.

For now, I'm just using the function below that loops over elements calling join(), but I'm wondering if there is a better approach.

x = ["aa", "bb", "cc"]
y = ["dd", "ee", "ff"]

function mypaste(v1, v2)
    n = length(v1)
    res = Array{ASCIIString}(n)
    for i = 1:n
        res[i] = join([v1[i], v2[i]])
    end
    return res
end

mypaste(x, y)

Running mypaste() gives us the output below, as desired.

3-element Array{ASCIIString,1}:
 "aadd"
 "bbee"
 "ccff"

Is there a good alternative? Am I misunderstanding the join() function?

like image 744
paulstey Avatar asked Mar 30 '16 20:03

paulstey


3 Answers

I don't think I'd use join at all. Join is used to combine strings within one collection; you're after concatenation of strings across two different collections. So while it's easy (and efficient) to create the temporary collections you need for join with zip, you can avoid it by using the string function or multiplication:

julia> map(string, x, y)
3-element Array{ASCIIString,1}:
 "aadd"
 "bbee"
 "ccff"

julia> map(*, x, y)
3-element Array{ASCIIString,1}:
 "aadd"
 "bbee"
 "ccff"

Even better (but perhaps too clever by half), there's the broadcasting element-wise multiplication operator .*:

julia> x .* y
3-element Array{ASCIIString,1}:
 "aadd"
 "bbee"
 "ccff"
like image 131
mbauman Avatar answered Nov 19 '22 02:11

mbauman


map could be used. The one-liner is map(join,zip(x,y)). As in the following example, which also adds z:

julia> x = ["aa","bb","cc"];

julia> y = ["dd","ee","ff"];

julia> z = ["gg","hh","ii"];

julia> map(join,zip(x,y,z))
3-element Array{Any,1}:
 "aaddgg"
 "bbeehh"
 "ccffii"

(see @DSM answer for list comprehension)

like image 44
Dan Getz Avatar answered Nov 19 '22 02:11

Dan Getz


You could use a list comprehension and zip to get the pairs:

julia> x = ["aa", "bb", "cc"];

julia> y = ["dd", "ee", "ff"];

julia> [join(i) for i=zip(x,y)]
3-element Array{ByteString,1}:
 "aadd"
 "bbee"
 "ccff"
like image 32
DSM Avatar answered Nov 19 '22 00:11

DSM