[R] assign object with loop (translation from SAS to R)

David Winsemius dwinsemius at comcast.net
Fri Jun 29 16:18:03 CEST 2012


On Jun 28, 2012, at 9:18 PM, lynx wrote:

> I have a dataset named DM with p1, p2, ...., p9 (9 columns,  
> numerical values)
> I would like to calculate to multify each pair of columns (p1p2,  
> p1p3,...
> p1p9, p2p3, p2p4.... p8p9) and assign them in p1p2, p1p3,... p1p9,  
> p2p3,
> p2p4.... p8p9
>
> In SAS,
>
> l=0;
> p_int_sum=0;	
> do i=1 to 8;
> 	do j=(i+1) to 9;
> 	l=l+1;
> 	p{i}p{j}=p{i}*p{j};
> 	end;
> end;
>
> I would like to know how to assign them in R
> I tried for function but failed.
> for (i in 1:8) {
> for (j in 2:9) {
# Try instead:

DM[[ paste("p",i, "p",j,sep="") ]] <-
           DM[[paste("p",i, sep="")]] * DM[[paste("p",i, sep="")]]

> DM$p[i]p[j] <- DM$p[i] * DM$p[j]
>
> }}

I suspect there is a more elegant method than this use of R as a macro  
processor. I tested the above approach with suitably smalled  
subscripts on a smaller dataset:

DM <- data.frame(p1=1:10,p2=1:10,p3=1:10,p4=1:10,p5=1:10)


-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list