Operation based on names in Julia NamedArray()

53 Views Asked by At

I want to apply a conditional function on a NamedArray in Julia and the condition is based on the row/column names. I have problem with applying the condition on names. For example, consider

A = NamedArray([1, 2, 3, 4], (["Aa", "Ab", "Ba", "Bb"]))

and I want to multiply elements by 2 if the second letter is "a". The below code does not work:

(1 .+ SubString.(names(A), 2, 2) .== "a") .* A

and the SubString() gives error

ERROR: MethodError: no method matching SubString(::Vector{String}, ::Int64, ::Int64)
1

There are 1 best solutions below

0
Mohammad On

Based on @DanGetz 's comment, this works:

A .* (1 .+ (getindex.(names(A,1), 2) .== 'a'))

or this one with SubString():

A .* (1 .+ (SubString.(names(A,1), 2) .== "a"))