在每次迭代时打印 lapply 所以输出在列表元素之间
print at each iteration lapply so output is between list elements
似乎是一个基本问题。有没有办法在函数的迭代之间 print()
或 message()
以便打印位于控制台输出中的列表元素之间。示例:
two_sq <- function (x) {
print(paste("this is ", x))
x^2
}
lapply(1:3, two_sq)
给出:
# [1] "this is 1"
# [1] "this is 2"
# [1] "this is 3"
# [[1]]
# [1] 1
# [[2]]
# [1] 4
# [[3]]
# [1] 9
期望输出:
# [1] "this is 1"
# # [[1]]
# # [1] 1
# [2] "this is 2"
# # [[2]]
# # [1] 4
# [3] "this is 3"
# # [[3]]
# # [1] 9
我们可以使用 for
循环
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
哪里
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
似乎是一个基本问题。有没有办法在函数的迭代之间 print()
或 message()
以便打印位于控制台输出中的列表元素之间。示例:
two_sq <- function (x) {
print(paste("this is ", x))
x^2
}
lapply(1:3, two_sq)
给出:
# [1] "this is 1"
# [1] "this is 2"
# [1] "this is 3"
# [[1]]
# [1] 1
# [[2]]
# [1] 4
# [[3]]
# [1] 9
期望输出:
# [1] "this is 1"
# # [[1]]
# # [1] 1
# [2] "this is 2"
# # [[2]]
# # [1] 4
# [3] "this is 3"
# # [[3]]
# # [1] 9
我们可以使用 for
循环
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
哪里
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