findAssignsTo: Find assignments to variables in R code

View source: R/getToplevelAssigns.R

findAssignsToR Documentation

Find assignments to variables in R code

Description

findAssignsTo identifies assignments in code with the left-hand-side being one of a specified set of possible variables of interest.

There are two types of assignments this function can detect. The simple/non-complex assignments are of the form x = val, x <- val and x -> val where val can be a variable, a literal value or a call.

Complex assigments are include calls such as x[[1]][[i]] = val, x$y$z = val and foo(x, a) = val. These involve replacement functions.

Usage

findAssignsTo(code, var = character(), complex = TRUE,
              pred = if (complex) isComplexAssignTo else isSimpleAssignTo)
isComplexAssignTo(x, var, simpleOk = TRUE) 
isSimpleAssignTo(x, var = character())

Arguments

code,x

the R code/language object

var

the names of the variables being assigned. If this is empty for findAssignsTo, all assignments are returned.

complex

a logical value. If TRUE, the function includes both simple and complex assignments; if FALSE only simple assignments are considered. Complex assignments include expressions such as is used to detect

pred

the predicate function to identify the assignments of interest. One can specify a different predicate than isComplexAssignTo or isAssignTo.

simpleOk

a logical value. If TRUE, a simple assignment is also acceptable; otherwise, the assignment call must have a non-symbol/name on the right-hand side but a call such as x[i], x$i, names(x).

Value

A list of the assignment calls found in the code.

Author(s)

Duncan Temple Lang

References

R Language manual.

See Also

findUnusedArgs, findUnusedAssignments

Examples

  bar = function(x) {
     a = 1 + x
     b = 2 + x^2
     ans = a + b
     ans
  }
  findAssignsTo(bar, "a")
  findAssignsTo(bar, "b")
  findAssignsTo(bar, "ans")



  # simple and complex assignments
  foo = function(x, y) {
    z = 3
    
    x[10] = 1
    y$el = 3

    foo(y, "abc") = 100
    bar(y) = "xyz"
    attr(z, "bar") = TRUE

    x[[1]][[2]][[3]] = val
    x$y$z = val

    y$a + sum(x) + z
  }

  findAssignsTo(foo, "x")
  findAssignsTo(foo, "y")
  findAssignsTo(foo, "z")

duncantl/CodeAnalysis documentation built on Feb. 21, 2024, 10:49 p.m.