python - how to extract index in factor vector in Rpy2 -


i have factor vector sv='ababbc' , integer vector fv=[1,1,1,1,1,1]. fv correspond sv.

import rpy2.robjects robjects sv=robjects.strvector('ababbc') fac=robjects.factorvector(sv) fv=robjects.r['rep'](1,6) 

i want change value of element 2 in fv, of index correspond letter “a”. made fv=[2,1,2,1,1,1]

how it? thank you.

to index when true:

in [54]: import numpy np np.argwhere(np.array(sv) == 'a') out[54]: array([[0],        [2]]) 

the 1st , 3rd positions have letter 'a'.

you can't fac, factorized , contains levels, 1, 2, 3..., not original 'a', 'b', 'c'... anymore.

in [55]:  np.argwhere(np.array(fac) == 'a') out[55]: array([], shape=(0, 1), dtype=int64) in [56]:  np.array(fac) out[56]: array([1, 2, 1, 2, 2, 3], dtype=int32) 

or can done in r side:

in [51]:  robjects.reval('result1 <- which(sv %in% c("a"))') print robjects.r.result1 [1] 1 3 

to systematically assign given value level, suggest use factor function in r:

in [53]: robjects.r.assign('sv',  sv) robjects.reval('result3 <- factor(sv, levels=c("a","b","c"), labels=c(10,2,3))') print robjects.r.result3 [1] 10 2  10 2  2  3  levels: 10 2 3 

so a gets 10, b gets 2, c gets 3 , on.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -