Using do loops in R to create new variables

前端 未结 6 1828
别那么骄傲
别那么骄傲 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条回答
  •  清酒与你
    2020-12-20 02:00

    This stuff is trivial. To me, it looks like you want to find a way to create commands automatically and execute them. Easy peasy.

    For instance, this assigns to C_i the value in A_i:

    for(i in 1:100){
        tmpCmd = paste("C_",i,"= A_",i, sep = "")
        eval(parse(text = tmpCmd))
    }
    rm(i, tmpCmd)
    

    Just remember eval(parse(text = ...))) and paste(), and you're off to the races in creating loops of commands to execute.

    You can then add in the operation you'd like to do, i.e. the summation with B_i, by swapping in this line:

        tmpCmd = paste("C_",i,"= A_",i," + B_",i, sep = "")
    

    However, others are right that using good data structures is a way to avoid having to do a lot of tedious things like this. Yet, when you need to, such repetitive code isn't hard to devise.

提交回复
热议问题