1

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

Nilima
  • 197
  • 1
  • 2
  • 9

1 Answers1

1

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)]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Is there a way to initialize b? I am getting an error `number of items to replace is not a multiple of replacement length` – Nilima May 13 '20 at 19:47
  • @Nilima updated the post. I think you are creating the 'b' based on index. in that case, just use index to subset the 'a' – akrun May 13 '20 at 19:52