[R] assign object with loop (translation from SAS to R)
Rui Barradas
ruipbarradas at sapo.pt
Fri Jun 29 10:02:22 CEST 2012
Hello,
See inline.
Em 29-06-2012 02:18, lynx escreveu:
> 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;
>
In R this sort of syntax doesn't work, the trick is to create the
variable where to hold the rsult beforehand and use vectors.
DM <- data.frame(p=1:9)
DM$prod <- NA # create results variable
i <- 2:9 # use a vector to index DM$p
DM$prod[i] <- DM$p[i - 1]*DM$p[i]
DM
Hope this helps,
Rui Barradas
> 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) {
> DM$p[i]p[j] <- DM$p[i] * DM$p[j]
>
> }}
>
> Thank you so much for reading this!
>
> --
> View this message in context: http://r.789695.n4.nabble.com/assign-object-with-loop-translation-from-SAS-to-R-tp4634806.html
> Sent from the R help mailing list archive at Nabble.com.
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list