在 R 中使用 do 循环创建新变量 [英] Using do loops in R to create new variables

查看:51
本文介绍了在 R 中使用 do 循环创建新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直是 SAS 程序员,希望跳到 R.我知道 R 对于变量重新编码并不是那么好,但是有没有办法用 do 循环来做到这一点.

I'm a long time SAS programmer looking to make the jump to R. I know R isn't all that great for variable re-coding but is there a way to do this with do loops.

如果我有很多名为 a_1 a_2...a_100、b_1 b_2 ... b_100 的变量,并且我想创建新变量 c_1 c_2 ... c_100,其中 c_i = a_i + b_i.有没有办法在没有 100 条语句的情况下做到这一点?

If I have a lot of variables named a_1 a_2...a_100, b_1 b_2 ... b_100 and I want to create new variables c_1 c_2 ... c_100 where c_i = a_i + b_i. Is there a way to do this without 100 statements?

在 SAS 中,我会简单地使用:

In SAS I would simply use:

%do i=1 %to 100;
c_&i = a_&i + b_&i;
%end;

谢谢!

推荐答案

SAS 使用一种基本的宏语言,它依赖于文本替换,而不是像任何适当的编程语言那样对表达式求值.您的 SAS 文件本质上是两件事:SAS 命令和宏表达式(以%"开头的内容).宏语言问题很大,很难调试(例如,表达式中的表达式是否被扩展?为什么必须执行&&x"甚至&&&x"?为什么需要两个这里是分号?).与基于单一语法的精心设计的编程语言相比,它既笨拙又不优雅.

SAS uses a rudimentary macro language, which depends on text replacement rather than evaluation of expressions like any proper programming language. Your SAS files are essentially two things: SAS commands, and Macro expressions (things starting with '%'). Macro languages are highly problematic and hard to debug (for example, do expressions within expressions get expanded? Why do you have to do "&&x" or even "&&&x"? Why do you need two semicolons here?). It's clunky, and inelegant compared to a well-designed programming language that is based on a single syntax.

如果您的 a_i 变量是单个数字,那么您应该将它们设为向量 - 例如:

If your a_i variables are single numbers, then you should have made them as a vector - e.g:

> a = 1:100
> b = runif(100)

现在我可以轻松获取元素了:

Now I can get elements easy:

> a[1]

并并行相加:

> c = a + b

你可以用循环来做,先初始化 c:

You could do it with a loop, initialising c first:

> c = rep(0,100)
> for(i in 1:100){
   c[i]=a[i]+b[i]
   }

但这太慢了.

几乎每个 R 初学者都会问如何为 i 的某些值创建变量 a_i",然后不久之后他们又问如何访问变量 a_i 以获得 i 的某些值.答案总是将 a 作为向量或列表.

Nearly every R beginner asks 'how do I create a variable a_i for some values of i', and then shortly afterwards they ask how to access variable a_i for some values of i. The answer is always to make a as either a vector or a list.

这篇关于在 R 中使用 do 循环创建新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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