Search code examples
rconditional-statementsstring-lengthnchar

Can I rename vector elements based on their nchar length and their current values using R?


I have 6 vector values

vec<-c("Col1","Col2islonger","Col3isabitlonger","Col4isless","Col5willbelongest")

I run

nchar(vec)

my results are

4,12,16,10,17

Based on those values I would like to run a conditional statement or for loop whichever is better that would rename the columns based on their lengths and current values. For example

If nchar(vec) is less or equal to 10 keep the name as is. If the it is greater than 10 make sure the renamed element takes the first 9 values and skips over to the last.

newvec<- c("Col1","Col2islonr","Col3isabir","Col4isless","Col5willbt")

Solution

  • Try this:

    #Data
    vec<-c("Col1","Col2islonger","Col3isabitlonger","Col4isless","Col5willbelongest")
    #Rename
    vec2 <- ifelse(nchar(vec)<=10,vec,paste0(substr(vec,1,9),substr(vec,nchar(vec),nchar(vec))))
    

    Output:

    [1] "Col1"       "Col2islonr" "Col3isabir" "Col4isless" "Col5willbt"