[R] use 'lapply' to creat 2 new columns based on old ones in a data frame

runner sunnyside500 at gmail.com
Sat Oct 13 01:46:02 CEST 2007

There is a dataset 'm', which has 3 columns: 'index', 'old1' and 'old2';

I want to create 2 new columns: 'new1' and 'new2' on this condition: 
if 'index'==i, then 'new1'='old1'+add[i].
'add' is a vector of numbers to be added to old columns, e.g. add=c(10,20,30
Like this:

index	    old1	    old2	    new1	    new2
1	    	    5	    	    6	    	    15	    	    16
2	    	    5	    	    6	   	      25	    	    26
3	    	    5	    	    6	    	    35	    	    36
3	    	    50	    	   60	    	   80	    	   90

Since the actual dataset is huge, I use 'lapply'. I am able to add 1 column:

do.call(rbind, lapply( 1:nrow(m), 
                            function(i) {m$new1[i]=m[i,2]+add[m[i,1]];
return (m[i,])} 

but don't know how to do for 2 columns at the same time, sth. like this
simply doesn't work:
                          function(i){ m$new1[i]=m[i,2]+add[m[i,1]]; 
                                          return (m[i,])}
Could you please tell me how? or any other better approach?

View this message in context: http://www.nabble.com/use-%27lapply%27-to-creat-2-new-columns-based-on-old-ones-in-a-data-frame-tf4616650.html#a13184905
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list