insightsengineering / insightsengineering/teal.code

[Bug]: `within` doesn't replace the lefthand side of an expression.

Open
#275 0 comments 0 reactions 0 assignees View on GitHub
bug core
Dominant language
R
Stars
12
Forks
11
Avg merge
1d 17h
Merged PRs (30d)
1

Description

### What happened?

I wanted to mutate a variable by using as.factor but I found that using this approach doesn't replace the content but creates a new column:

``` r
library("teal.code")
var <- "Species"
q <- within(qenv(),
{
library("dplyr")
iris <- iris
iris2 <- mutate(iris, a = as.factor(a))
},
a = as.name(var)
)
setdiff(colnames(q$iris2), colnames(q$iris))
#> [1] "a"
```

Created on 2025-10-24 with [reprex v2.1.1](https://reprex.tidyverse.org)

One workaround is to use the dplyr's walrus `:=` assignment:

``` r
library("teal.code")
var <- "Species"
q <- within(qenv(),
{
library("dplyr")
iris <- iris
iris2 <- mutate(iris, a := as.factor(a))
},
a = as.name(var)
)
setdiff(colnames(q$iris2), colnames(q$iris))
#> character(0)
```

Created on 2025-10-24 with [reprex v2.1.1](https://reprex.tidyverse.org)

but this might confuse readers of the code if this end up on the Show R code on teal.
If not a bug perhaps mentioning this on the documentation would be helpful to users.

Also, I realized that `within` doesn't have the `@aliases within` so users searching with `?within` will not find it (but it is linked from eval_code and qenv).

### sessionInfo()

```R

```

### Relevant log output

```R

```

### Code of Conduct

- [x] I agree to follow this project's Code of Conduct.

### Contribution Guidelines

- [x] I agree to follow this project's Contribution Guidelines.

### Security Policy

- [x] I agree to follow this project's Security Policy.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.