1

This code words as intended in 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')

Output is:

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

Whereas in R, how to get the same output? My code in R as below:

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')

The output I get is: [1] "No more books in the shelf"

Is there a different function to use within a for loop?

2
  • Is there a reason why we need to use paste inside a print function in a loop? In this code it works fine as a standalone: weather_report <- function(Cel = as.numeric(readline('Enter the temperature in C:'))){ F = Cel*1.8 + 32 if(F > 90){ ans <- 'It\'s too hot' print(ans) } else{ ans <- 'It\'s not too hot' print(ans) } paste('Temperature in F =',F) } Commented Feb 2, 2019 at 4:26
  • 1
    If you need to concatenate different objects together you need to use paste and since it does not automatically print in for loop, you need to explicitly mention that as well. In the function above there is no for loop, hence paste works fine. Commented Feb 2, 2019 at 4:32

1 Answer 1

1

You just need to print the paste part as it is in the loop. In loop you have to explicitly tell to print the things.

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"

However, let me show you the magic of R. You can avoid the loop by doing

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"     
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.