How do I create a vector of character strings using a loop?
I'm trying to create a vector of character strings in R using a loop, but I'm having some problems. I would appreciate any help anyone can offer.
The code I'm working with is a little more verbose, but I tried to code a reproducible example here that captures all the key bits:
vector1<-c(1,2,3,4,5,6,7,8,9,10)
vector2<-c(1,2,3,4,5,6,7,8,9,10)
thing<-character(10)
for(i in 1:10) {
line1<-vector1[i]
line2<-vector2[i]
thing[i]<-cat(line1,line2,sep="\n")
}
R then outputs the following:
1
1
Error in thing[i] <- cat(line1, line2, sep = "\n") :
replacement has length zero
What I am trying to achieve is a character vector where each character is split across two lines, so there thing[1]
is
1 1
and thing[2]
-
2 2
etc. Does anyone know how I can do this?
cat
prints to the screen, but returns NULL
- to concatenate into a new character vector, you need to use paste
:
thing[i]<-paste(line1,line2,sep="\n")
For example, in an interactive terminal:
> line1 = "hello"
> line2 = "world"
> paste(line1,line2,sep="\n")
[1] "hello\nworld"
> ret <- cat(line1,line2,sep="\n")
hello
world
> ret
NULL
Note that, in your case, the for loop could simply be replaced with a more concise and efficient string:
thing <- paste(vector1, vector2, sep="\n")
# [1] "1\n1" "2\n2" "3\n3" "4\n4" "5\n5" "6\n6" "7\n7" "8\n8"
# [9] "9\n9" "10\n10"
source to share