gpt4 book ai didi

r - R中打印和返回的区别?

转载 作者:行者123 更新时间:2023-12-01 22:25:20 24 4
gpt4 key购买 nike

我已经定义了一个阶乘函数。脚本是这样的:

fac <- function(x) {
f=1
for (i in 1:x) {
f = f * i
print(f)
}
print(f)
}

如果 fac(5),则输出如下所示:

[1] 1
[1] 2
[1] 6
[1] 24
[1] 120
[1] 720
[1] 5040

但是当我将“print(f)”部分更改为“return(f)”时,输出是:

[1] 1

为什么会这样? R 中的 print 和 return 有区别吗?

最佳答案

让我们举个例子:

fac <- function(x) {
f=1
for (i in 1:x) {
f = f * i
print(f)
}
print(f)
}

fac2 <- function(x) {
f=1
for (i in 1:x) {
f = f * i
print(f)
}
return(f)
}

fac3 <- function(x) {
f=1
for (i in 1:x) {
f = f * i
return(f)
}
print(f)
}

并使用它们:

> f1 <- fac(10)
[1] 1
[1] 2
[1] 6
[1] 24
[1] 120
[1] 720
[1] 5040
[1] 40320
[1] 362880
[1] 3628800
[1] 3628800
> f2 <- fac2(10)
[1] 1
[1] 2
[1] 6
[1] 24
[1] 120
[1] 720
[1] 5040
[1] 40320
[1] 362880
[1] 3628800
> f3 <- fac3(10)
> f1
[1] 3628800
> f2
[1] 3628800
> f3
[1] 1

print 顾名思义,打印到控制台(并返回打印的值)

return 只返回值并结束函数。

fac(10) 的情况下,最后一个 printf 的最后一个值,它返回它,如 fac2(10) 的不同之处在于它不会打印两次,因为循环中只有 print 打印值。

fac3(10) 在第一次迭代时返回,因此它永远不会转到 print 语句并返回第一个值而不向控制台打印任何内容。

您可以为此做的是:

fixedfac <- function(x) {
f=vector('numeric',x) # pre allocate the return vector to avoid copy while growing in the loop
tmp=1 # use a temp var for the maths (could be avoided, but it's to keep it simple)
for (i in 1:x) {
tmp <- tmp * i # do the math
f[i] <- tmp # store in result
}
f # return the vector with all values (we need at least this as for does not return anything).
}

它将返回一个向量(return 是不必要的,因为函数总是返回其最后一条语句的值)

> fixedfac(10)
[1] 1 2 6 24 120 720 5040 40320 362880 3628800

关于r - R中打印和返回的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35773027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com