R - cut digits

Asked

Viewed 130 times

5

Would someone like to tell me how I can cut digits in the R?

Example:

ano <- c(1999,2000,2001,2002,2003)

And only to return:

#[1] 99 00 01 02 03

2 answers

7


We can use the function substr doing the following:

ano<- c(1999,2000,2001,2002,2003)

substr(ano, 3, 4)

outworking:

[1] "99" "00" "01" "02" "03"

What the function substr ago?

The function has 3 arguments:

substr(x, start, stop)

x is the vector you want to cut the digits. Keep in mind that the vector you set (ano) is the type double. In that case, the function substr will transform ano in character to carry out the operation.

start: Where will you start cutting the digits? The initial cut position. For example substr("sport recife", 1, 1,) will return "s".

end: following the same idea, this is the last digit that will be included in the cut.

  • Thank you very much! That’s what I needed. I had found this function "str_sub(year, start = -2)", but it didn’t work here.

  • @For I don’t know why it didn’t work, but I suspect you didn’t install (or load) the package stringr. Try this: stringr::str_sub(ano, -2). If it doesn’t work, it’s because you don’t have the package installed. Install and repeat the code, it should work.

  • Yes, I believe it is due to the lack of the same package. Here I have some restrictions regarding the installation of new packages. But it worked with your tip. Thank you @Jdemello!

5

Although there is already an accepted answer, here is another way to do the same.

You can use arithmetic to keep only the last two digits, just calculate the rest of the division by the power of the appropriate ten.

ano %% 100
#[1] 99  0  1  2  3

Or, if a 2-digit result is required, format with sprintf, for example.

sprintf("%02d", ano %% 100)
#[1] "99" "00" "01" "02" "03"

And this can be put into a more general function.

cortar <- function(x, digits = 2, numeric = FALSE){
  y <- x %% 10^digits
  if(numeric)
    y
  else{
    fmt <- paste0("%0", digits, "d")
    sprintf(fmt, y)
  }
}

cortar(ano)
#[1] "99" "00" "01" "02" "03"

cortar(ano, digits = 3)
#[1] "999" "000" "001" "002" "003"

cortar(ano, numeric = TRUE)
#[1] 99  0  1  2  3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.