Search code examples
rreplacerow-number

Replace values (corresponding to the order of row) with the row name in R


I have a dataframe something like this:

    rowid A B 
     101  1 3
     102  2 3
     103  1 4
     104  2 4

I wanted to replace values in columns A and B with the corresponding rowid (please refer to the table below) in R. The values in columns A and B are based on the order of the rowid. For example, I want to replace a value of 3 in column A with a rowid of 103. I would really appreciate it if anyone could provide any advice.

    rowid  A   B
     101  101 103
     102  102 103
     103  101 104
     104  102 104

Solution

  • Using dplyr you can do :

    library(dplyr)
    df %>% mutate(across(-rowid, ~rowid[.]))
    
    #  rowid   A   B
    #1   101 101 103
    #2   102 102 103
    #3   103 101 104
    #4   104 102 104
    

    In base R with lapply :

    df[-1] <- lapply(df[-1], function(x) df$rowid[x])
    

    data

    df <- structure(list(rowid = 101:104, A = c(1L, 2L, 1L, 2L), B = c(3L, 
    3L, 4L, 4L)), class = "data.frame", row.names = c(NA, -4L))