Как напечатать объединенную строку результат каждой итерации цикла в R - PullRequest
0 голосов
/ 02 февраля 2019

Это кодовые слова, как и предполагалось в 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 голосов
/ 02 февраля 2019

Вам просто нужно 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"     
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...