Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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)
like image 296
Leonhardt Guass Avatar asked Nov 11 '21 04:11

Leonhardt Guass


People also ask

How do you assign an element to a vector?

The syntax for assigning values from an array or list: vectorname. assign(arr, arr + size) Parameters: arr - the array which is to be assigned to a vector size - number of elements from the beginning which has to be assigned.

How do you add to a vector in C++?

Appending to a vector means adding one or more elements at the back of the vector. The C++ vector has member functions. The member functions that can be used for appending are: push_back(), insert() and emplace(). The official function to be used to append is push_back().

How do you add an element to a vector array?

Insertion: Insertion in array of vectors is done using push_back() function. Above pseudo-code inserts element 35 at every index of vector <int> A[n]. Traversal: Traversal in an array of vectors is perform using iterators. Above pseudo-code traverses vector <int> A[n] at each index using starting iterators A[i].


1 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)

like image 191
IceCreamToucan Avatar answered Oct 19 '22 07:10

IceCreamToucan