[R] matrix with Loop

R. Michael Weylandt michael.weylandt at gmail.com
Thu Mar 29 20:16:01 CEST 2012


apply() will hit all the rows/columns at once so you don't need the
loop construct at all.

E.g.,

x <- matrix(rnorm(20), ncol = 5)

## One Line
y1 <- apply(x, 1, mean)

## Or Four
y2 <- numeric(nrow(x))
for(i in 1:nrow(x)){
   y2[i] <- mean(x[i,])
}

## But they're the same

identical(y1, y2) # TRUE

Does that clarify things?
Michael

On Thu, Mar 29, 2012 at 12:25 PM, Christopher Kelvin
<chris_kelvin2001 at yahoo.com> wrote:
> Please, can you be a little specific for me about where to inside your suggestion to make the code complete complete. I have tried it but i am getting errors.
> Thank you
> Chris Kelvin
>
>
> ----- Original Message -----
> From: R. Michael Weylandt <michael.weylandt at gmail.com>
> To: Christopher Kelvin <chris_kelvin2001 at yahoo.com>
> Cc: "r-help at r-project.org" <r-help at r-project.org>
> Sent: Thursday, March 29, 2012 11:33 PM
> Subject: Re: [R] matrix with Loop
>
> apply(x, 1, mean)
> apply(x, 2, median)
>
> or for more speed rowMeans()
>
> ? apply
>
> Michael
>
> On Thu, Mar 29, 2012 at 9:00 AM, Christopher Kelvin
> <chris_kelvin2001 at yahoo.com> wrote:
>> Hello!
>> I got something to ask..whether you can help me with the R program...i got this for example 5x4 matrix..and i want to find:
>>  i) mean for each row of the matrix
>> ii) median for each column of the matrix
>> and i need to do this using a loop function...below is my program..u try to check it for me as the output that i got is not what i desired...thanks..
>>
>> data<-rnorm(20,0,1)
>> dim(data)<-c(5,4)
>> is.matrix(data)
>> data
>> a<-function(x)
>> {
>> for(i in 1:nrow(x))
>> {
>> for(j in 1:ncol(x))
>> {
>> med<-median(x[,j])
>> mean<-mean(x[i,])
>> print(c(med=med,mean=mean))
>> }
>> }
>> }
>> a(data)
>>
>> Chris Guure
>> Researcher
>> Institute for Mathematical Research
>> UPM
>>
>> ______________________________________________
>> 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