baru
baru

Reputation: 401

R - add same element to vector without use for loop

I'm pretty new in R, I only know its foundamental concepts.

I have the v vector:

   v<-c(1,2,3,4)

and I would like to append to v four NA values, obtaining:

v(1,2,3,4,NA,NA,NA,NA)

T o solve this I can use a for loop:

for(i in 1:4){
   v<-append(v, NA)
}

My question is: are there clever and/or faster R solutions I could use?

Upvotes: 0

Views: 69

Answers (1)

Arun kumar mahesh
Arun kumar mahesh

Reputation: 2359

From the above comments we had found some useful answers where every new OP can view in aswer window rather than comment sections, thanks OP for your valuable answers

v <- c(v, rep(NA, 4)) # joel.wilson

length(v)<-length(v)+4 # Nicola

'length<-'(v, 8) # akrun

Please note:

in general the Joel.Wilson's option is the good one 'cause can be used to append several times a specific value (numeric, character, boolean, etc.), while other two solutions only NA values as they play on the length property.

Upvotes: 1

Related Questions