Using do loops in R to create new variables

前端 未结 6 1817
别那么骄傲
别那么骄傲 2020-12-20 00:56

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

6条回答
  •  旧时难觅i
    2020-12-20 01:52

    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.

提交回复
热议问题