gpt4 book ai didi

r - 无法使用R中的循环和函数更新向量

转载 作者:行者123 更新时间:2023-12-04 04:02:55 24 4
gpt4 key购买 nike

我是 R 的新手,我正在尝试使用函数和循环添加到向量 a 上。这是我的代码:

add_to_a <- function(num){
print (paste("This is a: ", paste(a,collapse =" ")))
for (i in 1:3){
a <- c(a,"hello")
}
}

a <- c()

for(i in 1:5){
a<- add_to_a(i)
}

我的输出是:

[1] "This is a:  "
[1] "This is a: "
[1] "This is a: "
[1] "This is a: "
[1] "This is a: "

我试图调试这个问题并添加了打印语句:

add_to_a <- function(num){
print (paste("This is a: ", paste(a,collapse =" ")))
for (i in 1:3){
a <- c(a,"hello")
}
print (a)
}

a <- c()
for(i in 1:5){
a<- add_to_a(i)
}

这是我的输出:

[1] "This is a:  "
[1] "hello" "hello" "hello"
[1] "This is a: hello hello hello"
[1] "hello" "hello" "hello" "hello" "hello" "hello"
[1] "This is a: hello hello hello hello hello hello"
[1] "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello"
[1] "This is a: hello hello hello hello hello hello hello hello hello"
[1] "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello"
[1] "This is a: hello hello hello hello hello hello hello hello hello hello hello hello"
[1] "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello"

并且 a 在最后按预期更新:

[1] "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello"

你能帮我理解为什么两种情况下的输出不同吗?

最佳答案

原因是变量的局部或全局定义。不需要该功能。注意 num 变量没有用。

这个解决方案应该有效:

a <- c()
for(i in 1:5){
print(paste("This is a: ", paste(a,collapse =" ")))
for (i in 1:3){
a <- c(a,"hello")
}
}

如果你想做类似的事情:

add_to_a <- function(a){
print(paste("This is a: ", paste(a, collapse =" ")))
for (i in 1:3){
a <- c(a, "hello")
}
return(a)
}

a <- c()
for(i in 1:5){
a <- add_to_a(a)
}

有关局部或全局变量的更完整解释,我建议您查看 this post .

关于r - 无法使用R中的循环和函数更新向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62819918/

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