[R] get line from file having 'at' step in function body

Grzegorz Smoliński g@@mo||n@k|1 @end|ng |rom gm@||@com
Sun May 15 19:03:40 CEST 2022


Hi,

I'm looking for the reverse operation for utils::findLineNum(). Let's
take the code as below saved in file "test.R":

```
fun1 <- function() {
c(1,
2,
3)
}
```

Let's say in the file it starts from line 1, i.e. fun1 definition is
from line 1 to 5. I can now use `utils::findLineNum(fun1, line =
3)[[1]]$at` to get the location in the body, but how to get a line
having the location in the body?

Full code:

```
fun1 <- function() {
  c(1,
    2,
    3)
}

at <- utils::findLineNum("test.R", line = 3)[[1]]$at

getSrcLocation(body(fun1)[[at]], "line") # returns NULL, because
subsetting drops the 'srcref' attribute?
```
Is there some specific function for this? The problem is that in the
example above, the 'at' points to the line 2, not 3 if I can say that
(we can check this using `utils::findLineNum(fun1, line = 2)[[1]]$at`
- returned value is the same as for line 3) and I need to get this
first line to which the 'at' refers to. The only solution I see is to
use `findLineNum` on all previous lines (from the chosen line) and see
when the 'at' has changed - if has changed, then take the last checked
line. Is there a simpler solution?

Best regards,

Grzegorz



More information about the R-help mailing list