print at each iteration lapply so output is between list elements

Viewed 229

Seems a rudimentary question. Is there a way to print() or message() between iterations of a function so that the print is between the list elements in the console output. Example:

two_sq <- function (x) {
  print(paste("this is ", x))
  x^2
}
lapply(1:3, two_sq)

Gives:

    # [1] "this is  1"
    # [1] "this is  2"
    # [1] "this is  3"
    # [[1]]
    # [1] 1

    # [[2]]
    # [1] 4

    # [[3]]
    # [1] 9

Desired output:

# [1] "this is  1"

# # [[1]]
# # [1] 1

# [2] "this is  2"

# # [[2]]
# # [1] 4

# [3] "this is  3"

# # [[3]]
# # [1] 9
2 Answers

We can use a for loop

for(i in 1:3) two_sq(i)
#[1] "this is  1"
#[1] 1
#[1] "this is  2"
#[1] 4
#[1] "this is  3"
#[1] 9

where

two_sq <- function (x) {
    print(paste("this is ", x))
    print(x^2)
}
two_sq <- function (x) {
    print(paste("this is ", x))
    print(x^2)
}
invisible(lapply(1:3, two_sq))

# [1] "this is  1"
# [1] 1
# [1] "this is  2"
# [1] 4
# [1] "this is  3"
# [1] 9
Related