Search code examples
rrlang

R: Rename R objects in an expression


I have an expression (sometimes a simple one, sometimes more complex), and I am looking for a robust way to rename the objects in the expression. I am currently converting the expression to a string, doing some matching and replacing. But this is certainly not the most error-proof way of doing this.

Essentially, I think something like RStudio's "Rename in Scope" feature, but being able to run it on a programmatically on a single expression.

I think there could be a a way to dis-assemble the expression into its parts, rename, then re-assemble?

Thank you!

library(rlang)

# what i have
expr(row_type == 'label')
#> row_type == "label"

# what i want
expr(row_type_2 == 'label')
#> row_type_2 == "label"

# can it also work with `.data$` prefix to give us `.data$row_type_2 == 'label'`
expr(.data$row_type == 'label')
#> .data$row_type == "label"

Solution

  • Use substitute as shown:

    e <- expr(row_type == 'label')
    do.call("substitute", list(e, list(row_type = as.name("row_type_2"))))
    ## row_type_2 == "label"
    
    e2 <- expr(.data$row_type == 'label')
    do.call("substitute", list(e2, list(row_type = as.name("row_type_2"))))
    ## .data$row_type_2 == "label"
    

    This also works if you know the precise structure of e and e2:

    e[[3]] <- as.name("row_type_2")
    e
    ## row_type == row_type_2
     
    e2[[2:3]] <- as.name("row_type_2")
    e2
    ## .data$row_type_2 == "label"