[R] using apply to loop [SEC=UNCLASSIFIED]

Crombie, Joe Joe.Crombie at brs.gov.au
Fri Dec 21 04:47:13 CET 2007


Hi Louis,

You could try this:

# find the index of the maximum value in each row of _data_, #
disregarding the last column classified <-
apply(data[,-(nclass+1)],1,which.max)

## or, if the maximum may be repeated:
classified <- apply(data[,-(nclass+1)], 1, FUN = function(x) which(x ==
max(x)))

# the variable _truth_ is just the last column of _data_ ?
truth <- data[,nclass + 1]

?table
z <- table(classified, truth)


HTH  Joe

 
Joe Crombie
 
Biosecurity and Information Sciences
Bureau of Rural Science
Canberra  Australia
 
e: joe.crombie at brs.gov.au
 

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of Louis Martin
Sent: Friday, 21 December 2007 11:37 AM
To: R-help at r-project.org
Subject: [R] using apply to loop

Hi,

I am running the following loop, but it takes hours to run as n is big.
Is there any way "apply" can be used? Thanks.
### Start
    nclass <- dim(data)[[2]] - 1
    z <- matrix(0, ncol = nclass, nrow = nclass)
    n <- dim(data)[[1]]
    x <- c(1:nclass)
# loop starts
for(loop in 1:n) {
        r <- data[loop, 1:nclass]
        classified <- x[r == max(r)]
       
        truth <- data[loop, nclass + 1]
        z[classified, truth] <- z[classified, truth] + 1
    }
# loop ends


             
---------------------------------

	[[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.

------IMPORTANT - This message has been issued by The Department of Agriculture, Fisheries and Forestry (DAFF). The information transmitted is for the use of the intended recipient only and may contain confidential and/or legally privileged material. It is your responsibility to check any attachments for viruses and defects before opening or sending them on. 

Any reproduction, publication, communication, re-transmission, disclosure, dissemination or other use of the information contained in this e-mail by persons or entities other than the intended recipient is prohibited. The taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you have received this e-mail in error please notify the sender and delete all copies of this transmission together with any attachments. If you have received this e-mail as part of a valid mailing list and no longer want to receive a message such as this one advise the sender by return e-mail accordingly. Only e-mail correspondence which includes this footer, has been authorised by DAFF 
------



More information about the R-help mailing list