我想输出这个:
This is the text [1] from process
This is the text [2] from process
This is the text [3] from process
如何使用for循环创建它?我尝试了什么:
for (i in 1:3) {
query_line<- "This is the text["+i+"]from process"
}
错误是:
Error in "This is the text[" + i : non-numeric argument to binary operator
答案 0 :(得分:1)
您可以使用?cat
:
for (i in 1:3) {
cat("This is the text [", i, "] from process\n")
}
#This is the text [ 1 ] from process
#This is the text [ 2 ] from process
#This is the text [ 3 ] from process
如果您只想将其存储在变量中,可以执行以下操作(不要忘记提前初始化存储变量):
n <- 3
res <- character(n)
for (i in 1:n) {
res[i] <- paste("This is the text [", i, "] from process")
}
然后,结果存储在res
:
res
#[1] "This is the text [ 1 ] from process" "This is the text [ 2 ] from process"
#[3] "This is the text [ 3 ] from process"
但是,如果您真的只想创建一个包含该文本的字符向量,则可以在一次paste
调用中执行此操作:
paste("This is the text [", 1:3, "] from process")
#[1] "This is the text [ 1 ] from process" "This is the text [ 2 ] from process"
#[3] "This is the text [ 3 ] from process"
答案 1 :(得分:1)
您还可以使用生成诊断消息的message
函数。它以红色显示。
for (i in 1:5)
message(paste("This is the text [",i,"] from process",sep=""))