Search code examples
rstring-matching

Comparison of of character type and factor type in R


Ok, so I am having this issue right now. I have a matrix A whose rownames are the values of a field in another matrix B. I want to find indices of my rownames in the second matrix B. Now I am trying to do this operation which(A$field == rowname_A) . Unfortunately couple of things are appearing one - the rowname_A variable is of character class. It is of this format , "X12345". The values of A$field is of type factor. Is there a way to remove the appended X from the character, convert it to factor and do the comparison. Or convert the factor variables of A$field in to character type and then do the comparison.

Help will be appreciated.

Thanks.


Solution

  • This is fairly straightfoward. The example below should help you out.

    A <- matrix(1:3)
    rownames(A) <- paste0("X", 1:3)
    B <- data.frame(field = factor(1:3))
    
    # Remove "X" from rownames(A) and check equality
    B$field %in% substr(rownames(A), 2, nchar(rownames(A)))
    
    # Add "X" to B$field and check equality
    paste0("X", B$field) %in% rownames(A)