如何从循环内部向现有变量添加值? [英] how to add value to existing variable from inside a loop?

查看:64
本文介绍了如何从循环内部向现有变量添加值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从循环中向现有向量中添加一个计算值,在该循环中从循环中调用所需向量.我正在寻找的是一个类似于Assign()函数的函数,但是它将使我能够将值添加到现有变量中而不创建新变量.

I want to add a computed value to an existing vector from within a loop in which the wanted vector is called from within the loop . that is im looking for some function that is similar to assign() function but that will enable me to add values to an existing variables and not creating new variables.

示例: 说我有3个变量:

example: say I have 3 variabels :

sp=3
for(i in 1:sp){
    name<-paste("sp",i,sep="")
    assign(name,rnorm(5))
}

现在我要访问每个变量中的最后一个值,将其加倍,然后将重新添加到向量中:

and now I want to access the last value in each of the variabels, double it and add the resault to the vector:

for(i in 1:sp){
    name<-paste("sp",i,sep="")
    name[6]<-name[5]*2
}

这里的问题是名称"是一个字符串,R如何将其识别为真实名称并访问它?

the problem here is that "name" is a string, how can R identify it as a veriable name and access it?

推荐答案

您要的是这样的东西:

get(name)

在您的代码中,它是这样的:

In your code it would like this:

v <- 1:10
var <- "v"

for (i in v){
  tmp <- get(var)
  tmp[6] <- tmp[5]*2
  assign(var, tmp)
}
# [1]  1  2  3  4  5 10  7  8  9 10

这对您有任何帮助吗?

Does that help you in any way?

但是,我同意另一个答案,那就是列表和lapply/sapply函数更适合!

However, I agree with the other answer, that lists and the lapply/sapply-functions are better suited!

这篇关于如何从循环内部向现有变量添加值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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