Skip to content

Bug report: Warning/Error when 'pos' argument is a vector #19

@NourEdinDarwish

Description

@NourEdinDarwish

Hi,

I ran into a small issue when using grid.echo() on a base plot that uses text() with a vectorized pos argument (like pos = c(2, 4)).

It seems to trigger this warning from R:
Warning: number of items to replace is not a multiple of replacement length

Reprex

Here is a minimal example that reproduces it:

library(gridGraphics)
#> Loading required package: grid

# 1. Base plot with mixed text positions (left=2, right=4)
plot(1:5, 1:5, main = "Test")
text(1:5, 1:5, labels = LETTERS[1:5], pos = c(2, 4, 2, 4, 2))

# 2. Convert to grid
# This triggers the warning
grid.echo()
#> Warning in xx[pos == 2] <- xx - convertWidth(offset, "native", valueOnly =
#> TRUE): number of items to replace is not a multiple of replacement length
#> Warning in xx[pos == 4] <- xx + convertWidth(offset, "native", valueOnly =
#> TRUE): number of items to replace is not a multiple of replacement length

Created on 2026-01-19 with reprex v2.1.1

Possible Cause

I looked into R/text.R (around lines 29-32 in C_text), and it looks like the code is trying to update xx using a subset index (e.g. pos == 2), but convertWidth(offset, ...) returns the full vector of offsets.

So it ends up trying to assign the full vector (length 5) into the subset slots (length 3), which causes the mismatch warning.

Suggested Fix

I was able to fix it locally by calculating the converted offsets before the subset assignment, and then subsetting the offset vector to match.

Something like this seems to work:

# Calculate full offsets first
cw_offset <- convertWidth(offset, "native", valueOnly=TRUE)
ch_offset <- convertHeight(offset, "native", valueOnly=TRUE)

# Then apply to the specific indices
if (any(pos == 2)) xx[pos == 2] <- xx[pos == 2] - cw_offset[pos == 2]
if (any(pos == 4)) xx[pos == 4] <- xx[pos == 4] + cw_offset[pos == 4]
if (any(pos == 1)) yy[pos == 1] <- yy[pos == 1] - ch_offset[pos == 1]
if (any(pos == 3)) yy[pos == 3] <- yy[pos == 3] + ch_offset[pos == 3]

Let me know if this makes sense!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions