rstring-length

How i can check the full length of number even if it includes zeros?


i want to check the length of x that includes number like (600,000) it always returns length of 5 not 6. i think R doesn't count if they more than 4 zeros like above. i want know how to count the full length of x even with zeros.

Thanks in advance.

test_f <- function(x) {
  
  len <- nchar(x)
  
  print(len)
  
  if (len == 6){
    
    first_indx <- substring(x,1,3)
    first_val <- NUM20 %>%  select(ID,num_name_ar) %>% filter(ID == first_indx) %>% select(num_name_ar)
    
    second_indx <- substring(x,4,6)
    second_val <- NUM20 %>%  select(ID,num_name_ar) %>% filter(ID == second_indx) %>% select(num_name_ar)
    
  }
}

test_f(600000)

i tried the above code and were expecting to get length of 6


Solution

  • The length isn't being given how you're expecting due to the fact R is converting the 600000 to scientific notation 6e+05. To avoid this you may want to add a format step at the beginning of the function

    test_f <- function(x) {
      print(x)
      x <- format(x, scientific = FALSE)
      print(x)
      len <- nchar(x)
      print(len)
      
      if (len == 6){
        
        first_indx <- substring(x,1,3)
        first_val <- NUM20 %>%  select(ID,num_name_ar) %>% filter(ID == first_indx) %>% select(num_name_ar)
        
        second_indx <- substring(x,4,6)
        second_val <- NUM20 %>%  select(ID,num_name_ar) %>% filter(ID == second_indx) %>% select(num_name_ar)
        
      }
    }
    
    test_f(600000)
    

    OUTPUT

    [1] 6e+05
    [1] "600000"
    [1] 6
    Error in test_f(6e+05) : object 'NUM20' not found