R:保持For循环中的值 [英] R: Hold Values Generated in For Loop

查看:197
本文介绍了R:保持For循环中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉提出这个问题,但是我看起来相当困难,一直没有找到解决办法。



例如:

  myfunction <  -  function(x = 1:5){
for(in 1:length(x)){
r <-x [i]
}
print r)
}

如果我运行上面的代码, x,在这种情况下5.我知道这是因为我每次通过for循环覆盖r。

我也试过:



$ $ p $ myfunction< - function(x = 1:5){
for(i in 1:length(x)){
r [i]< -x [i]
}
print(r)
}

但是我还是得到了最后一个值。

我唯一的解决方案nd是指定在使用r <-numeric(length)之前保存生成值的变量的长度:

  myfunction <  - 函数(x = 1:5){
r< -numeric(5)
for(i in 1:length(x)){
r [i]< -x [i]
}
print(r)
}

但是,如果我不知道预先返回的向量的长度,这个解决方案显然是不够的。

感谢您的帮助!$ b

解决方案

你的循环只经过一次,它是与我=长度(X)。你可能想要

pre $ (我在seq(length(x))){
#code here


$或
$ b $(我在seq_along(x)){
#code here
}


I apologize for this question in advance, but I've looked pretty hard and haven't been able to find a solution.

How do I values generated by a for loop in a variable?

For example:

myfunction <- function(x=1:5) {
                for(i in 1:length(x)) {
                r<-x[i]
                }
                print(r)
              }

If I run the above code, I only get the last value for x, in this case 5. I understand that this is because I'm overwriting r each time through the for loop.

I've also tried:

myfunction <- function(x=1:5) {
                for(i in 1:length(x)) {
                r[i]<-x[i]
                }
                print(r)
              }

But I still just get the last value.

The only solution I've found is to specify the length of the variable that will hold the generated values before using r<-numeric(length):

myfunction <- function(x=1:5) {
                r<-numeric(5)
                for(i in 1:length(x)) {
                r[i]<-x[i]
                }
                print(r)
              }

But this solution will obviously be insufficient if I don't know the length of the vector to be returned beforehand.

Thanks for any help!

解决方案

Your loop only goes through once and it is with i = length(x). You probably want

for(i in seq(length(x))){
    # code here
}

# or

for(i in seq_along(x)){
    # code here
}

这篇关于R:保持For循环中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆