user53020 user53020 - 3 months ago 10
R Question

R repeat only one element and change other elements

I need this:

"X","Y",151,"X","Y",152,"X","Y",153,"X","Y",154,....."X","Y",334


But I can only get this:

names<-c("X","Y",seq(152,334,by=1))
#"X","Y",151,152,153,154....334


Thanks

Answer

We can do

v1 <-  152:334
v2 <- rep(c("X", "Y", ""), length(v1))
v3 <- replace(v2, v2 == "", v1)
head(v3, 10)
#[1] "X"   "Y"   "152" "X"   "Y"   "153" "X"   "Y"   "154" "X"  
tail(v3, 10)
# [1] "331" "X"   "Y"   "332" "X"   "Y"   "333" "X"   "Y"   "334"