When assign a value to a position in a vector, how do you pass the name of the value as well?

Viewed 51

For example,

var <- structure(character(3), names=character(3))
v2 <- "p2"; names(v2) <- "name p2"

If I do the following:

var[2] <- v2

Only the value "p2" is passed into the vector but not the name "name p2".

What I want is a one-line syntax to do the following:

var[2] <- v2; names(var)[2] <- names(v2)
2 Answers
var <- structure(character(3), names=letters[1:3])
v2 <- "p2"; names(v2) <- "name p2"

vslice <- function(x, i) x[i]
`vslice<-` <- function(x, i, value){
  x[i] <- value
  names(x)[i] <- names(value)
  x
}

vslice(var, 2)
#>  b 
#> ""
vslice(var, 2) <- v2
var
#>       a name p2       c 
#>      ""    "p2"      ""

Created on 2021-11-11 by the reprex package (v2.0.1)

You could just capture the steps in a function:

vec_names_merge <- function(x, y, pos) {
  y[pos] <- x; 
  names(y)[pos] <- names(x)
  y
}

vec_names_merge(v2, var, 2)
        name p2         
     ""    "p2"      "" 
Related