user53020
user53020

Reputation: 889

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

Upvotes: 2

Views: 140

Answers (1)

akrun
akrun

Reputation: 887951

We create a vector of sequence ('v1'), replicate the vector (c("X", "Y", "")) by the length of 'v1' and replace the""` with 'v1'.

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"

Or another option is replicate the string ("X Y") by the length of 'v1', rbind with 'v1', concatenate (c) the matrix to a vector, scan to split up the "X Y" to "X", "Y".

scan(text=c(rbind(rep("X Y", length(v1)),  v1)), what = "", quiet=TRUE)

Upvotes: 1

Related Questions