Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

sas - Using do loops in R to create new variables

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.

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?

In SAS I would simply use:

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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]

and add up in parallel:

> c = a + b

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]
   }

But that would be sloooooow.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...