Re: [R] 'apply' with additional class variable

From: Joshua Wiley <>
Date: Sat, 21 May 2011 11:57:13 -0700

Hi Mark,

Is there a reason you cannot simply include the make of the car along with all the other data? Using your example:

cbind(, carmake)

then instead of applying across columns, apply across rows, and have your custom function decide what to do based on the column named "carmake". Alternately, if you will be dealing with the same makes of cars a lot and are willing to do something a bit more involved, you could consider defining custom classes for each car make, make your function generic, and then create methods for it to match the different car makes.



On Sat, May 21, 2011 at 11:23 AM, Mark Ebbert <> wrote:
> Dear R gurus,
> I'm trying to solve what I assume is a fairly simple problem, but I'm having trouble finding the proper approach. I have a matrix where each column is some object (e.g. a car) and each row is a numeric measurement of a feature of said object (e.g. horse power, top speed, etc.). Let's also suppose that I know what make the car is (e.g. toyota, ford, etc.), stored in a separate vector. What I want to do is apply a custom function over each column of this matrix, but the function will behave differently depending on the make of the car, so each time a column is passed into my custom function, the function needs to know the make of the car. What I imagine being able to do is something like this:
> carmake<-c("Toyota","Ford","Chevy")
> x<-matrix(1:12,nrow=4)
> colnames(x)<-c("Car1","Car2","Car3")
> rownames(x)<-c("Horsepower","TopSpeed","Weight","Cost")
> res<-apply(my_matrix,2,my_func,carmake)
> The obvious problem with this is that I cannot know which column 'my_func' is working on, in order to know which column to get the car make from. I then thought I could try and match on column name, but when the column is passed into 'my_func' it loses the column name.
> Anyway, I hope that made sense. I appreciate any help you may offer!
> Mark T. W. Ebbert
> ______________________________________________
> mailing list
> PLEASE do read the posting guide
> and provide commented, minimal, self-contained, reproducible code.

Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Sat 21 May 2011 - 18:59:17 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 21 May 2011 - 20:40:09 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive