Search code examples
rsubsetrenaming

subsetting and renaming vector elements


I must be doing some naive mistake, but cannot figure out why my code is not working as intended:

testVector<- c('a', 'a', 'a', 'b', 'b', 'b')

names(testVector)<- replicate(n = 6, expr = 'temp')

##The following does not work, but does not give any error:
names(testVector[testVector=='a'])<- replicate(n = 3, expr = 'tempA')
#
names(testVector[testVector=='a'])
# [1] "temp" "temp" "temp"

The subsetting part seem to be right, I don't understand why it is not changing names though. What am I missing?


Solution

  • You need to subset the names

    names(testVector)[testVector=='a'] <- replicate(n = 3, expr = 'tempA')
    
    testVector
    #tempA tempA tempA  temp  temp  temp 
    #  "a"   "a"   "a"   "b"   "b"   "b"