Juan David Ossa Gomez
Juan David Ossa Gomez

Reputation: 83

How to extract the max value of a string in R

I have a vector of strings like this:

"1111111221111122111111UUUUUUUUUUUUUUUUUU"
"---1-1---1--111111"
"1111112111 1111" (with blank spaces)

everyone has different length and I want to extract the max value of the each string, for the three examples above the max values would be (2,1,2), but don't know how to do it with the letters or the dash or the blank spaces, all these three are the minimum, i.e., 1 is bigger than "U", "-" and " " and between them is the same.

Any advice?

Best regards

Upvotes: 1

Views: 1682

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 546153

Decompose the problem into independent, solvable steps:

  1. Transform the input into a suitable format
  2. Find the maximum

The we get:

  1. # Separate strings into individual characters
    digits_str = strsplit(input, '')
    # Convert to correct type
    digits = lapply(digits_str, as.integer)
    
  2. # Perform actual logic, on each input string in turn.
    result = vapply(digits, max, integer(1L), na.rm = TRUE)
    

This uses the lapply and vapply functions which allow you to perform an operation (here first as.integer and then max) on all values in a vector/list.

Upvotes: 2

Related Questions