0

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")
user35131
  • 1,105
  • 6
  • 18

2 Answers2

2

We can use sub to trim the vec. We create a logical vector with the number of character of the 'vec' ('i1'). Using that, we update for those elements that are greater than 10 characters to remove the characters between the 10th and the last character with sub and update it

i1 <- nchar(vec)  > 10
vec[i1] <-  sub("^(.{1,9}).*(.)", "\\1\\2", vec[i1])

-output

vec
#[1] "Col1"       "Col2islonr" "Col3isabir" "Col4isless" "Col5willbt"     
akrun
  • 874,273
  • 37
  • 540
  • 662
2

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"
Duck
  • 39,058
  • 13
  • 42
  • 84