如何在R中为每个for循环迭代打印连接字符串的结果

时间:2019-02-02 04:20:46

标签: r for-loop

此代码字符合Python的意图

my_books = ['R','Python','SQL','Java','C']

cou = 0
for i in my_books:
    cou = cou + 1
    print('Book Number:',cou,'&','Name of the book:',i)
print('\nNo more books in the shelf')

输出为:

Book Number: 1 & Name of the book: R
Book Number: 2 & Name of the book: Python
Book Number: 3 & Name of the book: SQL
Book Number: 4 & Name of the book: Java
Book Number: 5 & Name of the book: C

No more books in the shelf

在R中,如何获得相同的输出? 我在R中的代码如下:

my_books = c('R','Python','SQL','Java','C')

cou = 0
for(i in my_books){
  cou = cou + 1
  paste('Book Number:',cou,'&','Name of the book:',i)
}
print('No more books in the shelf')

我得到的输出是:     [1]“书架上不再有书”

在for循环中是否可以使用其他功能?

1 个答案:

答案 0 :(得分:1)

您只需要print paste部分就可以了。在循环中,您必须明确告知print事情。

my_books = c('R','Python','SQL','Java','C')

cou = 0
for(i in my_books){
  cou = cou + 1
  print(paste('Book Number:',cou,'&','Name of the book:',i))
}


#[1] "Book Number: 1 & Name of the book: R"
#[1] "Book Number: 2 & Name of the book: Python"
#[1] "Book Number: 3 & Name of the book: SQL"
#[1] "Book Number: 4 & Name of the book: Java"
#[1] "Book Number: 5 & Name of the book: C"

但是,让我向您展示R的魔力。这样做可以避免循环

paste('Book Number:', seq_along(my_books), '& Name of the book:', my_books)

#[1] "Book Number: 1 & Name of the book: R"     
#[2] "Book Number: 2 & Name of the book: Python"
#[3] "Book Number: 3 & Name of the book: SQL"   
#[4] "Book Number: 4 & Name of the book: Java"  
#[5] "Book Number: 5 & Name of the book: C"