如何使用循环创建一个字符串的向量? [英] How to create a vector of character strings using a loop?
问题描述
我试图使用循环在R中创建一个字符串的向量,但我有一些麻烦。我非常感谢任何人都能提供帮助。
I am trying to create a vector of character strings in R using a loop, but am having some trouble. I'd appreciate any help anyone can offer.
我使用的代码有点详细,但我已经尝试编写一个可重复的示例捕获所有关键位:
The code I'm working with is a bit more detailed, but I've tried to code a reproducible example here which 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")
}
如下:
1
1
Error in thing[i] <- cat(line1, line2, sep = "\n") :
replacement has length zero
我想实现的是一个字符向量,其中每个字符分成两行,使 thing [1]
是
What I'm trying to achieve is a character vector where each character is split over two lines, such that thing[1]
is
1
1
和 thing [2]
是
2
2
等。有谁知道我怎么能这样做?
and so on. Does anyone know how I could do this?
推荐答案
cat
打印到屏幕, $ c> NULL - 要连接到一个新的字符向量,您需要使用粘贴
:
cat
prints to the screen, but it returns NULL
- to concatenate to a new character vector, you need to use paste
:
thing[i]<-paste(line1,line2,sep="\n")
例如在交互式终端中:
> line1 = "hello"
> line2 = "world"
> paste(line1,line2,sep="\n")
[1] "hello\nworld"
> ret <- cat(line1,line2,sep="\n")
hello
world
> ret
NULL
虽然注意到在你的情况下,整个for循环可以被替换具有更简洁和高效的行:
Though note that in your case, the entire for loop could just be replaced with the more concise and efficient line:
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"
这篇关于如何使用循环创建一个字符串的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!