Using do loops in R to create new variables

前端 未结 6 1829
别那么骄傲
别那么骄傲 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

    The R way would be to use lists.

    > a_1 = 1
    > a_2 = 2
    > a_3 = 3
    > a_4 = 4
    > a_5 = 5
    
    > b_1 = 1
    > b_2 = 2
    > b_3 = 3
    > b_4 = 4
    > b_5 = 5
    
    > a.list <- ls(patter='a_*')
    > a.list
    [1] "a_1" "a_2" "a_3" "a_4" "a_5"
    

    and define blist as well.

    if(length(a.list)==length(b.list)){
       c.list <- lapply(1:length(a.list), function(x) eval(parse(text=a.list[x])) + eval(parse(text=b.list[x])))
    
       c.list.names <- paste('c', 1:length(a.list), sep='_')
    
       lapply(1:length(c.list), function(x) assign(c.list.names[x], c.list[x], envir=.GlobalEnv)) 
    }
    

    I can't think of a way to do this without the eval(parse(yuk)) and assign unless you follow csgillespie's advice (which is the right way!)

提交回复
热议问题