I have an array
a<-c(6,77,98,88,3,10,7,5)
I want to initialize another array with the 1st, 6th, and 8th element i.e. b should look as follows:
b = (6,10,5)
Is there a straightforward way to do this in R?
(I am a beginner, as I am sure you understand, on stack overflow as much as on R. I couldn't find the exact thing I am looking for - maybe I am using the wrong terms to search.)
We can use indexing in replace
. Assuming that we need a vector with length
8, initialize with numeric
(gives a vector of 0's), then replace
using an index with the vector 'b'
replace(numeric(8), c(1, 6, 8), b)
#[1] 6 0 0 0 0 10 0 5
If we need to initialize as missing values
replace(rep(NA_integer_, 8), c(1, 6, 8), b)
If we want to extract 1, 6, 8 elements from 'a'
b <- a[c(1, 6, 8)]