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

Time:11-11

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)

CodePudding user response:

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)

CodePudding user response:

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"      "" 

CodePudding user response:

One way to do this is to grow the named vector by appending values rather than inserting them by index value. You could insert by inserting a value into an existing vector, but it is cumbersome:

var <- c(names_p1="p1")
var <- c(var, names_p3="p3")
add <- c(names_p2="p2")
var <- c(var[1], add, var[2])
var
# names_p1 names_p2 names_p3 
#     "p1"     "p2"     "p3" 
  •  Tags:  
  • r
  • Related