[R] How to avoid the three loops in R?

ONKELINX, Thierry Thierry.ONKELINX at inbo.be
Fri Aug 1 15:40:19 CEST 2014


It is possible to do without loops if you start by calculating the totals. Then is just aggregating and merging data.

Best regards,

Thierry


set.seed(21)
n.country <- 5
average.price <- runif(n.country, max = 200)
price <- expand.grid(
  Product = 1:10,
  Country = factor(LETTERS[seq_len(n.country)]),
  Year = 2000:2010
)
price$Price <- rnorm(nrow(price), mean = average.price[price$Country], sd = 30)
#number and sum of all prices of the product over all countries and years
total.product <- aggregate(
  cbind(Price, N = 1) ~ Product,
  data = price,
  FUN = sum
)
#number and sum of all prices of the product per country over all years
total.product.country <- aggregate(
  cbind(Pricec = Price, Nc = 1) ~ Product + Country,
  data = price,
  FUN = sum
)
#merge both tables
combined.price <- merge(total.product, total.product.country)
with(combined.price, Price / N) #average price
with(combined.price, Pricec / Nc) #average price per country
with(combined.price, (Price - Pricec)/ (N - Nc)) #average price in the other countries



ir. Thierry Onkelinx
Instituut voor natuur- en bosonderzoek / Research Institute for Nature and Forest
team Biometrie & Kwaliteitszorg / team Biometrics & Quality Assurance
Kliniekstraat 25
1070 Anderlecht
Belgium
+ 32 2 525 02 51
+ 32 54 43 61 85
Thierry.Onkelinx op inbo.be
www.inbo.be

To call in the statistician after the experiment is done may be no more than asking him to perform a post-mortem examination: he may be able to say what the experiment died of.
~ Sir Ronald Aylmer Fisher

The plural of anecdote is not data.
~ Roger Brinner

The combination of some data and an aching desire for an answer does not ensure that a reasonable answer can be extracted from a given body of data.
~ John Tukey


-----Oorspronkelijk bericht-----
Van: r-help-bounces op r-project.org [mailto:r-help-bounces op r-project.org] Namens PIKAL Petr
Verzonden: vrijdag 1 augustus 2014 15:18
Aan: Lingyi Ma
CC: r-help op r-project.org
Onderwerp: Re: [R] How to avoid the three loops in R?

Hi

I do not see any solution without loops but maybe others find it.

I think that you can do it in one loop. Best structure for loop will be list.

In each cycle you will compute matrix with diagonal NA

mat<-matrix(1,nrow=number of items, ncol=number of items)
diag(mat) <- NA

apply(price chunk * mat, 2, mean, na.rm=T)


So when I named your example as temp I get

fac <- interaction(factor(temp$Product), factor(temp$Year_Month), drop=T) lll <- split(temp, fac) for( i in 1:length(lll)) {  mat <- matrix(1,  nrow=nrow(lll[[i]]), ncol= nrow(lll[[i]]))
 diag(mat) <- NA
 lll[[i]]$others <- apply(mat*lll[[i]][,3], 2, mean, na.rm=T)  }

> lll
$`1.201204`
  Country Product Price Year_Month others
1      AE       1    20     201204     24
2      DE       1    20     201204     24
3      CN       1    28     201204     20

$`2.201204`
  Country Product Price Year_Month others
4      AE       2    28     201204     25
5      DE       2    28     201204     25
6      CN       2    22     201204     28

$`3.201204`
  Country Product Price Year_Month others
7      AE       3    28     201204     28
8      CN       3    28     201204     28

$`1.201205`
   Country Product Price Year_Month others
9       AE       1    20     201205     24
10      DE       1    20     201205     24
11      CN       1    28     201205     20

$`2.201205`
   Country Product Price Year_Month others
12      AE       2    28     201205     28
13      DE       2    28     201205     28

I did not check speed but it shall be OK.

Regards
Petr

> -----Original Message-----
> From: r-help-bounces op r-project.org [mailto:r-help-bounces op r-
> project.org] On Behalf Of Lingyi Ma
> Sent: Friday, August 01, 2014 1:42 PM
> To: r-help op r-project.org
> Subject: [R] How to avoid the three loops in R?
>
> I have the following data set:
>
>   Country  Product   Price  Year_Month
>      AE         1           20    201204
>      DE         1           20    201204
>      CN         1           28    201204
>      AE         2           28    201204
>      DE         2           28    201204
>      CN         2           22    201204
>      AE         3           28    201204
>      CN         3           28    201204
>      AE         1           20    201205
>      DE         1           20    201205
>      CN         1           28    201205
>      AE         2           28    201205
>      DE         2           28    201205
>
> I want to create the one more column which is "The average price of
> the product in other areas".
> in other word, for each month, for each product, I calculate the
> average of such product in the other area.
>
> I want sth like:
>
>   Country  Product   Price  Year_Month    Price_average_In_Other_area
>      AE         1           20    201204              14
>      AE         2           28    201204              25
>
> Please avoid the three for loop, I have tried and it never end. I have
>  1070427 rows.  Is there better way to speed up my program?
>
>       [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help op 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.

________________________________
Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou určeny pouze jeho adresátům.
Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze svého systému.
Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či zpožděním přenosu e-mailu.

V případě, že je tento e-mail součástí obchodního jednání:
- vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, a to z jakéhokoliv důvodu i bez uvedení důvodu.
- a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany příjemce s dodatkem či odchylkou.
- trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným dosažením shody na všech jejích náležitostech.
- odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu případně osobě, kterou adresát zastupuje, předloženy nebo jejich existence je adresátovi či osobě jím zastoupené známá.

This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.

In case that this e-mail forms part of business dealings:
- the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
- if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
- the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
- the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.
______________________________________________
R-help op 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.
* * * * * * * * * * * * * D I S C L A I M E R * * * * * * * * * * * * *
Dit bericht en eventuele bijlagen geven enkel de visie van de schrijver weer en binden het INBO onder geen enkel beding, zolang dit bericht niet bevestigd is door een geldig ondertekend document.
The views expressed in this message and any annex are purely those of the writer and may not be regarded as stating an official position of INBO, as long as the message is not confirmed by a duly signed document.


More information about the R-help mailing list